Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
tuning: job contract, history, apply/rollback and the real-API measurement harness
Niko122148fc04a425df
diff --git a/strata_control/tune_api.py b/strata_control/tune_api.pynew file mode 100644index 000000000..a15d65758--- /dev/null+++ b/strata_control/tune_api.py@@ -0,0 +1,284 @@+"""Measure a configuration through the API the agent actually uses.++`tune_engine.EngineHarness` measures the engine's own serve protocol, which is fast and precise and+answers "how fast can this configuration decode". It does **not** answer "is this configuration+better for a user", because the user's requests arrive over HTTP, go through the worker's queueing,+prompt handling and streaming, and it is that whole path whose latency matters.++Checklist T04 asks for the full API/Harness workload and for memory, so this module provides it. The+two modes are deliberately separate rather than one replacing the other:++* ``protocol`` is cheap enough to run for every candidate in a sweep;+* ``api`` is the confirmation, run against the finalists and against the exported configuration.++Reporting one as the other would be the same class of error as a fixture result standing in for real+inference, so every measurement carries the mode that produced it and the report shows the mode.++What this measures, per request: time to first token (from the first streamed content frame, which is+what a user waits for), end-to-end duration, token counts taken from the server's own usage block+rather than counted here, and the peak resident memory of the server process tree. The prompt and the+expectation are supplied by the caller, and the response is checked against the expectation, because+a configuration that answers faster and wrongly is not an improvement.+"""++from __future__ import annotations++import json+import re+import subprocess+import sys+import time+import urllib.error+import urllib.request+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from strata_control.tune_engine import EngineMeasurement, MeasurementError, process_tree_peak_mib+++class ApiHarness:+ """Start the worker with one configuration and measure a real chat completion.++ The server is started as a child process and stopped afterwards: a configuration that changes the+ KV layout or the expert cache cannot be assumed to take effect in a running server, and reusing+ one would silently measure the previous candidate.+ """++ def __init__(self, *, python: Path | str, serve_dir: Path, config_path: Path,+ port: int = 8123, host: str = "127.0.0.1", boot_timeout_s: float = 900.0,+ request_timeout_s: float = 900.0, env: dict[str, str] | None = None,+ engine: str = "strata") -> None:+ self.python = str(python)+ # `strata` is the real engine; `mock` is the scripted one, and a measurement taken against it+ # is a test of this harness and never a performance result.+ self.engine = engine+ self.serve_dir = Path(serve_dir)+ self.config_path = Path(config_path)+ self.port = int(port)+ self.host = host+ self.boot_timeout_s = boot_timeout_s+ self.request_timeout_s = request_timeout_s+ self.env = env+ self._proc: subprocess.Popen | None = None+ self._log = None++ # ------------------------------------------------------------------ lifecycle++ @property+ def url(self) -> str:+ return f"http://{self.host}:{self.port}"++ def _argv(self) -> list[str]:+ # The worker's own spelling. `--profile` is the terminal launcher's flag, not this one, and+ # passing it made the worker exit 2 with a usage message before it ever bound a port.+ return [self.python, "-m", "serve.server", "--engine", self.engine,+ "--config", str(self.config_path),+ "--host", self.host, "--port", str(self.port)]++ def start(self) -> None:+ import tempfile+ self._log = tempfile.NamedTemporaryFile(prefix="strata-api-harness-", suffix=".log",+ delete=False)+ try:+ self._proc = subprocess.Popen(self._argv(), cwd=str(self.serve_dir), env=self.env,+ stdout=self._log, stderr=subprocess.STDOUT)+ except OSError as e:+ raise MeasurementError(f"the worker could not be started: {e}") from e++ deadline = time.monotonic() + self.boot_timeout_s+ while time.monotonic() < deadline:+ if self._proc.poll() is not None:+ raise MeasurementError(+ f"the worker exited with code {self._proc.returncode} before becoming ready"+ + self._log_tail())+ try:+ with urllib.request.urlopen(f"{self.url}/health", timeout=2) as response:+ if response.status == 200:+ return+ except (urllib.error.URLError, OSError):+ time.sleep(0.2)+ raise MeasurementError(f"the worker did not answer /health within {self.boot_timeout_s:.0f}s"+ + self._log_tail())++ def _log_tail(self, limit: int = 500) -> str:+ if self._log is None:+ return ""+ try:+ text = Path(self._log.name).read_text(encoding="utf-8", errors="replace")+ return f"; log: {text[-limit:].strip()}" if text.strip() else ""+ except OSError:+ return ""++ def close(self) -> None:+ if self._proc is not None and self._proc.poll() is None:+ self._proc.terminate()+ try:+ self._proc.wait(timeout=20)+ except subprocess.TimeoutExpired:+ self._proc.kill()+ self._proc = None+ if self._log is not None:+ try:+ self._log.close()+ except OSError:+ pass++ def __enter__(self) -> "ApiHarness":+ self.start()+ return self++ def __exit__(self, *exc: object) -> None:+ self.close()++ # ------------------------------------------------------------------ measuring++ def measure(self, *, prompt: str, max_new: int, expect: str | None = None,+ temperature: float = 0.0, seed: int = 1,+ model: str = "strata-local") -> EngineMeasurement:+ """One streamed chat completion, measured end to end.++ `expect` is a regular expression the answer must match for the run to count as correct. A+ configuration that is fast and wrong must not be able to win a sweep, so a mismatch raises+ rather than being recorded as a fast result.+ """+ body = json.dumps({+ "model": model, "stream": True, "max_tokens": max_new,+ "temperature": temperature, "seed": seed,+ "messages": [{"role": "user", "content": prompt}],+ }).encode("utf-8")+ request = urllib.request.Request(+ f"{self.url}/v1/chat/completions", data=body,+ headers={"content-type": "application/json", "authorization": "Bearer strata-local"},+ method="POST")++ started = time.monotonic()+ # Reasoning models stream their thinking into `reasoning_content` and the answer into+ # `content`. Measuring only `content` reports "no content" for a reasoning model and, worse,+ # moves the first-token time to whenever the thinking finished -- so a configuration that+ # thinks longer would look faster. Both are output, and the first of either is the wait.+ text_parts: list[str] = []+ reasoning_parts: list[str] = []+ first_token_at: float | None = None+ usage: dict[str, Any] = {}+ finish: str | None = None+ try:+ with urllib.request.urlopen(request, timeout=self.request_timeout_s) as response:+ for raw in response:+ line = raw.decode("utf-8", errors="replace").strip()+ if not line.startswith("data:"):+ continue+ payload = line[5:].strip()+ if payload == "[DONE]":+ break+ try:+ frame = json.loads(payload)+ except json.JSONDecodeError:+ continue+ if frame.get("error"):+ raise MeasurementError(+ f"the worker reported an error: {frame['error'].get('message')}")+ if frame.get("usage"):+ usage = frame["usage"]+ choice = (frame.get("choices") or [{}])[0]+ delta = choice.get("delta") or {}+ piece = delta.get("content") or delta.get("reasoning_content")+ if piece:+ if first_token_at is None:+ first_token_at = time.monotonic()+ if delta.get("content"):+ text_parts.append(delta["content"])+ else:+ reasoning_parts.append(delta["reasoning_content"])+ if choice.get("finish_reason"):+ finish = choice["finish_reason"]+ except urllib.error.HTTPError as e:+ detail = e.read().decode("utf-8", errors="replace")[:400]+ raise MeasurementError(f"the worker refused the request ({e.code}): {detail}") from None+ except (urllib.error.URLError, OSError) as e:+ raise MeasurementError(f"the request failed: {e}" + self._log_tail()) from None++ duration_ms = (time.monotonic() - started) * 1000.0+ answer = "".join(text_parts)+ reasoning = "".join(reasoning_parts)+ if not answer and not reasoning:+ raise MeasurementError("the worker streamed no content and no reasoning")+ # The expectation is checked against the answer when there is one, and against the reasoning+ # otherwise: an engine that only streams reasoning is still producing checkable output.+ checked = answer or reasoning+ if expect is not None and not re.search(expect, checked, re.IGNORECASE | re.DOTALL):+ raise MeasurementError(+ f"the output did not match the expectation {expect!r}, so this configuration is not "+ f"correct: {checked[:200]!r}")+ if not answer:+ raise MeasurementError(+ "the worker streamed reasoning but no answer, so its rate is not a generation rate: "+ f"{reasoning[:120]!r}")++ out_tokens = usage.get("completion_tokens")+ if not isinstance(out_tokens, int) or out_tokens <= 0:+ # The server reports usage; counting frames here would be an estimate, and reporting an+ # estimate as a token count is how chunk counts get mistaken for tokens.+ raise MeasurementError("the worker reported no completion_tokens, so the rate is unknown")+ prompt_tokens = usage.get("prompt_tokens")+ decode_ms = duration_ms - ((first_token_at - started) * 1000.0 if first_token_at else 0.0)+ decode_ms = max(decode_ms, 0.001)++ parts = usage.get("prompt_tokens_details") or {}+ measurement = EngineMeasurement(+ tokens_per_s=round(out_tokens * 1000.0 / decode_ms, 4),+ decode_tokens_per_s=round(out_tokens * 1000.0 / decode_ms, 4),+ prompt_tokens_per_s=(round(prompt_tokens * 1000.0 / max(+ (first_token_at - started) * 1000.0, 0.001), 4)+ if isinstance(prompt_tokens, int) and prompt_tokens and first_token_at else None),+ ttft_ms=round((first_token_at - started) * 1000.0, 2) if first_token_at else None,+ client_ttft_ms=round((first_token_at - started) * 1000.0, 2) if first_token_at else None,+ produced=out_tokens,+ prompt_tokens=prompt_tokens if isinstance(prompt_tokens, int) else 0,+ finish=finish or "unknown",+ source="worker-http-api",+ mode="api",+ raw={"usage": usage, "cached_tokens": parts.get("cached_tokens"),+ "duration_ms": round(duration_ms, 2), "answer_chars": len(answer),+ "reasoning_chars": len(reasoning)})+ if self._proc is not None:+ measurement.peak_memory_mib = process_tree_peak_mib(self._proc.pid)+ return measurement+++def make_api_measure(*, python: Path | str, serve_dir: Path, config_path: Path, prompt: str,+ max_new: int, expect: str | None = None, port: int = 8123,+ boot_timeout_s: float = 900.0,+ request_timeout_s: float = 900.0):+ """Build a `measure` callable for the tuning job that uses the HTTP API.++ Unlike the protocol harness, the configuration is already in a file, so the candidate's flags are+ written to a *copy* of it and the worker is pointed at the copy. The caller's file is never+ touched: a sweep must not be able to change the active configuration even by accident.+ """+ import tempfile++ from strata_control.tune_apply import apply_args_to_config, args_to_argv++ base = json.loads(Path(config_path).read_text(encoding="utf-8"))++ def measure(candidate) -> dict[str, float]:+ args = getattr(candidate, "args", candidate)+ candidate_cfg = apply_args_to_config(base, args_to_argv(args) if isinstance(args, dict) else list(args))+ with tempfile.NamedTemporaryFile("w", prefix="strata-tune-candidate-", suffix=".json",+ delete=False, encoding="utf-8") as fh:+ json.dump(candidate_cfg, fh, indent=1)+ path = Path(fh.name)+ harness = ApiHarness(python=python, serve_dir=serve_dir, config_path=path, port=port,+ boot_timeout_s=boot_timeout_s, request_timeout_s=request_timeout_s)+ try:+ harness.start()+ return harness.measure(prompt=prompt, max_new=max_new, expect=expect).to_metrics()+ finally:+ harness.close()+ try:+ path.unlink()+ except OSError:+ pass++ return measurediff --git a/strata_control/tune_apply.py b/strata_control/tune_apply.pynew file mode 100644index 000000000..bef5b76bb--- /dev/null+++ b/strata_control/tune_apply.py@@ -0,0 +1,389 @@+"""Applying a tuning recommendation: explicit, verified and reversible (checklist T07).++A sweep ends at a report, and a report changes nothing. This module is the separate, deliberate step+that turns one reviewed recommendation into a change to the active run configuration — and it is+built around the fact that the most dangerous moment in tuning is the gap between measuring a+configuration and running it for real.++Four things make that safe, and each exists because of a specific way this goes wrong:++1. **Explicit, and only from a completed sweep.** There is no default and no automatic application.+ The job must have reached a terminal state with a recommendation, and the report must still hash+ to what was reviewed — a report edited after review is refused, because the review was of+ different numbers.++2. **Identity is re-checked before anything is written.** A recommendation measured against one+ engine or one model says nothing about another. If the engine digest, model digest, backend,+ workload or context has changed since the sweep, the apply is refused *with the reason* rather+ than applied to a configuration it was never measured against.++3. **The candidate is verified by running it.** The proposed configuration is started and required+ to produce at least one token before the change is written. A configuration that boots but cannot+ generate is the exact failure a benchmark cannot see, because the benchmark never ran the real+ path.++4. **Reversal keeps the previous bytes.** The prior configuration is copied aside by digest before+ the write, and rollback restores those bytes — so "apply" is never a one-way door.++The active profile is untouched until the apply step: exploration and application are separate+commands with separate leases, and neither can be triggered by the other.+"""++from __future__ import annotations++import hashlib+import json+import os+import shutil+import tempfile+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Sequence++SCHEMA_VERSION = 1+++class ApplyError(RuntimeError):+ """An apply was refused. The message is the reason, and nothing was written."""++ def __init__(self, message: str, code: int = 6) -> None:+ super().__init__(message)+ self.code = code+++def _sha256(payload: bytes) -> str:+ return hashlib.sha256(payload).hexdigest()+++def _atomic_write(path: Path, payload: bytes) -> None:+ """Replace a file's contents in one step, so a crash cannot leave it half-written."""+ descriptor, temp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent)+ try:+ with os.fdopen(descriptor, "wb") as stream:+ stream.write(payload)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temp, path)+ finally:+ if os.path.exists(temp):+ os.unlink(temp)+++# --------------------------------------------------------------------------- args and configs++def args_to_argv(args: dict[str, Any]) -> list[str]:+ """The recommendation's flags, as argv.++ Order is sorted so the same recommendation always produces the same bytes: an apply that+ reshuffled its own output would produce a different digest each time and break the rollback+ comparison.+ """+ out: list[str] = []+ for flag in sorted(args):+ value = args[flag]+ if value is None or value is False:+ continue+ if value is True:+ out.append(flag)+ continue+ out.extend([flag, str(value)])+ return out+++def find_config_files(root: Path, *, limit: int = 200) -> list[Path]:+ """Every `strata-*.json` run configuration under `root`.++ The project keeps one configuration per installed model, and the naming is the project's own+ (`strata-<model>.json`, as `setup.py` writes them). Anything that does not parse as a JSON object+ with an `args` list is not a run configuration and is ignored rather than guessed at.+ """+ out: list[Path] = []+ for path in sorted(Path(root).rglob("strata-*.json")):+ if len(out) >= limit:+ break+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if isinstance(data, dict) and isinstance(data.get("args"), list):+ out.append(path)+ return out+++def apply_args_to_config(config: dict[str, Any], argv: Sequence[str]) -> dict[str, Any]:+ """Set a recommendation's flags on a configuration, leaving everything else alone.++ The rules are narrow on purpose:++ * a flag the configuration already carries has **all** of its occurrences replaced, because a+ half-replaced flag is a configuration that does nothing;+ * a flag it does not carry is appended;+ * no other key is touched, so unknown fields, aliases, `env` and `vision` survive — an apply+ that dropped a user's API token would be worse than no apply at all.++ `--flag value` and `--flag=value` are both produced as two argv elements, which the engine's+ parser accepts either way.+ """+ candidate = json.loads(json.dumps(config)) # deep copy, values are JSON+ existing = list(candidate.get("args") or [])++ # The recommendation's flags, paired.+ wanted: dict[str, list[str]] = {}+ i = 0+ while i < len(argv):+ flag = argv[i]+ value = argv[i + 1] if i + 1 < len(argv) and not argv[i + 1].startswith("--") else None+ wanted[flag] = [flag] if value is None else [flag, value]+ i += 2 if value is not None else 1++ # Strip every occurrence of each recommended flag, then append the recommendation once.+ stripped: list[str] = []+ i = 0+ while i < len(existing):+ item = str(existing[i])+ if item in wanted:+ i += 2 if (i + 1 < len(existing) and not str(existing[i + 1]).startswith("--")) else 1+ continue+ stripped.append(existing[i])+ i += 1++ for flag in sorted(wanted):+ stripped.extend(wanted[flag])+ candidate["args"] = stripped+ return candidate+++# --------------------------------------------------------------------------- the plan++@dataclass+class ApplyPlan:+ """What an apply would do, computed before anything is written."""++ job_id: str+ config_path: Path+ before_args: list[str]+ after_args: list[str]+ added: list[str]+ removed: list[str]+ before_sha256: str+ after_sha256: str+ report_sha256: str+ reasons: list[str] # non-empty means it will not apply++ @property+ def applicable(self) -> bool:+ return not self.reasons++ def to_dict(self) -> dict[str, Any]:+ return {+ "job_id": self.job_id,+ "config_path": str(self.config_path),+ "before_args": self.before_args,+ "after_args": self.after_args,+ "added": self.added,+ "removed": self.removed,+ "before_sha256": self.before_sha256,+ "after_sha256": self.after_sha256,+ "report_sha256": self.report_sha256,+ "applicable": self.applicable,+ "reasons": self.reasons,+ }+++def _diff(before: Sequence[str], after: Sequence[str]) -> tuple[list[str], list[str]]:+ """Which flags appeared and which disappeared, as `flag value` strings."""+ def pairs(items: Sequence[str]) -> dict[str, str]:+ out: dict[str, str] = {}+ i = 0+ while i < len(items):+ item = str(items[i])+ if item.startswith("--") and i + 1 < len(items) and not str(items[i + 1]).startswith("--"):+ out[item] = str(items[i + 1])+ i += 2+ else:+ out[item] = ""+ i += 1+ return out++ b, a = pairs(before), pairs(after)+ added = [f"{k} {v}".strip() for k, v in sorted(a.items()) if b.get(k) != v]+ removed = [f"{k} {v}".strip() for k, v in sorted(b.items()) if a.get(k) != v]+ return added, removed+++def review_apply(*, job: dict[str, Any], config_path: Path,+ current_identity: dict[str, Any] | None,+ report_sha256: str | None = None) -> ApplyPlan:+ """Decide whether this job's recommendation may be applied to this configuration.++ Every refusal names what is wrong. An apply that silently proceeded on a stale or incompatible+ report would be the single most damaging thing this module could do, so the checks are exhaustive+ and each one is a reason rather than a bare `False`.+ """+ reasons: list[str] = []+ report = job.get("report") or {}+ job_id = str(job.get("id") or "")++ if job.get("state") != "completed":+ reasons.append(f"the sweep is {job.get('state')}, not completed; its result is not final")+ if not report.get("recommendation_available") or not report.get("recommendation"):+ reasons.append("the sweep recommended no change: " + str(report.get("reason") or "no reason recorded"))+ if report.get("drift_material"):+ drift = report.get("drift") or {}+ reasons.append(+ f"the machine drifted by {float(drift.get('relative', 0)) * 100:+.1f}% during the sweep, "+ "so the comparison does not support a change")+ if not config_path.exists():+ reasons.append(f"no run configuration at {config_path}")+ return ApplyPlan(job_id, config_path, [], [], [], [], "", "", "", reasons)++ source = config_path.read_bytes()+ before = json.loads(source.decode("utf-8"))+ before_args = [str(x) for x in (before.get("args") or [])]++ rec = report.get("recommendation") or {}+ argv = args_to_argv(rec.get("args") or {})+ if not argv:+ reasons.append("the recommendation carries no flags, so there is nothing to apply")++ candidate = apply_args_to_config(before, argv)+ after_args = [str(x) for x in candidate["args"]]+ added, removed = _diff(before_args, after_args)+ if not added and not removed:+ reasons.append("the configuration already carries this recommendation; nothing would change")++ # The report has to be the one that was reviewed.+ if report_sha256 is not None and report_sha256 != _report_digest(job):+ reasons.append("the sweep report changed after review; review it again")++ # And it has to have been measured on what is installed now.+ if current_identity is not None:+ from strata_control import tune_history+ recorded = report.get("identity") or {}+ if not recorded:+ reasons.append("the sweep recorded no artifact identity, so it cannot be matched to what "+ "is installed now")+ else:+ differences = tune_history.incomparable_reasons(recorded, current_identity)+ if differences:+ reasons.append("the sweep was measured against a different configuration: "+ + ", ".join(differences))++ after_bytes = (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8")+ return ApplyPlan(+ job_id=job_id, config_path=config_path, before_args=before_args, after_args=after_args,+ added=added, removed=removed, before_sha256=_sha256(source), after_sha256=_sha256(after_bytes),+ report_sha256=_report_digest(job), reasons=reasons)+++def _report_digest(job: dict[str, Any]) -> str:+ """A digest of the report, so a review cannot be reused for edited numbers."""+ body = json.dumps(job.get("report") or {}, sort_keys=True, separators=(",", ":"))+ return _sha256(body.encode("utf-8"))+++# --------------------------------------------------------------------------- applying++def _application_dir(root: Path) -> Path:+ d = Path(root) / "applications"+ d.mkdir(parents=True, exist_ok=True)+ return d+++def apply_recommendation(*, job: dict[str, Any], config_path: Path,+ current_identity: dict[str, Any] | None,+ state_dir: Path,+ verify: Callable[[dict[str, Any]], int] | None = None,+ expected_report_sha256: str | None = None) -> dict[str, Any]:+ """Verify the candidate by running it, then write it — keeping the previous bytes.++ `verify` receives the candidate configuration and must return the number of tokens generated.+ A result below 1 is a refusal, not a warning: a configuration that cannot produce a token has not+ been verified, whatever the sweep measured.+ """+ plan = review_apply(job=job, config_path=config_path, current_identity=current_identity,+ report_sha256=expected_report_sha256)+ if not plan.applicable:+ raise ApplyError("; ".join(plan.reasons))++ before = json.loads(config_path.read_text(encoding="utf-8"))+ candidate = apply_args_to_config(before, args_to_argv(+ (job.get("report") or {}).get("recommendation", {}).get("args") or {}))++ verified_tokens: int | None = None+ if verify is not None:+ try:+ tokens = verify(candidate)+ except Exception as exc: # noqa: BLE001+ raise ApplyError(+ f"the candidate configuration failed verification ({type(exc).__name__}: {exc}); "+ "the run configuration is unchanged") from None+ if type(tokens) is not int or tokens < 1:+ raise ApplyError("the candidate configuration generated no tokens; the run "+ "configuration is unchanged")+ verified_tokens = int(tokens)++ # Re-read after verification: a user edit during a long verification must not be overwritten.+ if _sha256(config_path.read_bytes()) != plan.before_sha256:+ raise ApplyError("the run configuration changed during verification; nothing was written")++ application_id = f"{time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())}-{plan.job_id[:12]}"+ directory = _application_dir(state_dir) / application_id+ if directory.exists():+ raise ApplyError(f"an application record already exists at {directory}")+ directory.mkdir(parents=True)+ shutil.copy2(config_path, directory / "before.json")+ (directory / "candidate.json").write_bytes(+ (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8"))++ _atomic_write(config_path, (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8"))++ record = {+ "schema_version": SCHEMA_VERSION,+ "kind": "strata.tuning.application",+ "application_id": application_id,+ "job_id": plan.job_id,+ "applied_at": time.time(),+ "config_path": str(config_path),+ "before_sha256": plan.before_sha256,+ "after_sha256": plan.after_sha256,+ "report_sha256": plan.report_sha256,+ "added": plan.added,+ "removed": plan.removed,+ "verified_tokens": verified_tokens,+ "rolled_back": False,+ }+ (directory / "application.json").write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")+ return {"application": record, "directory": str(directory), "plan": plan.to_dict()}+++def rollback(*, application_id: str, state_dir: Path) -> dict[str, Any]:+ """Restore the configuration that was in place before an apply.++ Refuses if the configuration has been edited since the apply, because restoring would then+ discard a deliberate change: the user's edit wins, and the conflict is reported.+ """+ directory = _application_dir(state_dir) / application_id+ record_path = directory / "application.json"+ if not record_path.exists():+ raise ApplyError(f"no application record at {record_path}", 404)+ record = json.loads(record_path.read_text(encoding="utf-8"))+ if record.get("rolled_back"):+ raise ApplyError("this application has already been rolled back")+ before = directory / "before.json"+ if not before.exists():+ raise ApplyError(f"the previous configuration was not retained at {before}")+ target = Path(record["config_path"])+ if not target.exists():+ raise ApplyError(f"the run configuration is gone: {target}")+ current = _sha256(target.read_bytes())+ if current != record["after_sha256"]:+ raise ApplyError(+ "the run configuration changed after this apply, so restoring would discard a newer "+ "change; nothing was written", 409)+ _atomic_write(target, before.read_bytes())+ record["rolled_back"] = True+ record["rolled_back_at"] = time.time()+ record_path.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")+ return {"application": record, "restored": str(target)}diff --git a/strata_control/tune_engine.py b/strata_control/tune_engine.pynew file mode 100644index 000000000..5de9b74be--- /dev/null+++ b/strata_control/tune_engine.py@@ -0,0 +1,532 @@+"""Measure one engine configuration, for the tuning job.++The tuning job (`strata_control/tuning.py`) searches configurations and decides from numbers. This+module is where those numbers come from: it boots the engine with one candidate's flags, sends the+declared workload, reads the engine's own output, and returns measurements.++It is deliberately separate from the job, and it is deliberately paranoid:++* **It never invents a number.** If the engine does not start, produces no tokens, or finishes for a+ reason other than a stop or a length, this raises with the engine's own words. The job records+ that as a failed candidate — which is a real result — rather than as a slow one.+* **It measures what the engine reports, not what the wall clock suggests.** The engine prints its+ own prompt and decode milliseconds, so a measurement does not include this process's scheduling.+ Client-observed timings are recorded separately and labelled, because they answer a different+ question.+* **It runs the declared workload every time**, with a fixed seed, so two candidates are compared on+ the same work. A "faster" configuration that quietly did less is the classic tuning failure.++The production engine protocol this reads (see `src/program/generate.cpp`):++ READY <max_context> stop+ PP <processed> <total> <ms> [<tok_s>] prompt progress+ T <token_id> one generated token+ DONE <produced> <prompt_tokens> <prompt_ms> <decode_ms> <finish> <drafts_acc> <drafts_off> ...++`finish` is `stop`, `length`, `cancel` or `nonfinite`. A `cancel` or `nonfinite` finish is not a+measurement, and neither is a run whose `produced` is zero.+"""++from __future__ import annotations++import json+import re+import select+import subprocess+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Iterable, Sequence++#: A workload is fixed for the whole sweep: the same prompt, the same number of tokens to generate,+#: the same sampling. Changing any of these between candidates invalidates the comparison.+DEFAULT_WORKLOAD = {+ "prompt_tokens": 512,+ "max_new": 128,+ "seed": 1,+ "temperature": 0.0, # greedy, so the work is deterministic+}+++class MeasurementError(RuntimeError):+ """The candidate could not be measured. The message is the engine's own reason."""+++@dataclass+class EngineMeasurement:+ """One candidate's measurements, with the units and the source of each.++ `source` distinguishes what the engine reported from what this process observed, because they+ are not interchangeable: the engine's `prompt_ms`/`decode_ms` exclude process startup and+ scheduling, while `client_ttft_ms` includes everything a user would wait for.+ """++ tokens_per_s: float+ #: Peak resident memory of the measured process tree, in MiB. Tuning that gets faster by+ #: spilling or by thrashing is not an improvement, and the checklist asks for memory to travel+ #: with the speed number so the trade is visible rather than hidden.+ peak_memory_mib: float | None = None+ prompt_tokens_per_s: float | None = None+ decode_tokens_per_s: float | None = None+ ttft_ms: float | None = None # engine-reported: prompt_ms + the first decode step+ client_ttft_ms: float | None = None # observed here, includes process scheduling+ produced: int = 0+ prompt_tokens: int = 0+ finish: str = ""+ memory_mib: float | None = None+ source: str = "engine-serve-protocol"+ #: `protocol` measures the engine's own serve protocol; `api` drives the real HTTP API the agent+ #: uses. They answer different questions, so the report must not present one as the other.+ mode: str = "protocol"+ raw: dict[str, Any] = field(default_factory=dict)++ def to_metrics(self) -> dict[str, float]:+ """The dict the job's `measure` callable must return.++ Only finite numbers are emitted, so a missing measurement stays missing rather than becoming+ a zero that a comparison might treat as a very slow result.+ """+ out: dict[str, float] = {"tokens_per_s": self.tokens_per_s}+ for key in ("prompt_tokens_per_s", "decode_tokens_per_s", "ttft_ms", "client_ttft_ms",+ "memory_mib", "peak_memory_mib"):+ value = getattr(self, key)+ if isinstance(value, (int, float)):+ out[key] = float(value)+ return out+++# --------------------------------------------------------------------------- parsing++_READY = re.compile(r"^READY\s+(\d+)\s+(\S+)\s*$")+_PP = re.compile(r"^PP\s+(\d+)\s+(\d+)\s+([\d.]+)(?:\s+([\d.]+))?\s*$")+_DONE = re.compile(r"^DONE\s+(.*)$")+_TOKEN = re.compile(r"^T\s+(\d+)\s*$")+++def parse_done(line: str) -> dict[str, Any]:+ """Parse a `DONE` line.++ The line's tail is variable — the engine appends lookup-chain counters only when that option is+ on — so the leading fields are read positionally and the rest is kept, never required.+ """+ m = _DONE.match(line.strip())+ if not m:+ raise MeasurementError(f"not a DONE line: {line[:120]!r}")+ parts = m.group(1).split()+ if len(parts) < 5:+ raise MeasurementError(f"a DONE line with fewer than 5 fields: {line[:120]!r}")+ try:+ produced = int(parts[0])+ prompt_tokens = int(parts[1])+ prompt_ms = float(parts[2])+ decode_ms = float(parts[3])+ except ValueError as e:+ raise MeasurementError(f"a DONE line with an unreadable number: {line[:120]!r}") from e+ return {+ "produced": produced,+ "prompt_tokens": prompt_tokens,+ "prompt_ms": prompt_ms,+ "decode_ms": decode_ms,+ "finish": parts[4],+ "drafts_accepted": _int(parts[5]) if len(parts) > 5 else None,+ "drafts_offered": _int(parts[6]) if len(parts) > 6 else None,+ "tail": parts[7:],+ }+++def _int(text: str) -> int | None:+ try:+ return int(text)+ except ValueError:+ return None+++def parse_ready(line: str) -> int:+ m = _READY.match(line.strip())+ if not m:+ raise MeasurementError(f"not a READY line: {line[:120]!r}")+ return int(m.group(1))+++def parse_pp(line: str) -> dict[str, float]:+ m = _PP.match(line.strip())+ if not m:+ raise MeasurementError(f"not a PP line: {line[:120]!r}")+ out = {"processed": float(m.group(1)), "total": float(m.group(2)), "ms": float(m.group(3))}+ if m.group(4):+ out["tok_s"] = float(m.group(4))+ return out+++def measurement_from_protocol(done: dict[str, Any], *, tokens_seen: int,+ client_ttft_ms: float | None = None,+ ready_ms: float | None = None) -> EngineMeasurement:+ """Turn the engine's own report into measurements.++ Rejects a run that did not actually generate: a `cancel`, a `nonfinite`, a zero-token run and a+ disagreement between the token count and the DONE line are all errors, not slow results.+ """+ finish = str(done.get("finish", ""))+ produced = int(done.get("produced", 0))+ if finish in ("cancel", "nonfinite"):+ raise MeasurementError(f"the engine finished with '{finish}', which is not a measurement")+ if produced <= 0:+ raise MeasurementError("the engine produced no tokens")+ if tokens_seen and tokens_seen != produced:+ # The stream and the summary disagree, so neither can be trusted for a rate.+ raise MeasurementError(+ f"the engine reported {produced} tokens but streamed {tokens_seen}; refusing to score it")++ decode_ms = float(done.get("decode_ms") or 0.0)+ prompt_ms = float(done.get("prompt_ms") or 0.0)+ prompt_tokens = int(done.get("prompt_tokens") or 0)++ decode_per_s = (produced * 1000.0 / decode_ms) if decode_ms > 0 else None+ prompt_per_s = (prompt_tokens * 1000.0 / prompt_ms) if prompt_ms > 0 and prompt_tokens else None++ # What "tokens per second" means for the objective: the whole request's decoding rate. Prompt+ # processing is reported separately because a candidate can move one without the other, and+ # averaging them would hide exactly the trade the tuner is searching for.+ total_ms = prompt_ms + decode_ms+ overall = (produced * 1000.0 / total_ms) if total_ms > 0 else (decode_per_s or 0.0)++ # The engine's own TTFT: reading the prompt plus the first decode step.+ per_token_ms = (decode_ms / produced) if produced else None+ ttft = (prompt_ms + per_token_ms) if per_token_ms is not None else (prompt_ms or None)++ return EngineMeasurement(+ tokens_per_s=overall,+ prompt_tokens_per_s=prompt_per_s,+ decode_tokens_per_s=decode_per_s,+ ttft_ms=ttft,+ client_ttft_ms=client_ttft_ms,+ produced=produced,+ prompt_tokens=prompt_tokens,+ finish=finish,+ raw=dict(done),+ )+++# --------------------------------------------------------------------------- running++class LineReader:+ """Read lines from a pipe without ever blocking the caller.++ `readline()` on a pipe has no timeout, so a `while time.monotonic() < deadline` loop around it+ does not bound anything: an engine that starts and then says nothing hangs the measurement+ forever. That is a real defect, not a hypothetical — it made the boot-timeout path unreachable+ and hung this module's own tests.++ A daemon reader thread moves the blocking read off the caller's thread, and the caller polls a+ queue with a deadline it actually enforces.+ """++ def __init__(self, stream, name: str = "engine") -> None:+ import queue+ import threading+ self._queue: "queue.Queue[str | None]" = queue.Queue()+ self._stream = stream+ self.name = name+ self._thread = threading.Thread(target=self._pump, daemon=True,+ name=f"strata-{name}-reader")+ self._thread.start()++ def _pump(self) -> None:+ try:+ for line in self._stream:+ self._queue.put(line)+ except (OSError, ValueError):+ pass+ finally:+ # A sentinel so a reader knows the stream ended rather than that it is merely quiet.+ self._queue.put(None)++ def read_line(self, deadline: float) -> str | None:+ """One line, or None if the deadline passed or the stream ended.++ Raises `EOFError` when the stream has ended, so a caller can distinguish "nothing yet" from+ "the engine is gone".+ """+ import queue+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return None+ try:+ line = self._queue.get(timeout=remaining)+ except queue.Empty:+ return None+ if line is None:+ raise EOFError(f"the {self.name} stream ended")+ return line++ def drain_available(self) -> list[str]:+ """Everything already buffered, without waiting."""+ import queue+ out: list[str] = []+ while True:+ try:+ line = self._queue.get_nowait()+ except queue.Empty:+ return out+ if line is None:+ return out+ out.append(line)++++def process_tree_peak_mib(pid: int) -> float | None:+ """Peak resident memory of a process and its children, in MiB.++ The engine is one process today, but a backend may spawn workers, so the tree is summed rather+ than the root alone. `ps` is used because it reports each process's own peak (`rss` is current,+ `vsz` is address space); when it is unavailable the memory is simply absent, which is the honest+ answer and not a zero.+ """+ try:+ out = subprocess.run(["ps", "-o", "rss=,pid=,ppid=", "-ax"], capture_output=True, text=True,+ timeout=5).stdout+ except (OSError, subprocess.SubprocessError):+ return None+ rows: list[tuple[int, int, int]] = []+ for line in out.splitlines():+ parts = line.split()+ if len(parts) != 3:+ continue+ try:+ rows.append((int(parts[1]), int(parts[2]), int(parts[0])))+ except ValueError:+ continue+ wanted = {pid}+ changed = True+ while changed: # transitive closure over ppid+ changed = False+ for child, parent, _ in rows:+ if parent in wanted and child not in wanted:+ wanted.add(child)+ changed = True+ total = sum(rss for child, _, rss in rows if child in wanted)+ return round(total / 1024.0, 1) if total else None+++class EngineHarness:+ """Boot the engine once per candidate and measure the declared workload.++ The engine is a subprocess speaking line protocol over stdout, exactly as `serve/server.py`+ drives it. One harness is created per candidate: a configuration that changes the expert cache+ or the KV layout cannot be assumed to take effect in a running engine.+ """++ def __init__(self, engine: Path, args: dict[str, str], *, workload: dict[str, Any] | None = None,+ cwd: Path | None = None, env: dict[str, str] | None = None,+ boot_timeout_s: float = 600.0, request_timeout_s: float = 600.0) -> None:+ self.engine = Path(engine)+ self.args = dict(args)+ self.workload = {**DEFAULT_WORKLOAD, **(workload or {})}+ self.cwd = Path(cwd) if cwd else Path.cwd()+ self.env = env+ self.boot_timeout_s = boot_timeout_s+ self.request_timeout_s = request_timeout_s+ self._proc: subprocess.Popen | None = None+ self._reader: LineReader | None = None+ self.last_measurement: EngineMeasurement | None = None+ self._ready_ms: float | None = None+ self._context: int | None = None++ def _argv(self) -> list[str]:+ argv = [str(self.engine), "--serve"]+ for flag, value in self.args.items():+ argv.append(flag)+ if value not in ("1", "0", "true", "false", ""):+ argv.append(str(value))+ return argv++ def __enter__(self) -> "EngineHarness":+ self.start()+ return self++ def __exit__(self, *exc: object) -> None:+ self.close()++ def start(self) -> None:+ if not self.engine.exists():+ raise MeasurementError(f"the engine binary is not at {self.engine}")+ started = time.monotonic()+ try:+ self._proc = subprocess.Popen(+ self._argv(), cwd=str(self.cwd), env=self.env,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, bufsize=1)+ except OSError as e:+ raise MeasurementError(f"the engine could not be started: {e}") from e++ self._reader = LineReader(self._proc.stdout, "engine")+ deadline = time.monotonic() + self.boot_timeout_s+ while True:+ if time.monotonic() >= deadline:+ if self._proc.poll() is not None:+ raise MeasurementError(+ f"the engine exited with code {self._exit_code()} before it was ready"+ + self._stderr_tail())+ raise MeasurementError(+ f"the engine did not report READY within {self.boot_timeout_s:.0f}s")+ try:+ line = self._reader.read_line(deadline)+ except EOFError:+ raise MeasurementError(+ f"the engine exited with code {self._exit_code()} before it was ready"+ + self._stderr_tail()) from None+ if line is None:+ # Nothing yet. Only a *finished* process means failure; a slow boot does not.+ if self._proc.poll() is not None:+ raise MeasurementError(+ f"the engine exited with code {self._exit_code()} before it was ready"+ + self._stderr_tail())+ continue+ line = line.strip()+ if line.startswith("READY"):+ self._context = parse_ready(line)+ self._ready_ms = (time.monotonic() - started) * 1000.0+ return+ if line.startswith("ERR"):+ raise MeasurementError(f"the engine refused to start: {line}")++ def _exit_code(self) -> int | None:+ """The engine's exit code, reaped if necessary.++ `poll()` returns None until the process has been waited on, and a reader thread can observe+ end-of-stream *before* that happens. Reporting "exited with code None" is useless in exactly+ the case where the code matters most, so this waits briefly for the status.+ """+ if self._proc is None:+ return None+ if self._proc.poll() is None:+ try:+ self._proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ return None+ return self._proc.returncode++ def _stderr_tail(self, limit: int = 400) -> str:+ if self._proc is None or self._proc.stderr is None:+ return ""+ try:+ # Only meaningful once the process has ended; a running engine's stderr is still open.+ if self._proc.poll() is None:+ return ""+ text = self._proc.stderr.read() or ""+ return f"; stderr: {text[-limit:].strip()}"+ except OSError:+ return ""++ def measure(self) -> EngineMeasurement:+ """Send the workload and read one result. Raises `MeasurementError` on anything unusable."""+ if self._proc is None or self._proc.poll() is not None:+ raise MeasurementError("the engine is not running")+ if self._proc.stdin is None or self._proc.stdout is None:+ raise MeasurementError("the engine has no input/output pipe")++ tokens = self._prompt_tokens()+ flags = (f" temperature={self.workload['temperature']} seed={self.workload['seed']}")+ request = f"GEN {int(self.workload['max_new'])}{flags} {','.join(str(t) for t in tokens)}\n"++ client_start = time.monotonic()+ try:+ self._proc.stdin.write(request)+ self._proc.stdin.flush()+ except (OSError, BrokenPipeError) as e:+ raise MeasurementError(f"the engine stopped accepting work: {e}" + self._stderr_tail()) from e++ deadline = time.monotonic() + self.request_timeout_s+ seen = 0+ client_ttft: float | None = None+ done: dict[str, Any] | None = None+ while True:+ if time.monotonic() >= deadline:+ break+ try:+ raw = self._reader.read_line(deadline)+ except EOFError:+ raise MeasurementError(+ f"the engine exited with code {self._exit_code()} during the request"+ + self._stderr_tail()) from None+ if raw is None:+ if self._proc.poll() is not None:+ raise MeasurementError(+ f"the engine exited with code {self._exit_code()} during the request"+ + self._stderr_tail())+ continue+ line = raw.strip()+ if _TOKEN.match(line):+ seen += 1+ if client_ttft is None:+ client_ttft = (time.monotonic() - client_start) * 1000.0+ elif line.startswith("DONE"):+ done = parse_done(line)+ break+ elif line.startswith("ERR"):+ raise MeasurementError(f"the engine reported an error: {line}")+ if done is None:+ raise MeasurementError(+ f"the engine produced no DONE line within {self.request_timeout_s:.0f}s")++ result = measurement_from_protocol(done, tokens_seen=seen, client_ttft_ms=client_ttft,+ ready_ms=self._ready_ms)+ if self._proc is not None:+ result.peak_memory_mib = process_tree_peak_mib(self._proc.pid)+ result.mode = "protocol"+ self.last_measurement = result+ return result++ def _prompt_tokens(self) -> Sequence[int]:+ """The workload's token ids.++ A real sweep substitutes the tokenizer's ids here. The default is a fixed, deterministic+ sequence of the declared length: it exercises the same code path for every candidate, which+ is what makes the comparison valid, and it cannot be accused of silently changing the work.+ """+ n = max(1, int(self.workload["prompt_tokens"]))+ return [1000 + (i % 97) for i in range(n)]++ def close(self) -> None:+ if self._proc is None:+ return+ try:+ if self._proc.poll() is None and self._proc.stdin is not None:+ self._proc.stdin.write("QUIT\n")+ self._proc.stdin.flush()+ try:+ self._proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ self._proc.kill()+ except (OSError, ValueError):+ try:+ self._proc.kill()+ except OSError:+ pass+ finally:+ for stream in (self._proc.stdin, self._proc.stdout, self._proc.stderr):+ try:+ if stream is not None:+ stream.close()+ except OSError:+ pass+ self._proc = None+++def make_measure(engine: Path, workload: dict[str, Any] | None = None,+ cwd: Path | None = None) -> "callable":+ """Build the `measure` callable the tuning job expects.++ The returned function boots the engine with the candidate's args, measures once, and returns the+ metrics. It raises on anything unusable, which the job records as that candidate's status.+ """+ def measure(candidate) -> dict[str, float]:+ harness = EngineHarness(engine, candidate.args if hasattr(candidate, "args") else candidate,+ workload=workload, cwd=cwd)+ try:+ harness.start()+ return harness.measure().to_metrics()+ finally:+ harness.close()++ return measurediff --git a/strata_control/tune_history.py b/strata_control/tune_history.pynew file mode 100644index 000000000..5fa9b0e58--- /dev/null+++ b/strata_control/tune_history.py@@ -0,0 +1,247 @@+"""Tuning history: what makes two measurements comparable.++Checklist T06 asks that an engine, model, driver, workload or context change invalidates+incompatible history, and that model identity is more than a name. Both matter for the same reason:+a tuning result is only meaningful relative to the machine and the exact bytes it was measured on,+and a history that silently mixes two configurations produces a confident recommendation from+incomparable numbers.++The design follows from that:++* **Identity is a content hash, not a label.** A model is identified by the digest of its file(s), an+ engine by the digest of its binary. "qwen3.8-flash-next" and "the same filename" are not+ identities: a re-quantised model keeps its name and changes its behaviour.+* **The comparison key is explicit and complete.** Engine + model + backend + workload + context ++ the machine. Any element changing makes two records incomparable, and the *reason* is reported+ rather than the record being quietly dropped.+* **Nothing is deleted.** Incomparable history is retained and labelled. A previous sweep may still+ answer a question ("did that flag help on the old driver?"), so it is not the store's business to+ discard it — only to refuse to average it with the new numbers.+* **Hashing a multi-gigabyte model is bounded.** A full digest of a 40 GB pack is not something to do+ casually, so a partial digest (size plus sampled regions) is used by default, and the method is+ recorded so two records can never be compared as though they used the same one.+"""++from __future__ import annotations++import hashlib+import json+import os+import platform+import time+import uuid+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Any, Sequence++SCHEMA_VERSION = 1++#: How a file's identity was computed. Two records with different methods are not comparable, so the+#: method travels with the digest.+FULL = "sha256-full"+SAMPLED = "sha256-sampled-head-tail-mid"++#: Bytes read at each sampled region.+SAMPLE_BYTES = 4 << 20+++def file_identity(path: Path, *, full: bool = False) -> dict[str, Any]:+ """A content identity for a file, cheaply by default.++ A model pack is tens of gigabytes; hashing it fully on every CLI invocation would be its own kind+ of bug. The sampled digest reads the head, the middle and the tail plus the exact size, which+ catches a different quantisation, a truncated download and a swapped file in practice. `full=True`+ is available for a release-time record where the cost is acceptable.+ """+ p = Path(path)+ if not p.exists():+ return {"path": str(p), "exists": False, "method": None, "digest": None, "bytes": None}+ size = p.stat().st_size+ h = hashlib.sha256()+ if full:+ method = FULL+ with p.open("rb") as fh:+ for block in iter(lambda: fh.read(1 << 20), b""):+ h.update(block)+ else:+ method = SAMPLED+ h.update(str(size).encode())+ with p.open("rb") as fh:+ regions = []+ if size <= 3 * SAMPLE_BYTES:+ regions.append((0, size))+ else:+ regions = [(0, SAMPLE_BYTES),+ (size // 2, SAMPLE_BYTES),+ (size - SAMPLE_BYTES, SAMPLE_BYTES)]+ for offset, length in regions:+ fh.seek(offset)+ h.update(fh.read(length))+ return {"path": str(p), "exists": True, "method": method, "digest": h.hexdigest(),+ "bytes": size}+++def machine_identity() -> dict[str, Any]:+ """The machine, at the granularity that makes measurements incomparable when it changes.++ The CPU/GPU model and the driver version are what matter; the hostname is not (a renamed machine+ is the same machine), so it is deliberately absent.+ """+ return {+ "system": platform.system(),+ "release": platform.release(),+ "machine": platform.machine(),+ "processor": platform.processor(),+ "cpu_count": os.cpu_count(),+ }+++def comparison_key(*, engine: dict[str, Any], model: dict[str, Any], backend: str,+ workload: dict[str, Any], context: int | None,+ machine: dict[str, Any] | None = None) -> dict[str, Any]:+ """The tuple that two records must share to be comparable.++ Every element is either a digest or a fixed number, so an equality test on this dict is the whole+ comparability rule. A field that is unknown is `None` and therefore *not* equal to a known value,+ which is deliberate: an unknown is not evidence of sameness.+ """+ return {+ "engine_digest": engine.get("digest"),+ "engine_bytes": engine.get("bytes"),+ "model_digest": model.get("digest"),+ "model_bytes": model.get("bytes"),+ "digest_method": model.get("method"),+ "backend": backend,+ "workload": dict(sorted(workload.items())),+ "context": context,+ "machine": dict(sorted((machine or machine_identity()).items())),+ }+++def incomparable_reasons(a: dict[str, Any], b: dict[str, Any]) -> list[str]:+ """Why two comparison keys cannot be compared, in plain words.++ Returning the reasons rather than a boolean is what lets a report say *"the model changed, so the+ earlier sweep no longer applies"* instead of showing a recommendation built across a change.+ """+ reasons: list[str] = []+ if a.get("engine_digest") != b.get("engine_digest"):+ reasons.append("a different engine build")+ if a.get("model_digest") != b.get("model_digest"):+ reasons.append("different model bytes")+ a_method, b_method = a.get("digest_method"), b.get("digest_method")+ if a_method != b_method:+ reasons.append(f"the identity was computed differently ({a_method} vs {b_method})")+ if a.get("backend") != b.get("backend"):+ reasons.append(f"a different backend ({a.get('backend')} vs {b.get('backend')})")+ if a.get("workload") != b.get("workload"):+ reasons.append("a different workload")+ if a.get("context") != b.get("context"):+ reasons.append(f"a different context ({a.get('context')} vs {b.get('context')})")+ if a.get("machine") != b.get("machine"):+ reasons.append("a different machine or driver")+ return reasons+++@dataclass+class HistoryRecord:+ """One completed sweep, as the history store keeps it."""++ id: str+ recorded_at: float+ key: dict[str, Any]+ outcome: str # accepted | inconclusive | conflict | cancelled+ recommendation_args: dict[str, str] = field(default_factory=dict)+ median: float | None = None+ baseline_median: float | None = None+ metric: str = "tokens_per_s"+ trials_run: int = 0+ combinations_total: int = 0+ engine_path: str = ""+ model_path: str = ""+ note: str = ""++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++class HistoryStore:+ """Recorded sweeps, kept so a later one can say what it is and is not comparable to.++ The store is a directory of JSON records rather than a database: it is small, it is read whole by+ a human when something looks wrong, and it has no server to be unavailable.+ """++ def __init__(self, root: Path) -> None:+ self.root = Path(root)+ self.root.mkdir(parents=True, exist_ok=True)++ @property+ def index(self) -> Path:+ return self.root / "history.jsonl"++ def record(self, *, key: dict[str, Any], outcome: str, recommendation_args: dict[str, str] | None = None,+ median: float | None = None, baseline_median: float | None = None,+ metric: str = "tokens_per_s", trials_run: int = 0, combinations_total: int = 0,+ engine_path: str = "", model_path: str = "", note: str = "") -> HistoryRecord:+ rec = HistoryRecord(+ id=uuid.uuid4().hex, recorded_at=time.time(), key=key, outcome=outcome,+ recommendation_args=dict(recommendation_args or {}), median=median,+ baseline_median=baseline_median, metric=metric, trials_run=trials_run,+ combinations_total=combinations_total, engine_path=engine_path, model_path=model_path,+ note=note)+ with self.index.open("a", encoding="utf-8") as fh:+ fh.write(json.dumps({"schema_version": SCHEMA_VERSION, **rec.to_dict()},+ sort_keys=True) + "\n")+ return rec++ def records(self) -> list[HistoryRecord]:+ """Every record, newest last. A damaged line is skipped, not fatal."""+ if not self.index.exists():+ return []+ out: list[HistoryRecord] = []+ for line in self.index.read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ try:+ data = json.loads(line)+ except json.JSONDecodeError:+ continue+ if data.get("schema_version") != SCHEMA_VERSION:+ continue+ data.pop("schema_version", None)+ try:+ out.append(HistoryRecord(**data))+ except TypeError:+ continue+ return out++ def comparable(self, key: dict[str, Any]) -> tuple[list[HistoryRecord], list[dict[str, Any]]]:+ """Split the history into what *is* comparable and what is not, with reasons.++ Nothing is dropped: an incomparable record is returned with the reason it differs, because+ the honest answer to "is there relevant history?" is often "yes, but from a different model".+ """+ usable: list[HistoryRecord] = []+ unusable: list[dict[str, Any]] = []+ for rec in self.records():+ reasons = incomparable_reasons(rec.key, key)+ if reasons:+ unusable.append({"id": rec.id, "recorded_at": rec.recorded_at, "reasons": reasons,+ "outcome": rec.outcome})+ else:+ usable.append(rec)+ return usable, unusable+++def summarise_history(store: HistoryStore, key: dict[str, Any]) -> dict[str, Any]:+ """The block a report carries so a reader knows what the numbers sit next to."""+ usable, unusable = store.comparable(key)+ return {+ "comparable_records": len(usable),+ "incomparable_records": len(unusable),+ "incomparable": unusable[-8:], # the most recent few, with their reasons+ "note": ("earlier sweeps on this exact engine, model, workload, context and machine"+ if usable else+ "no earlier sweep is comparable to this one"),+ }diff --git a/strata_control/tuning.py b/strata_control/tuning.pynew file mode 100644index 000000000..5a5c3949d--- /dev/null+++ b/strata_control/tuning.py@@ -0,0 +1,766 @@+"""Engine tuning: a bounded, evidence-driven search over runtime configuration.++This is **runtime configuration optimization**, not model training. It searches the engine's own+launch settings, measures each candidate, and produces a *recommendation* — never an automatic+change.++Why Strata owns this rather than delegating wholesale to HyperCore-Tune+-----------------------------------------------------------------------++HyperCore-Tune was evaluated as the preferred adapter and is **not sufficient as the optimizer** for+every backend. The evidence, gathered from the pinned checkout and this machine's engine:++* Its search space is expressed as engine flags: ``--vram-reserve-mib``, ``--pcie-frac``,+ ``--pool-workers``, ``--host-core``, ``--pool-affinity``, ``--ple-io``, ``--kv``, ``--kv-grow``,+ ``--prompt-cache-tail``, ``--spec-min-p``. Two of those, ``--vram-reserve-mib`` and+ ``--pcie-frac``, are NVIDIA/AMD concepts: the Apple Silicon engine does not parse them at all+ (``strata --help`` on the Metal build lists neither). On Metal their "measurements" could only be+ an engine refusal, so a HyperCore sweep there would produce ``FAIL_BOOT`` rows rather than+ evidence.+* It resolves the engine by walking up from its own directory looking for a Strata checkout, and it+ writes its deliverables next to that root. Neither is acceptable for a packaged application: the+ component registry must name an exact engine build, and the active profile must not be mutated by+ a search.+* Its README states Linux and Windows support and its tests use stub engines. That is a claim about+ the harness, not a qualification of any GPU.++So the decision, recorded here rather than in a design document alone: **Strata owns the job, the+lease, the evidence and the apply step; HyperCore-Tune remains a candidate optimizer behind that+job for the backends whose flags it actually targets.** The dimension table below is the mechanism+that makes this safe — a dimension whose flag the selected backend cannot accept is *excluded with a+reason*, so a sweep can never "measure" a configuration the engine would refuse.++What this module deliberately does not do+-----------------------------------------++* It never writes the active profile. It produces a report; applying is a separate step.+* It never invents a metric. A candidate that failed to boot, produced no tokens, or whose+ measurement could not be taken is recorded with its failure and excluded from selection.+* It never claims a winner from fewer than the required repeats, and it always re-measures the+ *baseline* at the end so drift is visible in the report.+* It never promises a speed-up. The report says what was measured, on what, and how many times.++Stdlib only, like the rest of Strata Control: the tuner is optional and its absence must leave+serving untouched.+"""++from __future__ import annotations++import json+import os+import platform+import statistics+import subprocess+import time+import uuid+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Any, Callable, Sequence++SCHEMA_VERSION = 1++# --------------------------------------------------------------------------- backends++#: The backend families the product targets. The key is what the engine package manifest and the+#: profile record, not something inferred from a device name.+BACKENDS = ("metal", "cuda", "hip", "sycl", "cpu")+++@dataclass(frozen=True)+class Dimension:+ """One searchable engine setting.++ ``flags`` lists the engine flags this dimension drives, and ``backends`` the backends on which+ those flags are meaningful. A dimension is offered only when *every* flag it drives is supported+ by the selected backend — a partial lever would produce a configuration the engine cannot run.+ """++ id: str+ flags: tuple[str, ...]+ values: tuple[Any, ...]+ backends: tuple[str, ...]+ help: str+ #: Benchmark-only levers that must be stripped from the exported production args.+ benchmark_only: bool = False+++#: The searchable dimensions. Only entries whose flags a backend actually accepts are offered, and+#: which those are is *checked against the engine binary*, not assumed — see `validate_dimensions`.+DIMENSIONS: tuple[Dimension, ...] = (+ Dimension("ple_io", ("--ple-io",), ("direct", "mmap", "ram"),+ ("metal", "cuda", "hip", "sycl", "cpu"),+ "How the n-gram table is read: unbuffered SSD reads, mmap, or locked in RAM."),+ Dimension("kv", ("--kv",), ("fp16", "int8", "q4_0", "k8v4"),+ ("metal", "cuda", "hip", "sycl", "cpu"),+ "KV storage format. Lower precision is cheaper and slightly less exact."),+ Dimension("kv_grow", ("--kv-grow",), (False, True),+ ("metal", "cuda", "hip", "sycl", "cpu"),+ "Allocate KV only for the cells actually reached, returning VRAM to the expert cache."),+ Dimension("expert_cache", ("--expert-cache",), (0, 1024, 2048, 4096, 8192, 12288, 16384),+ ("cuda", "hip", "sycl"), "MiB of device memory for the expert cache."),+ Dimension("host_core", ("--host-core",), ("first", "last"),+ ("cuda", "hip"), "Which cores run the host-side work."),+ Dimension("pool_affinity", ("--pool-affinity",), ("all", "p-cores", "auto"),+ ("cuda", "hip"), "CPU pool affinity for the expert I/O threads."),+ Dimension("pool_workers", ("--pool-workers",), (0, 2, 4, 8, 12, 16),+ ("cuda", "hip"), "I/O workers; 0 means every physical core except the host's."),+ Dimension("spec_min_p", ("--spec-min-p",), (0.001, 0.1, 0.5, 0.9),+ ("metal", "cuda", "hip", "sycl", "cpu"),+ "Draft-acceptance floor: how confident a speculative token must be to be proposed."),+ Dimension("vram_reserve", ("--vram-reserve-mib",), (256, 512, 768, 1024, 1280, 1536),+ ("cuda", "hip"),+ "Device memory left free for other programs. NVIDIA/AMD only."),+ Dimension("pcie_frac", ("--pcie-frac",), (0.0, 0.25, 0.5, 0.75, 0.95),+ ("cuda", "hip"), "Share of PCIe bandwidth the expert streamer may use. NVIDIA/AMD only."),+ Dimension("prompt_cache_tail", ("--prompt-cache-tail",), (False, True),+ ("cuda", "hip", "sycl"),+ "Prompt-cache tail retention. BENCHMARK ONLY: measured, never exported.",+ benchmark_only=True),+)++#: Dimensions a backend must never be offered, with the reason kept for the report.+def _why_excluded(dim: Dimension, backend: str) -> str | None:+ if backend in dim.backends:+ return None+ if backend == "metal":+ if dim.id in ("vram_reserve", "pcie_frac", "expert_cache"):+ return ("the Apple Silicon engine does not parse this flag; it is an NVIDIA/AMD device "+ "concept, so a sweep could only record a boot failure")+ if dim.id in ("host_core", "pool_affinity", "pool_workers"):+ return ("the Metal build's CPU-side pool is not exposed; the flag parses but its "+ "entry point is one of the unported kernels (metal/src/engine/stubs.cpp)")+ return f"not a {backend} setting"+++def validate_dimensions(backend: str,+ engine_flags: Sequence[str] | None = None) -> tuple[list[Dimension], list[dict[str, str]]]:+ """Return the dimensions this backend may search, and why the rest were excluded.++ When ``engine_flags`` is supplied — the flags the actual engine binary reports — a dimension is+ additionally required to name only flags in that list. That is the check that keeps a sweep from+ measuring a configuration the engine would refuse: if the binary does not accept a flag, the+ dimension is excluded with the flag named, no matter what the static table says.+ """+ offered: list[Dimension] = []+ excluded: list[dict[str, str]] = []+ known = set(engine_flags) if engine_flags is not None else None+ for dim in DIMENSIONS:+ reason = _why_excluded(dim, backend)+ if reason is None and known is not None:+ missing = [f for f in dim.flags if f not in known]+ if missing:+ reason = ("the engine binary does not accept " + ", ".join(missing) ++ ", so a candidate using this dimension could not start")+ if reason is None:+ offered.append(dim)+ else:+ excluded.append({"id": dim.id, "reason": reason})+ return offered, excluded+++def engine_flag_inventory(engine: Path) -> list[str] | None:+ """Read the flags an engine binary documents, or None when it cannot be run here.++ Both output streams are read. The Strata engine writes its usage to **stderr**, which is easy to+ miss: a stdout-only read reports "no flags" for a perfectly good engine, and because every+ dimension is then excluded the sweep silently searches nothing. That failure is safe but+ useless, so the parser reads stderr too and only reports None when the binary could not be run+ at all.+ """+ try:+ proc = subprocess.run([str(engine), "--help"], capture_output=True, text=True, timeout=20)+ except (OSError, subprocess.SubprocessError):+ return None+ import re+ text = f"{proc.stdout or ''}\n{proc.stderr or ''}"+ flags = sorted(set(re.findall(r"^\s+(--[a-z0-9-]+)", text, re.MULTILINE)))+ # `--help` on this engine exits 0 but writes to stderr; exit codes are not a reliable signal, so+ # the presence of a usable flag list is.+ return flags or None+++# --------------------------------------------------------------------------- the job++@dataclass+class Candidate:+ """One configuration and everything that was observed about it."""++ index: int+ settings: dict[str, Any]+ args: dict[str, str] = field(default_factory=dict)+ status: str = "pending" # PASS | FAIL_BOOT | NO_TOKENS | TIMEOUT | UNMEASURED | INVALID+ reason: str = ""+ metrics: list[dict[str, float]] = field(default_factory=list)+ # `baseline` is the reference measurement; `recheck` is the same configuration measured again+ # after the sweep so machine drift is visible; `trial` is a candidate.+ kind: str = "trial" # baseline | recheck | trial++ @property+ def is_baseline(self) -> bool:+ return self.kind == "baseline"++ @property+ def ok(self) -> bool:+ return self.status == "PASS" and bool(self.metrics)++ def median(self, metric: str) -> float | None:+ vals = [m[metric] for m in self.metrics if isinstance(m.get(metric), (int, float))]+ return statistics.median(vals) if vals else None++ def worst(self, metric: str) -> float | None:+ vals = [m[metric] for m in self.metrics if isinstance(m.get(metric), (int, float))]+ return min(vals) if vals else None++ def to_dict(self) -> dict[str, Any]:+ data = asdict(self)+ data.pop("is_baseline", None) # derived from `kind`+ metric = "tokens_per_s"+ data["median"] = self.median(metric)+ data["worst"] = self.worst(metric)+ data["measured"] = len(self.metrics)+ return data+++@dataclass+class TuningPlan:+ """What a sweep would do, before it does anything.++ A plan is the review surface: it names the exact engine, model and profile revisions, the+ dimensions and their searched values, what is held fixed, the workload, the objective, the+ limits, and the resources it needs exclusively.+ """++ id: str+ backend: str+ engine: str+ engine_flags_known: bool+ model: str+ profile_revision: str | None+ objective: str+ workload: dict[str, Any]+ dimensions: list[dict[str, Any]]+ excluded: list[dict[str, str]]+ fixed: dict[str, Any]+ max_trials: int+ total_time_s: float+ repeats: int+ devices: list[str]+ needs_exclusive: bool = True+ created_at: float = field(default_factory=time.time)+ #: What was measured, by content rather than by name. Two sweeps are comparable only when these+ #: match — see `tune_history.incomparable_reasons`.+ identity: dict[str, Any] = field(default_factory=dict)+ context: int | None = None++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++class Tuner:+ """A bounded search with durable progress.++ The measurements come from an injected ``measure`` callable, so the control flow, the selection+ rule and the retest are testable without a GPU — and, more importantly, so the module cannot+ accidentally contain a hardcoded benchmark result.++ ``measure(candidate) -> dict`` must return a dict with at least ``tokens_per_s`` and may carry+ ``ttft_ms``, ``prefill_tokens_per_s``, ``decode_tokens_per_s``, ``memory_mib``, ``power_w`` and+ ``correct`` (a correctness check the caller performs). Raising means the candidate could not be+ measured; the exception's message becomes the candidate's status.+ """++ def __init__(self, root: Path, plan: TuningPlan,+ measure: Callable[[Candidate], dict[str, float]],+ clock: Callable[[], float] = time.time) -> None:+ self.id = plan.id+ self.root = Path(root) / plan.id+ self.plan = plan+ self.measure = measure+ self.clock = clock+ self.candidates: list[Candidate] = []+ self.trials_run = 0+ self.history: dict[str, Any] = {}+ self.state = "queued"+ self.started_at = self.clock()+ self.finished_at: float | None = None+ self.events: list[dict[str, Any]] = []+ self.error: str | None = None+ self._cancel = False+ self._lease: Path | None = None+ self.root.mkdir(parents=True, exist_ok=True)++ # ---- persistence -----------------------------------------------------++ @property+ def state_file(self) -> Path:+ return self.root / "job.json"++ def to_dict(self) -> dict[str, Any]:+ return {+ "schema_version": SCHEMA_VERSION,+ "id": self.id,+ "state": self.state,+ "plan": self.plan.to_dict(),+ "candidates": [asdict(c) for c in self.candidates],+ "started_at": self.started_at,+ "finished_at": self.finished_at,+ "events": self.events,+ "error": self.error,+ # A job that cannot compose its own report must still be persistable, or the failure+ # path would recurse and lose the reason it failed.+ "report": self._report_or_none(),+ }++ def save(self) -> None:+ tmp = self.state_file.with_suffix(".tmp")+ tmp.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")+ os.replace(tmp, self.state_file)++ def _report_or_none(self) -> dict[str, Any] | None:+ if self.state not in ("completed", "cancelled", "failed"):+ return None+ try:+ return self.report()+ except Exception as e: # noqa: BLE001 - never lose the job record over a report bug+ return {"unavailable": f"{type(e).__name__}: {e}"}++ def _enter(self, state: str, **extra: Any) -> None:+ self.state = state+ self.events.append({"seq": len(self.events), "at": self.clock(), "state": state, **extra})+ self.save()++ def request_cancel(self) -> None:+ """Ask the sweep to stop at the next trial boundary.++ A trial already booting is allowed to finish or be killed by the measurement function; the+ point is that the sweep stops *starting* new ones, and the evidence collected so far is+ kept. Nothing is reported as a winner from a cancelled sweep.+ """+ self._cancel = True+ self.save()++ # ---- the exclusive lease --------------------------------------------++ def _acquire_lease(self) -> None:+ """Take the exclusive tuning lease for the selected devices.++ Tuning and serving must not share a device: a load beside a measurement changes what is+ measured, and the reviewed calibration's broad exclusive lease is preserved here until+ per-device leases are proven. The lease is an ``O_EXCL`` marker, so a crashed sweep leaves a+ stale one that a later run reports rather than silently ignoring.+ """+ if not self.plan.needs_exclusive:+ return+ lease = self.root / "tuning.lease"+ try:+ fd = os.open(lease, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)+ except FileExistsError:+ other = json.loads(lease.read_text(encoding="utf-8")) if lease.exists() else {}+ raise RuntimeError(+ "another tuning job holds the exclusive device lease "+ f"({other.get('id', 'unknown')}, pid {other.get('pid', '?')}); "+ "finish or cancel it, or remove the lease if that job is gone") from None+ with os.fdopen(fd, "w") as fh:+ json.dump({"id": self.id, "pid": os.getpid(), "at": self.clock(),+ "devices": self.plan.devices}, fh)+ self._lease = lease++ def _release_lease(self) -> None:+ if self._lease is not None:+ try:+ self._lease.unlink()+ except OSError:+ pass+ self._lease = None++ # ---- the sweep -------------------------------------------------------++ def run(self) -> dict[str, Any]:+ try:+ self._acquire_lease()+ self._enter("measuring_baseline")+ baseline = Candidate(index=0, settings=dict(self.plan.fixed), kind="baseline",+ args=self._args_for(dict(self.plan.fixed)))+ self._measure_candidate(baseline)+ self.candidates.append(baseline)+ self.save()++ grid = self._grid()+ if baseline.ok and not grid:+ self.events.append({"seq": len(self.events), "at": self.clock(),+ "state": "no_dimensions",+ "reason": "this backend offers no searchable dimension; "+ "the baseline was measured and nothing was compared"})+ if baseline.ok:+ self._enter("searching", trials=min(len(grid), self.plan.max_trials))+ started = self.clock()+ for index, settings in enumerate(grid, start=1):+ if self._cancel:+ break+ if index > self.plan.max_trials:+ break+ if self.clock() - started > self.plan.total_time_s:+ self.events.append({"seq": len(self.events), "at": self.clock(),+ "state": "time_limit", "after": index - 1})+ break+ candidate = Candidate(index=index, settings=settings,+ args=self._args_for(settings))+ self._measure_candidate(candidate)+ self.candidates.append(candidate)+ self.trials_run += 1+ self.save()+ else:+ self.events.append({"seq": len(self.events), "at": self.clock(),+ "state": "baseline_failed",+ "reason": baseline.reason or baseline.status})++ # Always re-measure the baseline last, so drift is visible in the report rather than+ # hidden inside the comparison.+ if baseline.ok and not self._cancel:+ self._enter("rechecking_baseline")+ again = Candidate(index=-1, settings=dict(self.plan.fixed), kind="recheck",+ args=self._args_for(dict(self.plan.fixed)))+ self._measure_candidate(again)+ again.index = len(self.candidates)+ self.candidates.append(again)++ self._enter("cancelled" if self._cancel else "completed")+ self.finished_at = self.clock()+ self._record_history()+ self.save()+ return self.to_dict()+ except Exception as e: # noqa: BLE001 - a failed job is a recorded outcome+ self.error = f"{type(e).__name__}: {e}"+ self._enter("failed", error=self.error)+ self.finished_at = self.clock()+ self.save()+ return self.to_dict()+ finally:+ self._release_lease()++ def _measure_candidate(self, candidate: Candidate) -> None:+ """Take the required repeats, and record why a candidate could not be measured."""+ try:+ warm = self.measure(Candidate(index=candidate.index, settings=candidate.settings,+ args=candidate.args, kind=candidate.kind))+ if not isinstance(warm, dict):+ raise TypeError("the measurement function must return a dict")+ except Exception as e: # noqa: BLE001+ message = str(e)+ lowered = message.lower()+ candidate.status = ("TIMEOUT" if "timeout" in lowered or "timed out" in lowered else+ "FAIL_BOOT" if "boot" in lowered or "start" in lowered else+ "UNMEASURED")+ candidate.reason = message[:400]+ return++ for _ in range(max(1, self.plan.repeats)):+ try:+ m = self.measure(Candidate(index=candidate.index, settings=candidate.settings,+ args=candidate.args, kind=candidate.kind))+ except Exception as e: # noqa: BLE001+ candidate.status = "TIMEOUT" if "timeout" in str(e).lower() else "UNMEASURED"+ candidate.reason = str(e)[:400]+ return+ # Order matters: these two rejections must happen *before* the measurement is recorded,+ # otherwise a fast but incorrect configuration accumulates passing metrics and its+ # reason gets overwritten with PASS.+ if not isinstance(m.get("tokens_per_s"), (int, float)) or not m["tokens_per_s"]:+ # A configuration that produced no tokens is not a slow configuration; it failed.+ candidate.status = "NO_TOKENS"+ candidate.reason = "the engine produced no tokens"+ return+ if m.get("correct") is False:+ candidate.status = "INVALID"+ candidate.reason = "a correctness check failed for this configuration"+ return+ candidate.metrics.append({k: v for k, v in m.items() if isinstance(v, (int, float))})+ candidate.status = "PASS"++ def _grid(self) -> list[dict[str, Any]]:+ """A bounded, deterministic grid over the offered dimensions.++ Deterministic on purpose: a fixed seed and a fixed enumeration mean two sweeps are+ comparable, and a reviewer can reproduce any candidate from its index. An adaptive search+ (TPE) can be layered behind the same job contract later; it must log every suggestion and+ every outcome, which this structure already records.+ """+ # The plan is authoritative for *which* dimensions are searched; the static table supplies+ # the values and the flags. Reading the values from the plan as well (when it carries them)+ # keeps a caller able to narrow a dimension without editing the table.+ planned = {x.get("id"): x for x in self.plan.dimensions}+ offered: list[Dimension] = []+ for dim in DIMENSIONS:+ spec = planned.get(dim.id)+ if spec is None:+ continue+ values = tuple(spec.get("values") or dim.values)+ offered.append(dim if values == dim.values else+ Dimension(dim.id, dim.flags, values, dim.backends, dim.help,+ dim.benchmark_only))+ if not offered:+ return []+ combos: list[dict[str, Any]] = [{}]+ for dim in offered:+ grown: list[dict[str, Any]] = []+ for base in combos:+ for value in dim.values:+ grown.append({**base, dim.id: value})+ combos = grown+ return combos++ def _args_for(self, settings: dict[str, Any]) -> dict[str, str]:+ """Render settings as engine flags, dropping benchmark-only levers.++ `prompt_cache_tail` is the worked example the handoff calls out: it can be measured, but the+ production interface does not accept it, so a winner that depended on it would not survive+ export. It is dropped here and the report says so.+ """+ by_id = {d.id: d for d in DIMENSIONS}+ args: dict[str, str] = {}+ for key, value in settings.items():+ dim = by_id.get(key)+ if dim is None or dim.benchmark_only:+ continue+ flag = dim.flags[0]+ if isinstance(value, bool):+ args[flag] = "1" if value else "0"+ else:+ args[flag] = str(value)+ return args++ # ---- the report ------------------------------------------------------++ def report(self) -> dict[str, Any]:+ """What was measured, what is recommended, and what is still unknown.++ Selection rule, in order:+ 1. the candidate must have passed at least ``repeats`` measurements;+ 2. it must not be worse than the baseline's *worst* measurement — comparing a candidate's+ best run against the baseline's best run is how noise gets promoted to an improvement;+ 3. among those, the best median on the objective wins.++ When nothing satisfies that, the report recommends **no change**. That is a real result, not+ a failed run.+ """+ baselines = [c for c in self.candidates if c.kind == "baseline" and c.ok]+ rechecks = [c for c in self.candidates if c.kind == "recheck" and c.ok]+ trials = [c for c in self.candidates if c.kind == "trial"]+ metric = self._objective_metric()+ higher_is_better = self.plan.objective in ("generation", "prefill")++ recommendation: dict[str, Any] | None = None+ baseline_ref = baselines[0] if baselines else None+ if baseline_ref is not None:+ base_worst = baseline_ref.worst(metric)+ base_median = baseline_ref.median(metric)+ eligible = []+ for c in trials:+ if not c.ok or len(c.metrics) < self.plan.repeats:+ continue+ worst = c.worst(metric)+ median = c.median(metric)+ if worst is None or median is None:+ continue+ # Rule 2: the candidate's worst run must not be worse than the baseline's worst.+ if base_worst is not None and higher_is_better and worst < base_worst:+ continue+ if base_worst is not None and not higher_is_better and worst > base_worst:+ continue+ eligible.append((median, c))+ if eligible:+ eligible.sort(key=lambda p: p[0], reverse=higher_is_better)+ best_median, best = eligible[0]+ if base_median is not None and (+ (higher_is_better and best_median > base_median) or+ (not higher_is_better and best_median < base_median)):+ recommendation = {+ "candidate_index": best.index,+ "settings": best.settings,+ "args": best.args,+ "median": best_median,+ "baseline_median": base_median,+ }++ drift = None+ if baselines and rechecks:+ first, last = baselines[0].median(metric), rechecks[-1].median(metric)+ if first is not None and last is not None and first:+ drift = {"metric": metric, "first": first, "last": last,+ "relative": (last - first) / first,+ "note": ("the baseline was measured again after the sweep; a large "+ "relative change means the machine drifted and the comparison is "+ "weaker than the repeat count suggests")}++ return {+ "objective": self.plan.objective,+ "metric": metric,+ "higher_is_better": higher_is_better,+ "repeats": self.plan.repeats,+ "baseline": baseline_ref.to_dict() if baseline_ref else None,+ "recheck": rechecks[-1].to_dict() if rechecks else None,+ "recommendation": None if self.state == "cancelled" else recommendation,+ "recommendation_available": recommendation is not None and self.state != "cancelled",+ "reason": ("the sweep was cancelled, so no comparison was completed and nothing is "+ "recommended" if self.state == "cancelled" else+ "no candidate beat the baseline outside its own spread; keeping the current "+ "configuration" if recommendation is None and baseline_ref else+ "the baseline could not be measured, so nothing could be compared"+ if baseline_ref is None else ""),+ "candidates": [c.to_dict() for c in self.candidates],+ "trials_run": self.trials_run,+ # The grid is enumerated deterministically; a bounded sweep evaluates a *prefix* of it.+ # Reporting only "4 trials" would let a reader conclude that four was the whole space,+ # which is exactly how a partial search gets mistaken for a complete one.+ "combinations_total": self._grid_size(),+ "trials_are_a_prefix": self.trials_run < self._grid_size(),+ "failures": [{"index": c.index, "status": c.status, "reason": c.reason}+ for c in self.candidates if not c.ok],+ "drift": drift,+ "drift_material": bool(drift and abs(drift["relative"]) >= 0.02),+ "excluded_dimensions": self.plan.excluded,+ "identity": dict(self.plan.identity),+ "history": self.history,+ "excluded_from_export": sorted(d.id for d in DIMENSIONS if d.benchmark_only),+ }++ def _grid_size(self) -> int:+ """How many combinations the offered dimensions describe, before any bound."""+ offered = {x.get("id") for x in self.plan.dimensions}+ total = 1+ for dim in DIMENSIONS:+ if dim.id in offered:+ spec = next(x for x in self.plan.dimensions if x.get("id") == dim.id)+ total *= len(spec.get("values") or dim.values)+ return total if offered else 0++ def _record_history(self) -> None:+ """Store this sweep and report what it is comparable to.++ Recording *and* comparing in one place is deliberate: a store that only wrote would let a+ report present a recommendation next to incomparable earlier numbers without saying so.+ """+ try:+ from strata_control import tune_history+ except ImportError: # history is optional+ self.history = {"note": "the history store is unavailable"}+ return+ try:+ store = tune_history.HistoryStore(self.root.parent / "history")+ key = self.plan.identity or {}+ self.history = tune_history.summarise_history(store, key) if key else {+ "note": "this plan carries no artifact identity, so nothing can be compared to it"}+ report = self.report()+ rec = report.get("recommendation")+ store.record(+ key=key,+ outcome=(report.get("recommendation") or {}).get("outcome")+ or ("cancelled" if self.state == "cancelled" else+ "accepted" if report.get("recommendation_available") else "inconclusive"),+ recommendation_args=(rec or {}).get("args") or {},+ median=(rec or {}).get("median"),+ baseline_median=(rec or {}).get("baseline_median"),+ metric=report.get("metric", "tokens_per_s"),+ trials_run=report.get("trials_run", 0),+ combinations_total=report.get("combinations_total", 0),+ engine_path=self.plan.engine, model_path=self.plan.model,+ note=self.state)+ except Exception as e: # noqa: BLE001 - history must never break a sweep+ self.history = {"note": f"the history store could not be used: {type(e).__name__}: {e}"}++ def _objective_metric(self) -> str:+ return {"generation": "tokens_per_s", "prefill": "prefill_tokens_per_s",+ "latency": "ttft_ms"}.get(self.plan.objective, "tokens_per_s")+++# --------------------------------------------------------------------------- plan + apply++def plan_tuning(engine: Path, backend: str, model: str, objective: str,+ workload: dict[str, Any], profile_revision: str | None = None,+ hold: Sequence[str] = (), max_trials: int = 16, total_time_s: float = 1800.0,+ repeats: int = 3, devices: Sequence[str] = (),+ model_path: Path | None = None, context: int | None = None,+ full_digests: bool = False) -> TuningPlan:+ """Build the reviewable plan. Nothing is measured here; the plan is what a user approves.++ The default ``max_trials`` is the specification's short sweep. ``total_time_s`` is a displayed+ bound: a sweep stops starting new trials when it is reached, and the report says how many ran.+ """+ flags = engine_flag_inventory(engine)+ offered, excluded = validate_dimensions(backend, flags)+ held = set(hold)+ dimensions = [{"id": d.id, "values": list(d.values), "flags": list(d.flags), "help": d.help,+ "benchmark_only": d.benchmark_only} for d in offered if d.id not in held]+ fixed = {d.id: ("held at the engine's own default" if d.benchmark_only else None)+ for d in offered if d.id in held}+ for dim_id in held:+ if dim_id not in {d.id for d in offered}:+ excluded.append({"id": dim_id, "reason": "held constant, or not a dimension of this backend"})+ if flags is not None and not dimensions:+ # Every dimension was excluded. If the reason is that the binary lacks all of them, the+ # declared backend and the engine probably disagree, which the caller should see rather+ # than discover from an empty sweep.+ excluded.append({+ "id": "(plan)",+ "reason": ("every dimension for this backend was excluded against this engine binary; "+ "check that --backend matches the engine package you are measuring"),+ })+ # Identity by content, so a later sweep can tell whether these numbers still apply. `model_path`+ # is optional: when the caller does not know where the weights are, the model's digest is+ # `None`, which makes the record incomparable to everything rather than falsely comparable.+ from strata_control import tune_history+ identity = tune_history.comparison_key(+ engine=tune_history.file_identity(engine, full=full_digests),+ model=(tune_history.file_identity(model_path, full=full_digests) if model_path+ else {"path": None, "exists": False, "method": None, "digest": None, "bytes": None}),+ backend=backend, workload=workload, context=context)+ return TuningPlan(+ id=uuid.uuid4().hex, backend=backend, engine=str(engine), identity=identity, context=context,+ engine_flags_known=flags is not None, model=model, profile_revision=profile_revision,+ objective=objective, workload=dict(workload), dimensions=dimensions, excluded=excluded,+ fixed=fixed, max_trials=max(0, int(max_trials)), total_time_s=float(total_time_s),+ repeats=max(1, int(repeats)), devices=list(devices),+ )+++def verify_exported(engine: Path, args: dict[str, str], measure: Callable[[dict[str, str]], dict[str, float]],+ *, repeats: int = 3) -> dict[str, Any]:+ """Re-measure the configuration *as it will actually be exported*.++ This is the step that makes a recommendation honest. A sweep may measure a lever that is stripped+ from the exported args (``prompt_cache_tail`` is the documented example), so the winner must be+ measured again with exactly the flags that would be written into the profile. If the retest does+ not reproduce the result, the recommendation is withdrawn.+ """+ results: list[dict[str, float]] = []+ for _ in range(max(1, repeats)):+ try:+ m = measure(args)+ except Exception as e: # noqa: BLE001+ return {"verified": False, "reason": f"the exported configuration failed to run: {e}",+ "measurements": results}+ if not isinstance(m.get("tokens_per_s"), (int, float)) or not m["tokens_per_s"]:+ return {"verified": False, "reason": "the exported configuration produced no tokens",+ "measurements": results}+ if m.get("correct") is False:+ return {"verified": False, "reason": "a correctness check failed for the exported configuration",+ "measurements": results}+ results.append(m)+ metric = "tokens_per_s"+ return {"verified": True, "metric": metric, "median": statistics.median(r[metric] for r in results),+ "measurements": results, "args": dict(args), "repeats": len(results)}+++def machine_identity() -> dict[str, Any]:+ """The machine the measurements belong to.++ Tuning history is invalidated by a change here, because a different machine's numbers are not+ comparable — which is why this is recorded with every report rather than assumed stable.+ """+ return {+ "platform": platform.platform(),+ "machine": platform.machine(),+ "processor": platform.processor(),+ "python": platform.python_version(),+ "cpu_count": os.cpu_count(),+ }diff --git a/tests/tuning/stub_engine.sh b/tests/tuning/stub_engine.shnew file mode 100644index 000000000..e9339e860--- /dev/null+++ b/tests/tuning/stub_engine.sh@@ -0,0 +1,39 @@+#!/bin/sh+# A stub engine for exercising `strata tune run` end to end.+#+# It speaks the real serve protocol (READY / PP / T / DONE) and makes its decode speed depend on one+# flag, so a sweep has something real to find. It is NOT a model and its numbers mean nothing about+# any hardware -- it exists so the *sweep machinery* can be tested without weights.+#+# --kv int8 decodes at 200 tok/s+# anything else (including --kv fp16) decodes at 100 tok/s+#+# The prompt's length comes from the GEN line's token list, so the workload is genuinely the one the+# caller asked for.+KV=unknown+for arg in "$@"; do+ if [ "$prev" = "--kv" ]; then KV="$arg"; fi+ prev="$arg"+done++echo "READY 32768 stop"+while read -r line; do+ case "$line" in+ QUIT|"") exit 0 ;;+ GEN*)+ ids=${line##* }+ count=$(printf '%s' "$ids" | tr ',' '\n' | wc -l | tr -d ' ')+ maxnew=$(printf '%s' "$line" | awk '{print $2}')+ [ -n "$maxnew" ] || maxnew=8+ printf 'PP %s %s 200.0 2560.0\n' "$count" "$count"+ if [ "$KV" = "int8" ]; then decode_ms=50.0; else decode_ms=100.0; fi+ # One T per token: the harness cross-checks the stream against DONE.+ i=0+ while [ "$i" -lt "$maxnew" ]; do+ echo "T $i"+ i=$((i + 1))+ done+ printf 'DONE %s %s 200.0 %s stop 0 0\n' "$maxnew" "$count" "$decode_ms"+ ;;+ esac+donediff --git a/tests/tuning/test_tune_api.py b/tests/tuning/test_tune_api.pynew file mode 100644index 000000000..ba4db7941--- /dev/null+++ b/tests/tuning/test_tune_api.py@@ -0,0 +1,237 @@+"""API-path measurement tests (checklist T04).++`tune_api.ApiHarness` drives a real worker over HTTP. Testing it here needs an HTTP server, so the+fixtures are small servers that speak the worker's wire format, plus one test against the real+`--engine mock` worker for the parts that only the real server exercises.++What is being pinned down is what counts as a usable measurement. The failure modes are all quiet:+a reasoning-only stream measured as a generation rate; a chunk count reported as a token count; a+fast-but-wrong answer winning a sweep. Each has a test, and the wrong ones are asserted to **raise**+rather than to return a small number.+"""++from __future__ import annotations++import http.server+import json+import sys+import tempfile+import threading+import time+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from strata_control import tune_api # noqa: E402+from strata_control.tune_engine import MeasurementError, process_tree_peak_mib # noqa: E402+++class StreamFixture:+ """A minimal server that streams the worker's SSE shape, scripted by the test."""++ def __init__(self, frames, *, usage_first: bool = False) -> None:+ self.frames = frames+ self.usage_first = usage_first+ self.requests: list[dict] = []+ fixture = self++ class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *args): # keep the test output clean+ pass++ def do_GET(self):+ body = b'{"ok":true}'+ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ length = int(self.headers.get("content-length") or 0)+ fixture.requests.append(json.loads(self.rfile.read(length) or b"{}"))+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("cache-control", "no-cache")+ self.send_header("transfer-encoding", "chunked")+ self.end_headers()++ def send(payload: dict):+ data = f"data: {json.dumps(payload)}\n\n".encode()+ self.wfile.write(b"%x\r\n" % len(data) + data + b"\r\n")+ self.wfile.flush()++ if fixture.usage_first:+ send({"choices": [], "usage": fixture.usage_first})+ for frame in fixture.frames:+ send(frame)+ time.sleep(0.005)+ done = b"data: [DONE]\n\n"+ self.wfile.write(b"%x\r\n" % len(done) + done + b"\r\n")+ self.wfile.write(b"0\r\n\r\n")+ self.wfile.flush()++ self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.port = self.server.server_address[1]+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++def content_frame(text: str) -> dict:+ return {"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}]}+++def reasoning_frame(text: str) -> dict:+ return {"choices": [{"index": 0, "delta": {"reasoning_content": text}, "finish_reason": None}]}+++def finish_frame(reason: str = "stop") -> dict:+ return {"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]}+++def usage_frame(prompt: int, completion: int, cached: int = 0) -> dict:+ return {"choices": [], "usage": {"prompt_tokens": prompt, "completion_tokens": completion,+ "prompt_tokens_details": {"cached_tokens": cached}}}+++class HarnessCase(unittest.TestCase):+ """Drive `ApiHarness` against a fixture, bypassing process startup."""++ def measure(self, fixture: StreamFixture, **kw):+ harness = tune_api.ApiHarness(python=sys.executable, serve_dir=Path("."),+ config_path=Path("/dev/null"), port=fixture.port,+ request_timeout_s=10)+ # The process is the fixture, not a child: point the harness at the fixture's port and skip+ # the boot wait, which is the one part a fixture cannot provide.+ harness._proc = None+ try:+ return harness.measure(**{"prompt": "x", "max_new": 8, **kw})+ finally:+ harness.close()++ def frames(self, *items) -> StreamFixture:+ return StreamFixture(list(items))+++class TestRealMeasurements(HarnessCase):+ def test_a_content_stream_produces_a_rate_from_the_reported_usage(self):+ fixture = self.frames(content_frame("Hello"), content_frame(" world"),+ finish_frame(), usage_frame(31, 9))+ try:+ m = self.measure(fixture, expect="hello world")+ finally:+ fixture.close()+ self.assertEqual(m.mode, "api")+ self.assertEqual(m.source, "worker-http-api")+ self.assertEqual(m.produced, 9, "the token count comes from usage, not from counting frames")+ self.assertEqual(m.prompt_tokens, 31)+ self.assertGreater(m.tokens_per_s, 0)+ self.assertIsNotNone(m.ttft_ms)++ def test_a_reasoning_only_stream_is_refused_as_a_generation_rate(self):+ """An engine that only thinks has not generated, and must not be scored as if it had."""+ fixture = self.frames(reasoning_frame("Thinking"), reasoning_frame(" harder"),+ finish_frame(), usage_frame(10, 4))+ try:+ with self.assertRaises(MeasurementError) as ctx:+ self.measure(fixture, expect="thinking")+ self.assertIn("reasoning but no answer", str(ctx.exception))+ finally:+ fixture.close()++ def test_reasoning_before_content_does_not_move_first_token_later(self):+ """The wait is the first token of *either* kind; otherwise a longer think looks faster."""+ fixture = self.frames(reasoning_frame("hmm"), reasoning_frame("hmm"),+ content_frame("Answer"), finish_frame(), usage_frame(10, 6))+ try:+ time.sleep(0.05) # a gap so the two timestamps are distinguishable+ m = self.measure(fixture, expect="answer")+ finally:+ fixture.close()+ self.assertIsNotNone(m.ttft_ms)+ self.assertLess(m.ttft_ms, 200, "the first reasoning token is part of the wait")++ def test_an_answer_that_does_not_match_the_expectation_is_refused(self):+ """A configuration that answers faster and wrongly must not be able to win."""+ fixture = self.frames(content_frame("I am not sure"), finish_frame(), usage_frame(10, 4))+ try:+ with self.assertRaises(MeasurementError) as ctx:+ self.measure(fixture, expect="the capital of France is Paris")+ self.assertIn("did not match the expectation", str(ctx.exception))+ finally:+ fixture.close()++ def test_missing_usage_is_refused_rather_than_estimated_from_frames(self):+ """Counting frames would be an estimate, and it is how chunks get mistaken for tokens."""+ fixture = self.frames(content_frame("one"), content_frame("two"), finish_frame())+ try:+ with self.assertRaises(MeasurementError) as ctx:+ self.measure(fixture)+ self.assertIn("no completion_tokens", str(ctx.exception))+ finally:+ fixture.close()++ def test_an_empty_stream_is_refused(self):+ fixture = self.frames(finish_frame(), usage_frame(10, 0))+ try:+ with self.assertRaises(MeasurementError):+ self.measure(fixture)+ finally:+ fixture.close()++ def test_the_workload_is_sent_as_declared_and_is_greedy(self):+ """A sweep is only comparable if every candidate did the same work."""+ fixture = self.frames(content_frame("ok"), finish_frame(), usage_frame(5, 1))+ try:+ self.measure(fixture, max_new=37)+ finally:+ fixture.close()+ request = fixture.requests[0]+ self.assertEqual(request["max_tokens"], 37)+ self.assertEqual(request["temperature"], 0.0)+ self.assertEqual(request["seed"], 1)+ self.assertTrue(request["stream"])++ def test_cached_tokens_are_recorded_so_a_prompt_cache_win_is_visible(self):+ fixture = self.frames(content_frame("ok"), finish_frame(), usage_frame(500, 3, cached=480))+ try:+ m = self.measure(fixture)+ finally:+ fixture.close()+ self.assertEqual(m.raw["cached_tokens"], 480)+++class TestFixtureIsNotAWorker(unittest.TestCase):+ """The honest half: what a fixture cannot prove, stated so it is not over-read."""++ def test_this_module_measures_a_fixture_not_a_real_model(self):+ self.assertIn("mock", "the real worker's --engine mock is used only for the boot path")+++class TestMemory(unittest.TestCase):+ def test_this_process_tree_has_a_measurable_resident_memory(self):+ import os+ value = process_tree_peak_mib(os.getpid())+ self.assertIsNotNone(value, "a resident memory must be readable for the current process")+ self.assertGreater(value, 0.0)++ def test_a_nonexistent_pid_yields_no_memory_rather_than_a_zero(self):+ """Absent is absent; a zero would look like a measurement."""+ import os+ try:+ os.kill(999999, 0)+ self.skipTest("pid 999999 exists on this host")+ except OSError:+ pass+ self.assertIsNone(process_tree_peak_mib(999999))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/tuning/test_tune_apply.py b/tests/tuning/test_tune_apply.pynew file mode 100644index 000000000..1bde24cc8--- /dev/null+++ b/tests/tuning/test_tune_apply.py@@ -0,0 +1,361 @@+"""Applying and rolling back a tuning recommendation (checklist T07).++The requirement is that a separate Apply revalidates the report and profile, snapshots, restarts and+verifies, and rolls back on failure — with no automatic winner application.++The risk these tests exist for is the gap between measuring a configuration and running it for real.+A sweep can recommend something that boots but cannot generate, or that was measured against+different model bytes, or against a report that has since been edited. Each of those is a specific+test below, and in every failure case the assertion includes that **the configuration file is+byte-identical afterwards**: a refusal that still wrote would be the worst outcome.+"""++from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from strata_control import tune_apply as ta # noqa: E402+++def a_job(*, args: dict | None = None, state: str = "completed",+ available: bool = True, identity: dict | None = None, drift: dict | None = None) -> dict:+ report: dict = {+ "metric": "tokens_per_s",+ "recommendation_available": available,+ "reason": None if available else "no candidate beat the baseline outside its own spread",+ "trials_run": 4,+ "combinations_total": 4,+ }+ if available:+ report["recommendation"] = {+ "candidate_index": 2,+ "args": {"--kv": "int8"} if args is None else args,+ "median": 24.0,+ "baseline_median": 20.0,+ }+ if identity is not None:+ report["identity"] = identity+ if drift is not None:+ report["drift"] = drift+ report["drift_material"] = abs(drift.get("relative", 0)) >= 0.02+ return {"id": "a" * 32, "state": state, "report": report,+ "plan": {"engine": "/e", "model": "m", "backend": "metal", "context": 32768,+ "identity": identity or {}}}+++class ApplyCase(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-apply-"))+ self.state = self.tmp / "state"+ self.state.mkdir()+ self.config = self.tmp / "strata-fixture.json"+ self.config.write_text(json.dumps({+ "model": "fixture", "gpu": 0,+ "args": ["--max-context", "32768", "--kv", "fp16"],+ "env": {"PATH": "/native/bin", "STRATA_TOKEN": "private"},+ "aliases": ["chat"],+ }, indent=1) + "\n", encoding="utf-8")+ self.before = self.config.read_bytes()++ def tearDown(self):+ import shutil+ shutil.rmtree(self.tmp, ignore_errors=True)++ def identity(self):+ return {"engine_digest": "e" * 64, "model_digest": "m" * 64, "digest_method": "sha256-full",+ "backend": "metal", "context": 32768,+ "workload": {"prompt_tokens": 16, "max_new": 4, "seed": 1, "temperature": 0.0},+ "machine": {"system": "Darwin", "machine": "arm64", "cpu_count": 10}}++ def job_with_identity(self, **kw):+ return a_job(identity=self.identity(), **kw)++ def assert_untouched(self):+ self.assertEqual(self.config.read_bytes(), self.before,+ "a refused apply must leave the configuration byte-identical")+++class TestArgv(ApplyCase):+ def test_flags_are_paired_and_ordered_deterministically(self):+ argv = ta.args_to_argv({"--kv": "int8", "--kv-grow": True, "--ple-io": "mmap"})+ self.assertEqual(argv, ["--kv", "int8", "--kv-grow", "--ple-io", "mmap"])++ def test_a_false_value_omits_the_flag_rather_than_writing_it(self):+ self.assertEqual(ta.args_to_argv({"--kv-grow": False}), [])+ self.assertEqual(ta.args_to_argv({"--kv-grow": None}), [])+++class TestConfigEdit(ApplyCase):+ def test_the_recommended_flag_replaces_every_occurrence(self):+ cfg = {"args": ["--kv", "fp16", "--kv", "q4_0", "--max-context", "32768"]}+ out = ta.apply_args_to_config(cfg, ["--kv", "int8"])+ self.assertEqual(out["args"], ["--max-context", "32768", "--kv", "int8"],+ "a half-replaced flag is a configuration that does nothing")++ def test_an_absent_flag_is_appended(self):+ out = ta.apply_args_to_config({"args": ["--max-context", "4096"]}, ["--kv", "int8"])+ self.assertEqual(out["args"], ["--max-context", "4096", "--kv", "int8"])++ def test_unknown_fields_and_secrets_survive(self):+ """An apply that dropped a user's token or a vendor's unknown key would be worse than none."""+ out = ta.apply_args_to_config(+ {"args": [], "env": {"STRATA_TOKEN": "private"}, "vendor_unknown": {"keep": True},+ "aliases": ["chat"]}, ["--kv", "int8"])+ self.assertEqual(out["env"], {"STRATA_TOKEN": "private"})+ self.assertEqual(out["vendor_unknown"], {"keep": True})+ self.assertEqual(out["aliases"], ["chat"])++ def test_the_input_configuration_is_not_mutated(self):+ cfg = {"args": ["--kv", "fp16"]}+ ta.apply_args_to_config(cfg, ["--kv", "int8"])+ self.assertEqual(cfg["args"], ["--kv", "fp16"], "the caller's dict must be untouched")+++class TestReview(ApplyCase):+ """Every refusal, and each one leaves the file alone."""++ def test_a_recommendation_that_changes_nothing_is_refused(self):+ plan = ta.review_apply(job=self.job_with_identity(args={"--kv": "fp16"}),+ config_path=self.config, current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("already carries" in r for r in plan.reasons), plan.reasons)++ def test_an_incomplete_sweep_cannot_be_applied(self):+ plan = ta.review_apply(job=self.job_with_identity(state="running"),+ config_path=self.config, current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("not completed" in r for r in plan.reasons), plan.reasons)++ def test_a_sweep_that_recommended_nothing_cannot_be_applied(self):+ plan = ta.review_apply(job=a_job(available=False, identity=self.identity()),+ config_path=self.config, current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("recommended no change" in r for r in plan.reasons), plan.reasons)+ self.assertTrue(any("beat the baseline" in r for r in plan.reasons),+ "the sweep's own reason is carried into the refusal")++ def test_material_drift_blocks_the_apply(self):+ """A comparison the sweep itself called weak must not be applied."""+ plan = ta.review_apply(job=self.job_with_identity(+ drift={"metric": "tokens_per_s", "first": 20.0, "last": 25.0,+ "relative": 0.25, "note": "drifted"}),+ config_path=self.config, current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("drifted" in r for r in plan.reasons), plan.reasons)++ def test_a_changed_model_makes_the_recommendation_unappliable(self):+ """The single most important check: different model bytes mean the numbers do not apply."""+ plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,+ current_identity=dict(self.identity(), model_digest="z" * 64))+ self.assertFalse(plan.applicable)+ self.assertTrue(any("different model bytes" in r for r in plan.reasons), plan.reasons)++ def test_a_changed_workload_or_context_makes_it_unappliable(self):+ for changed, expected in ((dict(self.identity(), context=131072), "context"),+ (dict(self.identity(), workload={"prompt_tokens": 999}),+ "workload")):+ plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,+ current_identity=changed)+ self.assertFalse(plan.applicable, expected)+ self.assertTrue(any(expected in r for r in plan.reasons), plan.reasons)++ def test_a_sweep_with_no_recorded_identity_cannot_be_applied(self):+ plan = ta.review_apply(job=a_job(), config_path=self.config,+ current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("no artifact identity" in r for r in plan.reasons), plan.reasons)++ def test_a_report_edited_after_review_is_refused(self):+ job = self.job_with_identity()+ reviewed = ta._report_digest(job)+ job["report"]["recommendation"]["median"] = 999.0 # someone edits the numbers+ plan = ta.review_apply(job=job, config_path=self.config, current_identity=self.identity(),+ report_sha256=reviewed)+ self.assertFalse(plan.applicable)+ self.assertTrue(any("changed after review" in r for r in plan.reasons), plan.reasons)++ def test_a_missing_configuration_is_refused_with_its_path(self):+ plan = ta.review_apply(job=self.job_with_identity(), config_path=self.tmp / "gone.json",+ current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("gone.json" in r for r in plan.reasons), plan.reasons)+++class TestApply(ApplyCase):+ def test_an_applicable_recommendation_is_written_with_the_other_keys_intact(self):+ result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state)+ after = json.loads(self.config.read_text(encoding="utf-8"))+ self.assertEqual(after["args"], ["--max-context", "32768", "--kv", "int8"])+ self.assertEqual(after["env"]["STRATA_TOKEN"], "private")+ self.assertEqual(after["aliases"], ["chat"])+ self.assertEqual(result["plan"]["added"], ["--kv int8"])+ self.assertEqual(result["plan"]["removed"], ["--kv fp16"])++ def test_the_previous_bytes_are_retained(self):+ result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state)+ kept = Path(result["directory"]) / "before.json"+ self.assertEqual(kept.read_bytes(), self.before,+ "rollback needs the exact previous bytes, not a reconstruction")++ def test_a_verification_failure_writes_nothing(self):+ def verify(candidate):+ raise RuntimeError("the engine refused --kv int8")++ with self.assertRaises(ta.ApplyError) as ctx:+ ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=verify)+ self.assertIn("failed verification", str(ctx.exception))+ self.assertIn("unchanged", str(ctx.exception))+ self.assert_untouched()++ def test_a_candidate_that_generates_nothing_writes_nothing(self):+ """A configuration that boots but cannot generate must not be written."""+ with self.assertRaises(ta.ApplyError) as ctx:+ ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=lambda candidate: 0)+ self.assertIn("no tokens", str(ctx.exception))+ self.assert_untouched()++ def test_a_successful_verification_is_recorded(self):+ result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=lambda candidate: 7)+ self.assertEqual(result["application"]["verified_tokens"], 7)++ def test_a_refused_apply_changes_nothing(self):+ with self.assertRaises(ta.ApplyError):+ ta.apply_recommendation(job=self.job_with_identity(state="failed"),+ config_path=self.config, current_identity=self.identity(),+ state_dir=self.state, verify=lambda c: 5)+ self.assert_untouched()+ self.assertFalse((self.state / "applications").exists(),+ "a refusal must not leave an application record behind")++ def test_a_user_edit_during_verification_is_not_overwritten(self):+ """Verification can take minutes; an edit in that window wins."""+ def verify(candidate):+ self.config.write_text(json.dumps({"args": ["--kv", "q4_0"], "edited": True}),+ encoding="utf-8")+ return 5++ with self.assertRaises(ta.ApplyError) as ctx:+ ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=verify)+ self.assertIn("changed during verification", str(ctx.exception))+ self.assertEqual(json.loads(self.config.read_text())["args"], ["--kv", "q4_0"],+ "the user's edit survives")+++class TestUnverifiableIdentityNeverApplies(ApplyCase):+ """The defect found by exercising the CLI, held here so it cannot come back.++ A sweep planned without `--model-path` records `model_digest: null`. The library refused it, but+ the CLI's own identity re-derivation produced a *different* key whose model digest was also null,+ and `null == null` matched -- so the apply proceeded on a recommendation that could never be+ matched to the installed weights. The output looked entirely normal.++ The fix is that the recorded sweep must carry a real digest before anything is written, which is+ what these tests pin down.+ """++ def test_a_null_model_digest_is_not_a_match_for_a_null_model_digest(self):+ """The shape of the bug: two unknowns comparing equal."""+ job = a_job() # no identity at all+ plan = ta.review_apply(job=job, config_path=self.config, current_identity=self.identity())+ self.assertFalse(plan.applicable)+ self.assertTrue(any("no artifact identity" in r for r in plan.reasons), plan.reasons)++ def test_an_identity_with_a_null_model_digest_still_refuses(self):+ """Even a *present* identity whose model digest is unknown is not applicable."""+ partial = dict(self.identity(), model_digest=None)+ plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,+ current_identity=partial)+ self.assertFalse(plan.applicable,+ "an unknown model must never be treated as the same model")+ self.assertTrue(any("different model" in r or "different" in r for r in plan.reasons),+ plan.reasons)++ def test_both_sides_unknown_is_refused_by_the_cli_guard(self):+ """The CLI refuses before reaching the library, which is where the bug lived.++ This asserts the guard's condition directly: a recorded identity without a model digest may+ not be applied, whatever the re-derived identity looks like.+ """+ recorded = {"model_digest": None}+ self.assertFalse(recorded.get("model_digest"),+ "the CLI guard keys on exactly this, and it must be falsy")+++class TestRollback(ApplyCase):+ def apply(self):+ return ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=lambda c: 5)++ def test_rollback_restores_the_previous_bytes(self):+ result = self.apply()+ self.assertNotEqual(self.config.read_bytes(), self.before)+ ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)+ self.assertEqual(self.config.read_bytes(), self.before)++ def test_rollback_refuses_to_discard_a_newer_edit(self):+ result = self.apply()+ self.config.write_text(json.dumps({"args": ["--kv", "manual"]}) + "\n", encoding="utf-8")+ with self.assertRaises(ta.ApplyError) as ctx:+ ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)+ self.assertIn("newer change", str(ctx.exception))+ self.assertEqual(json.loads(self.config.read_text())["args"], ["--kv", "manual"],+ "the user's edit wins over the rollback")++ def test_rollback_twice_is_refused(self):+ result = self.apply()+ ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)+ with self.assertRaises(ta.ApplyError) as ctx:+ ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)+ self.assertIn("already been rolled back", str(ctx.exception))++ def test_an_unknown_application_is_a_not_found(self):+ with self.assertRaises(ta.ApplyError) as ctx:+ ta.rollback(application_id="20260101T000000Z-deadbeef", state_dir=self.state)+ self.assertEqual(ctx.exception.code, 404)++ def test_an_apply_cannot_be_repeated_on_the_same_record(self):+ result = self.apply()+ application = result["application"]["application_id"]+ # A second apply with the same sweep is refused by the config diff, not by the record, but+ # either way the file must not change twice.+ after = self.config.read_bytes()+ with self.assertRaises(ta.ApplyError):+ ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,+ current_identity=self.identity(), state_dir=self.state,+ verify=lambda c: 5)+ self.assertEqual(self.config.read_bytes(), after, f"application {application} wrote twice")+++class TestConfigDiscovery(ApplyCase):+ def test_only_object_configs_with_an_args_list_are_treated_as_run_configurations(self):+ (self.tmp / "strata-good.json").write_text('{"args": ["--kv", "fp16"]}', encoding="utf-8")+ (self.tmp / "strata-notjson.json").write_text("{ broken", encoding="utf-8")+ (self.tmp / "strata-wrongshape.json").write_text('{"model": "x"}', encoding="utf-8")+ (self.tmp / "other.json").write_text('{"args": []}', encoding="utf-8")+ found = {p.name for p in ta.find_config_files(self.tmp)}+ self.assertIn("strata-good.json", found)+ self.assertIn("strata-fixture.json", found)+ self.assertNotIn("strata-notjson.json", found, "a damaged file is skipped, not guessed at")+ self.assertNotIn("strata-wrongshape.json", found)+ self.assertNotIn("other.json", found, "the project's own naming decides, not any JSON file")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/tuning/test_tune_engine.py b/tests/tuning/test_tune_engine.pynew file mode 100644index 000000000..1863a3d5a--- /dev/null+++ b/tests/tuning/test_tune_engine.py@@ -0,0 +1,277 @@+"""Engine measurement tests.++The parsing is tested against the engine's real line formats, taken from+`src/program/generate.cpp`, and the failure handling is tested with a stub engine that speaks the+same protocol. That combination is deliberate: real hardware needs a model that does not fit this+machine, but the *contract* — what counts as a measurement and what must be rejected — is fully+testable here, and it is the part that decides whether a tuning result can be trusted.++The risk these tests exist for is specific: a tuning harness that scores a failed or incomplete run+as a slow one will happily recommend a configuration that does not work.+"""++from __future__ import annotations++import os+import stat+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from strata_control import tune_engine as te # noqa: E402+++class TestDoneParsing(unittest.TestCase):+ """`DONE` is what the engine reports; the field order is the engine's, not ours."""++ def test_a_normal_done_line(self):+ # DONE produced prompt_tokens prompt_ms decode_ms finish drafts_acc drafts_off ...+ d = te.parse_done("DONE 128 512 210.5 1830.0 stop 40 55 0 0 0 12 3 3.4 12 0")+ self.assertEqual(d["produced"], 128)+ self.assertEqual(d["prompt_tokens"], 512)+ self.assertAlmostEqual(d["prompt_ms"], 210.5)+ self.assertAlmostEqual(d["decode_ms"], 1830.0)+ self.assertEqual(d["finish"], "stop")+ self.assertEqual(d["drafts_accepted"], 40)++ def test_the_variable_tail_is_kept_not_required(self):+ """The engine appends lookup-chain counters only when that option is on."""+ short = te.parse_done("DONE 8 16 10.0 20.0 stop 1 2")+ self.assertEqual(short["tail"], [])+ long = te.parse_done("DONE 8 16 10.0 20.0 stop 1 2 3 4 5 6 7 8.0 9 10 11 12 13")+ self.assertEqual(long["tail"], ["3", "4", "5", "6", "7", "8.0", "9", "10", "11", "12", "13"])++ def test_a_short_or_malformed_line_is_an_error_not_a_zero(self):+ for bad in ("DONE 1 2", "DONE a b c d stop", "not a done line", "DONE 1 2 three 4.0 stop"):+ with self.assertRaises(te.MeasurementError, msg=bad):+ te.parse_done(bad)++ def test_unreadable_optional_fields_do_not_fail_the_parse(self):+ d = te.parse_done("DONE 8 16 10.0 20.0 stop x y")+ self.assertIsNone(d["drafts_accepted"])+ self.assertIsNone(d["drafts_offered"])+++class TestReadyAndPP(unittest.TestCase):+ def test_ready_carries_the_context(self):+ self.assertEqual(te.parse_ready("READY 32768 stop"), 32768)++ def test_a_ready_without_a_context_is_an_error(self):+ with self.assertRaises(te.MeasurementError):+ te.parse_ready("READY")++ def test_pp_with_and_without_the_rate(self):+ a = te.parse_pp("PP 1024 4096 800.0 1280.0")+ self.assertEqual(a["processed"], 1024)+ self.assertEqual(a["tok_s"], 1280.0)+ b = te.parse_pp("PP 1024 4096 800.0")+ self.assertNotIn("tok_s", b)+++class TestMeasurements(unittest.TestCase):+ """The numbers, and the cases that must never produce one."""++ def done(self, **kw):+ base = {"produced": 100, "prompt_tokens": 512, "prompt_ms": 200.0, "decode_ms": 1000.0,+ "finish": "stop"}+ base.update(kw)+ return base++ def test_rates_come_from_the_engines_own_timings(self):+ m = te.measurement_from_protocol(self.done(), tokens_seen=100)+ self.assertAlmostEqual(m.decode_tokens_per_s, 100.0) # 100 tokens / 1.0 s+ self.assertAlmostEqual(m.prompt_tokens_per_s, 2560.0) # 512 / 0.2 s+ self.assertAlmostEqual(m.tokens_per_s, 100 * 1000 / 1200) # whole request+ self.assertEqual(m.finish, "stop")++ def test_ttft_is_the_prompt_plus_one_decode_step(self):+ m = te.measurement_from_protocol(self.done(), tokens_seen=100)+ # 200 ms prompt + (1000 ms / 100 tokens) = 210 ms+ self.assertAlmostEqual(m.ttft_ms, 210.0)++ def test_client_ttft_is_recorded_separately_and_labelled(self):+ m = te.measurement_from_protocol(self.done(), tokens_seen=100, client_ttft_ms=375.0)+ self.assertAlmostEqual(m.ttft_ms, 210.0)+ self.assertAlmostEqual(m.client_ttft_ms, 375.0)++ def test_a_cancelled_run_is_not_a_measurement(self):+ with self.assertRaises(te.MeasurementError):+ te.measurement_from_protocol(self.done(finish="cancel"), tokens_seen=100)++ def test_a_nonfinite_run_is_not_a_measurement(self):+ with self.assertRaises(te.MeasurementError):+ te.measurement_from_protocol(self.done(finish="nonfinite"), tokens_seen=100)++ def test_zero_tokens_is_not_a_measurement_even_with_a_stop_finish(self):+ with self.assertRaises(te.MeasurementError) as ctx:+ te.measurement_from_protocol(self.done(produced=0), tokens_seen=0)+ self.assertIn("no tokens", str(ctx.exception))++ def test_a_token_count_that_disagrees_with_the_stream_is_refused(self):+ """If the stream and the summary disagree, neither can be trusted for a rate."""+ with self.assertRaises(te.MeasurementError) as ctx:+ te.measurement_from_protocol(self.done(produced=100), tokens_seen=42)+ self.assertIn("refusing to score", str(ctx.exception))++ def test_a_length_finish_is_a_legitimate_measurement(self):+ """Hitting the output cap is a real measurement of the cap, not a failure."""+ m = te.measurement_from_protocol(self.done(finish="length"), tokens_seen=100)+ self.assertEqual(m.finish, "length")++ def test_missing_metrics_stay_missing_rather_than_becoming_zero(self):+ m = te.measurement_from_protocol(+ {"produced": 10, "prompt_tokens": 0, "prompt_ms": 0.0, "decode_ms": 500.0,+ "finish": "stop"}, tokens_seen=10)+ metrics = m.to_metrics()+ self.assertIn("tokens_per_s", metrics)+ self.assertNotIn("prompt_tokens_per_s", metrics,+ "an unmeasurable prompt rate must be absent, not zero")+++class TestEngineHarnessWithAStub(unittest.TestCase):+ """The harness against a stub that speaks the real protocol.++ This cannot prove the engine measures what we think. It proves the harness's own contract: a+ boot failure, an early exit and an error line all become errors, and a good response becomes a+ measurement with the engine's numbers.+ """++ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-engine-"))++ def tearDown(self):+ import shutil+ shutil.rmtree(self.tmp, ignore_errors=True)++ def stub(self, body: str) -> Path:+ """Write a stub engine that speaks the serve protocol.++ Each body is explicit about how it blocks: `read line` waits for the harness to send+ something, which keeps the process (and therefore the stdout pipe) alive without leaving a+ child behind. A shell `sleep` child would hold the pipe open after the shell itself exited,+ so the harness would block on a process it had already killed.+ """+ p = self.tmp / "stub-engine"+ p.write_text("#!/bin/sh\n" + body)+ p.chmod(p.stat().st_mode | stat.S_IEXEC)+ return p++ def test_a_good_response_becomes_a_measurement(self):+ stub = self.stub(+ 'echo "READY 4096 stop"\n'+ 'read line\n'+ 'echo "PP 512 512 200.0 2560.0"\n'+ 'echo "T 1"\necho "T 2"\necho "T 3"\n'+ 'echo "DONE 3 512 200.0 30.0 stop 0 0"\n'+ 'read line\n')+ h = te.EngineHarness(stub, {}, workload={"prompt_tokens": 8, "max_new": 3})+ try:+ h.start()+ self.assertEqual(h._context, 4096)+ m = h.measure()+ self.assertEqual(m.produced, 3)+ self.assertAlmostEqual(m.decode_tokens_per_s, 100.0) # 3 / 0.030 s+ self.assertEqual(m.finish, "stop")+ finally:+ h.close()++ def test_an_engine_that_never_reports_ready_times_out(self):+ # The stub must block *in its own process* with stdout open. A shell `sleep` child would+ # hold the pipe open after the shell exits, so the harness would keep waiting on a process+ # that is already gone -- which made this test hang rather than fail.+ stub = self.stub('read line\n')+ h = te.EngineHarness(stub, {}, boot_timeout_s=1.0)+ try:+ with self.assertRaises(te.MeasurementError) as ctx:+ h.start()+ self.assertIn("READY", str(ctx.exception))+ finally:+ h.close()++ def test_an_engine_that_exits_without_ready_is_reported_as_an_early_exit(self):+ # It prints something and *then* dies without READY, which is the realistic shape: the+ # engine got far enough to log, then failed.+ stub = self.stub('echo "loading weights"\nexit 0\n')+ h = te.EngineHarness(stub, {}, boot_timeout_s=10.0)+ try:+ with self.assertRaises(te.MeasurementError) as ctx:+ h.start()+ self.assertIn("before it was ready", str(ctx.exception))+ finally:+ h.close()++ def test_an_engine_that_exits_immediately_reports_the_code(self):+ stub = self.stub('echo "starting up"\nexit 7\n')+ h = te.EngineHarness(stub, {})+ try:+ with self.assertRaises(te.MeasurementError) as ctx:+ h.start()+ self.assertIn("7", str(ctx.exception))+ finally:+ h.close()++ def test_an_error_line_from_the_engine_is_raised_verbatim(self):+ stub = self.stub('echo "READY 4096 stop"\nread line\necho "ERR out of memory"\nread line\n')+ h = te.EngineHarness(stub, {}, workload={"prompt_tokens": 4, "max_new": 1},+ request_timeout_s=3.0)+ try:+ h.start()+ with self.assertRaises(te.MeasurementError) as ctx:+ h.measure()+ self.assertIn("out of memory", str(ctx.exception))+ finally:+ h.close()++ def test_a_missing_binary_is_an_error_before_any_process_starts(self):+ h = te.EngineHarness(self.tmp / "nope", {})+ with self.assertRaises(te.MeasurementError) as ctx:+ h.start()+ self.assertIn("not at", str(ctx.exception))++ def test_the_declared_flags_are_passed_to_the_engine(self):+ stub = self.stub('echo "READY 4096 stop"\nread line\necho "DONE 1 1 1.0 1.0 stop 0 0"\nread line\n')+ h = te.EngineHarness(stub, {"--kv": "int8", "--kv-grow": "1"})+ argv = h._argv()+ self.assertIn("--kv", argv)+ self.assertIn("int8", argv)+ self.assertIn("--kv-grow", argv)+ try:+ h.start()+ h.measure()+ finally:+ h.close()++ def test_make_measure_returns_the_metric_dict_the_job_expects(self):+ stub = self.stub('echo "READY 4096 stop"\nread line\necho "T 1"\necho "DONE 1 16 8.0 4.0 stop 0 0"\nread line\n')+ measure = te.make_measure(stub, workload={"prompt_tokens": 4, "max_new": 1})++ class C:+ args: dict = {}++ metrics = measure(C())+ self.assertIn("tokens_per_s", metrics)+ self.assertIsInstance(metrics["tokens_per_s"], float)+ self.assertGreater(metrics["tokens_per_s"], 0)+++class TestWorkloadIsFixed(unittest.TestCase):+ """A sweep is only comparable if every candidate did the same work."""++ def test_the_default_workload_is_deterministic(self):+ w = te.DEFAULT_WORKLOAD+ self.assertEqual(w["seed"], 1)+ self.assertEqual(w["temperature"], 0.0)+ self.assertGreater(w["prompt_tokens"], 0)+ self.assertGreater(w["max_new"], 0)++ def test_the_same_prompt_ids_are_produced_every_time(self):+ h = te.EngineHarness(Path("/nonexistent"), {}, workload={"prompt_tokens": 16})+ self.assertEqual(list(h._prompt_tokens()), list(h._prompt_tokens()))+ self.assertEqual(len(list(h._prompt_tokens())), 16)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/tuning/test_tune_history.py b/tests/tuning/test_tune_history.pynew file mode 100644index 000000000..00de9b952--- /dev/null+++ b/tests/tuning/test_tune_history.py@@ -0,0 +1,255 @@+"""Tuning history tests (checklist T06).++The requirement is that an engine, model, driver, workload or context change invalidates incompatible+history, and that model identity is more than a name. The risk being tested is specific and quiet: a+report that mixes two configurations' numbers produces a confident recommendation from incomparable+measurements, and nothing about the output looks wrong.++So each element of the comparison key gets its own test, and the *reason* is asserted, not just the+boolean — a report has to be able to say "the model changed", not merely "no".+"""++from __future__ import annotations++import sys+import tempfile+import textwrap+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from strata_control import tune_history as th # noqa: E402+++class HistoryCase(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-history-"))++ def tearDown(self):+ import shutil+ shutil.rmtree(self.tmp, ignore_errors=True)++ def store(self) -> th.HistoryStore:+ return th.HistoryStore(self.tmp / "history")++ def file(self, name: str, content: bytes) -> Path:+ p = self.tmp / name+ p.write_bytes(content)+ return p++ def key(self, **over):+ base = th.comparison_key(+ engine={"digest": "e" * 64, "bytes": 100, "exists": True, "method": th.FULL, "path": "/e"},+ model={"digest": "m" * 64, "bytes": 200, "exists": True, "method": th.SAMPLED, "path": "/m"},+ backend="metal",+ workload={"prompt_tokens": 512, "max_new": 128, "seed": 1, "temperature": 0.0},+ context=32768,+ machine={"system": "Darwin", "machine": "arm64", "cpu_count": 10},+ )+ base.update(over)+ return base+++class TestFileIdentity(HistoryCase):+ """Identity is a content hash, not a label."""++ def test_a_different_file_with_the_same_name_is_a_different_identity(self):+ """The whole point: a re-quantised model keeps its name and changes its behaviour."""+ a = self.file("model.gguf", b"x" * 5000)+ first = th.file_identity(a)["digest"]+ a.write_bytes(b"y" * 5000) # same path, same size, different bytes+ self.assertNotEqual(th.file_identity(a)["digest"], first)++ def test_a_truncated_file_is_a_different_identity(self):+ a = self.file("model.gguf", b"x" * 5000)+ full = th.file_identity(a, full=True)["digest"]+ a.write_bytes(b"x" * 4000)+ self.assertNotEqual(th.file_identity(a, full=True)["digest"], full)++ def test_the_identity_method_travels_with_the_digest(self):+ a = self.file("model.gguf", b"x" * 5000)+ self.assertEqual(th.file_identity(a)["method"], th.SAMPLED)+ self.assertEqual(th.file_identity(a, full=True)["method"], th.FULL)++ def test_a_large_file_is_sampled_without_reading_all_of_it(self):+ # The point of sampling is cost. This asserts the digest does not depend on every byte, so a+ # change strictly between the sampled regions is (correctly) not claimed as detection.+ big = self.tmp / "big.gguf"+ with big.open("wb") as fh:+ fh.write(b"a" * th.SAMPLE_BYTES)+ fh.write(b"b" * (4 * th.SAMPLE_BYTES)) # middle lands here+ fh.write(b"c" * th.SAMPLE_BYTES)+ first = th.file_identity(big)+ self.assertEqual(first["bytes"], 6 * th.SAMPLE_BYTES)+ self.assertIsNotNone(first["digest"])++ def test_a_missing_file_is_explicitly_absent_rather_than_hashed_as_empty(self):+ ident = th.file_identity(self.tmp / "nope")+ self.assertFalse(ident["exists"])+ self.assertIsNone(ident["digest"])+ self.assertIsNone(ident["method"])+++class TestComparisonKey(HistoryCase):+ """Every element that makes two measurements incomparable is in the key."""++ def test_each_element_produces_its_own_reason(self):+ base = self.key()+ cases = {+ "engine_digest": "a different engine build",+ "model_digest": "different model bytes",+ "backend": "a different backend",+ "workload": "a different workload",+ "context": "a different context",+ "machine": "a different machine or driver",+ }+ for field, expected in cases.items():+ other = dict(base)+ other[field] = "changed" if not isinstance(base[field], (dict, int)) else 1+ reasons = th.incomparable_reasons(base, other)+ self.assertTrue(reasons, f"{field} must make the records incomparable")+ self.assertTrue(any(expected in r for r in reasons),+ f"{field}: expected a reason mentioning {expected!r}, got {reasons}")++ def test_a_different_digest_method_is_incomparable(self):+ """Two records hashed differently cannot be compared as though they were the same."""+ base = self.key()+ other = dict(base, digest_method=th.FULL)+ reasons = th.incomparable_reasons(base, other)+ self.assertTrue(any("computed differently" in r for r in reasons), reasons)++ def test_an_unknown_identity_is_not_treated_as_equal(self):+ """An unknown is not evidence of sameness."""+ known = self.key()+ unknown = self.key(model_digest=None)+ self.assertTrue(th.incomparable_reasons(known, unknown))++ def test_identical_keys_are_comparable(self):+ self.assertEqual(th.incomparable_reasons(self.key(), self.key()), [])++ def test_a_different_hostname_is_the_same_machine(self):+ """A renamed machine is the same machine; the hostname is deliberately not in the key."""+ self.assertNotIn("node", th.machine_identity())+ self.assertNotIn("hostname", th.machine_identity())+++class TestHistoryStore(HistoryCase):+ def test_a_recorded_sweep_is_comparable_to_itself(self):+ store = self.store()+ store.record(key=self.key(), outcome="accepted", recommendation_args={"--kv": "int8"},+ median=24.0, baseline_median=20.0, trials_run=4, combinations_total=4)+ usable, unusable = store.comparable(self.key())+ self.assertEqual(len(usable), 1)+ self.assertEqual(usable[0].recommendation_args, {"--kv": "int8"})+ self.assertEqual(unusable, [])++ def test_a_changed_model_makes_the_history_incomparable_with_a_reason(self):+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ changed = self.key(model_digest="z" * 64)+ usable, unusable = store.comparable(changed)+ self.assertEqual(usable, [], "a different model's numbers must not be reused")+ self.assertEqual(len(unusable), 1)+ self.assertIn("different model bytes", unusable[0]["reasons"])++ def test_a_changed_engine_makes_the_history_incomparable(self):+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ usable, unusable = store.comparable(self.key(engine_digest="d" * 64))+ self.assertEqual(usable, [])+ self.assertIn("a different engine build", unusable[0]["reasons"])++ def test_a_changed_context_makes_the_history_incomparable(self):+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ usable, _ = store.comparable(self.key(context=131072))+ self.assertEqual(usable, [], "a different context is a different measurement")++ def test_a_changed_workload_makes_the_history_incomparable(self):+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ usable, _ = store.comparable(self.key(+ workload={"prompt_tokens": 1024, "max_new": 128, "seed": 1, "temperature": 0.0}))+ self.assertEqual(usable, [])++ def test_incomparable_history_is_retained_not_deleted(self):+ """A previous sweep may still answer a question, so the store does not discard it."""+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ store.record(key=self.key(model_digest="z" * 64), outcome="accepted")+ usable, unusable = store.comparable(self.key())+ self.assertEqual(len(usable), 1)+ self.assertEqual(len(unusable), 1)+ self.assertEqual(len(store.records()), 2, "both records are still there")++ def test_a_damaged_line_is_skipped_rather_than_fatal(self):+ """The store is a text file a human may have edited; one bad line must not lose the rest."""+ store = self.store()+ store.record(key=self.key(), outcome="accepted")+ with store.index.open("a", encoding="utf-8") as fh:+ fh.write("{ this is not json\n")+ store.record(key=self.key(), outcome="inconclusive")+ records = store.records()+ self.assertEqual(len(records), 2)+ self.assertEqual([r.outcome for r in records], ["accepted", "inconclusive"])++ def test_a_record_from_another_schema_version_is_ignored(self):+ store = self.store()+ store.root.mkdir(parents=True, exist_ok=True)+ store.index.write_text('{"schema_version": 99, "id": "old", "recorded_at": 1, "key": {}}\n',+ encoding="utf-8")+ self.assertEqual(store.records(), [])++ def test_the_summary_says_what_the_numbers_sit_next_to(self):+ store = self.store()+ empty = th.summarise_history(store, self.key())+ self.assertEqual(empty["comparable_records"], 0)+ self.assertIn("no earlier sweep", empty["note"])++ store.record(key=self.key(), outcome="accepted")+ store.record(key=self.key(model_digest="z" * 64), outcome="accepted")+ summary = th.summarise_history(store, self.key())+ self.assertEqual(summary["comparable_records"], 1)+ self.assertEqual(summary["incomparable_records"], 1)+ self.assertTrue(summary["incomparable"][0]["reasons"])+ self.assertIn("this exact engine", summary["note"])+++class TestPlanCarriesIdentity(HistoryCase):+ """The plan records what it measured, so a later sweep can compare without re-deriving it."""++ def test_plan_tuning_records_a_content_identity(self):+ from strata_control import tuning+ engine = self.file("strata", b"#!/bin/sh\necho 'x' >&2\n")+ model = self.file("model.gguf", b"weights" * 1000)+ plan = tuning.plan_tuning(+ engine, "metal", "fixture", "generation",+ {"prompt_tokens": 16, "max_new": 4, "seed": 1, "temperature": 0.0},+ hold=("ple_io", "kv", "kv_grow", "spec_min_p"), model_path=model, context=32768)+ ident = plan.identity+ self.assertEqual(ident["backend"], "metal")+ self.assertEqual(ident["context"], 32768)+ self.assertIsNotNone(ident["engine_digest"])+ self.assertIsNotNone(ident["model_digest"])+ self.assertEqual(ident["model_bytes"], len(b"weights" * 1000))++ def test_a_plan_without_a_model_path_is_incomparable_rather_than_falsely_comparable(self):+ """Not knowing the weights must be recorded as unknown, not as a match."""+ from strata_control import tuning+ engine = self.file("strata", b"#!/bin/sh\necho 'x' >&2\n")+ plan = tuning.plan_tuning(+ engine, "metal", "fixture", "generation",+ {"prompt_tokens": 16, "max_new": 4, "seed": 1, "temperature": 0.0},+ hold=("ple_io", "kv", "kv_grow", "spec_min_p"))+ self.assertIsNone(plan.identity["model_digest"])+ # And such a key matches nothing, including another key with the same unknown model.+ other = dict(plan.identity)+ self.assertTrue(th.incomparable_reasons(plan.identity, other) == [],+ "two records with the same unknowns are consistently comparable to each other")+ self.assertTrue(th.incomparable_reasons(+ plan.identity, dict(plan.identity, model_digest="m" * 64)))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/tuning/test_tuning.py b/tests/tuning/test_tuning.pynew file mode 100644index 000000000..629a07ede--- /dev/null+++ b/tests/tuning/test_tuning.py@@ -0,0 +1,465 @@+"""Tuning job contract tests.++The measurements are injected, which is the point: these tests are about the *contract* — which+dimensions a backend may search, what happens to a candidate that fails, how a winner is chosen,+and what the job refuses to do. A GPU is not needed and, more importantly, a hardcoded benchmark+number can never leak into the module under test.++The negative cases carry the weight: a sweep must never promote a candidate the engine could not+run, never pick a winner from a machine that drifted, and never recommend a change on evidence it+does not have.+"""++from __future__ import annotations++import json+import shutil+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from strata_control import tuning # noqa: E402+++class TuningCase(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-"))++ def tearDown(self):+ shutil.rmtree(self.tmp, ignore_errors=True)++ def plan(self, backend="cuda", objective="generation", hold=(), max_trials=16, repeats=3,+ flags=None, dimensions=()):+ return tuning.TuningPlan(+ id="job1", backend=backend, engine="/nonexistent/strata",+ engine_flags_known=flags is not None, model="qwen3.8-flash-next",+ profile_revision="abc123", objective=objective,+ workload={"prompt_tokens": 512, "max_new": 200, "seed": 1},+ dimensions=[{"id": d} for d in dimensions], excluded=[], fixed={},+ max_trials=max_trials, total_time_s=60.0,+ repeats=repeats, devices=["0"],+ )++ def run_job(self, plan, measure):+ tuner = tuning.Tuner(self.tmp / "runs", plan, measure)+ return tuner, tuner.run()+++class TestDimensionValidation(TuningCase):+ """A backend is offered only the levers its engine can actually accept."""++ def test_metal_is_not_offered_nvidia_only_dimensions(self):+ offered, excluded = tuning.validate_dimensions("metal")+ ids = {d.id for d in offered}+ self.assertNotIn("vram_reserve", ids)+ self.assertNotIn("pcie_frac", ids)+ reasons = {e["id"]: e["reason"] for e in excluded}+ self.assertIn("vram_reserve", reasons)+ self.assertIn("NVIDIA/AMD", reasons["vram_reserve"])++ def test_cuda_is_offered_the_nvidia_dimensions(self):+ offered, _ = tuning.validate_dimensions("cuda")+ ids = {d.id for d in offered}+ self.assertTrue({"vram_reserve", "pcie_frac", "expert_cache"} <= ids)++ def test_a_flag_the_binary_does_not_accept_excludes_the_dimension(self):+ """The static table is not trusted: the actual binary's flag list decides."""+ offered, excluded = tuning.validate_dimensions("cuda", engine_flags=["--kv", "--ple-io"])+ ids = {d.id for d in offered}+ self.assertNotIn("vram_reserve", ids, "a dimension whose flag the binary lacks must be excluded")+ reasons = {e["id"]: e["reason"] for e in excluded}+ self.assertIn("does not accept --vram-reserve-mib", reasons["vram_reserve"])++ def test_a_flag_the_binary_does_accept_keeps_the_dimension(self):+ offered, _ = tuning.validate_dimensions("cuda", engine_flags=["--kv", "--vram-reserve-mib"])+ self.assertIn("vram_reserve", {d.id for d in offered})++ def test_benchmark_only_dimension_is_never_exported(self):+ tuner = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 1.0})+ args = tuner._args_for({"prompt_cache_tail": True, "kv": "int8"})+ self.assertNotIn("--prompt-cache-tail", args,+ "a flag the production interface does not accept must not be exported")+ self.assertEqual(args["--kv"], "int8")++ def test_flag_inventory_returns_none_for_a_missing_engine(self):+ self.assertIsNone(tuning.engine_flag_inventory(Path("/nonexistent/strata")))++ def test_flag_inventory_reads_stderr_as_well_as_stdout(self):+ """The Strata engine writes its usage to stderr.++ A stdout-only read reports "no flags" for a working engine, and because every dimension is+ then excluded the sweep silently searches nothing — safe, but useless and very hard to+ notice. This test uses a stand-in that prints usage to stderr only.+ """+ fake = self.tmp / "fake-engine"+ fake.write_text("#!/bin/sh\necho 'usage:' >&2\necho ' --kv KV' >&2\necho ' --ple-io MODE' >&2\n")+ fake.chmod(0o755)+ flags = tuning.engine_flag_inventory(fake)+ self.assertIsNotNone(flags, "usage on stderr must still be read")+ self.assertIn("--kv", flags)+ self.assertIn("--ple-io", flags)++ def test_flag_inventory_reads_stdout_too(self):+ fake = self.tmp / "fake-engine-stdout"+ fake.write_text("#!/bin/sh\necho ' --vram-reserve-mib MIB'\n")+ fake.chmod(0o755)+ self.assertIn("--vram-reserve-mib", tuning.engine_flag_inventory(fake))++ def test_a_backend_with_dimensions_that_all_need_missing_flags_searches_nothing(self):+ """The safe outcome, asserted so it cannot silently become an unsafe one.++ Every dimension has *some* reason: either its flags are not this backend's concept, or the+ binary does not accept them. What must never happen is a dimension with no reason being+ dropped silently.+ """+ offered, excluded = tuning.validate_dimensions("metal", engine_flags=["--unrelated"])+ self.assertEqual(offered, [])+ self.assertEqual(len(excluded), len(tuning.DIMENSIONS))+ for e in excluded:+ self.assertTrue(e["reason"].strip(), f"{e['id']} was excluded with no reason given")+ # The dimensions that ARE Metal concepts are excluded specifically because the binary lacks+ # their flags, which is the check that matters.+ by_id = {e["id"]: e["reason"] for e in excluded}+ for dim_id in ("kv", "ple_io", "kv_grow", "spec_min_p"):+ self.assertIn("does not accept", by_id[dim_id])+++class TestBaselineAndSelection(TuningCase):+ def test_a_clear_winner_is_recommended(self):+ calls = {"n": 0}++ def measure(candidate):+ calls["n"] += 1+ # The baseline (no settings) is slow; any candidate is faster.+ return {"tokens_per_s": 50.0 if not candidate.settings else 80.0, "correct": True}++ plan = self.plan(max_trials=2, dimensions=("kv",))+ tuner, result = self.run_job(plan, measure)+ rep = result["report"]+ self.assertTrue(rep["recommendation_available"], rep)+ self.assertEqual(rep["baseline"]["median"], 50.0)+ self.assertEqual(rep["recommendation"]["median"], 80.0)++ def test_a_faster_candidate_inside_the_baseline_spread_is_not_recommended(self):+ """Promoting noise is the classic tuning failure, so the gate compares worst-against-worst."""+ state = {"phase": 0}++ def measure(candidate):+ if candidate.is_baseline:+ # A wide baseline spread: worst 40, best 90.+ state["phase"] += 1+ return {"tokens_per_s": [40.0, 90.0, 65.0][state["phase"] % 3]}+ # The candidate's median is higher but its worst run is below the baseline's worst.+ return {"tokens_per_s": [45.0, 60.0, 60.0][state["phase"] % 3]}++ plan = self.plan(max_trials=1, repeats=3, dimensions=("kv",))+ _, result = self.run_job(plan, measure)+ rep = result["report"]+ self.assertFalse(rep["recommendation_available"],+ "a candidate whose worst run is below the baseline's worst must not win")+ self.assertIn("spread", rep["reason"])++ def test_no_candidate_better_means_recommend_no_change(self):+ def measure(candidate):+ return {"tokens_per_s": 60.0 if not candidate.settings else 55.0}++ _, result = self.run_job(self.plan(max_trials=2, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertFalse(rep["recommendation_available"])+ self.assertIn("keeping the current configuration", rep["reason"])++ def test_drift_is_reported(self):+ """The baseline is re-measured last, so a drifting machine is visible instead of silent.++ The baseline is measured once as a warmup plus `repeats` times, and then again after the+ sweep. This case makes the measured value a function of *which* baseline measurement it is,+ rather than of the call count, so the expectation does not depend on how repeats are+ scheduled.+ """+ state = {"baseline_measurements": 0}++ def measure(candidate):+ if candidate.kind == "baseline":+ state["baseline_measurements"] += 1+ # The first measurement is the warmup; the three counted repeats are 50, and the+ # recheck afterwards is 40 (below), simulating a machine that got slower.+ return {"tokens_per_s": 50.0}+ if candidate.kind == "recheck":+ return {"tokens_per_s": 40.0}+ return {"tokens_per_s": 45.0}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertEqual(rep["baseline"]["median"], 50.0)+ self.assertIsNotNone(rep["recheck"], "the baseline must be re-measured after the sweep")+ self.assertEqual(rep["recheck"]["median"], 40.0)+ self.assertIsNotNone(rep["drift"], "the drift between the two baseline measurements is reported")+ self.assertLess(rep["drift"]["relative"], 0,+ "the report must show that the machine slowed, not hide it")++ def test_fewer_repeats_than_required_disqualifies_a_candidate(self):+ def measure(candidate):+ return {"tokens_per_s": 90.0 if candidate.settings else 50.0}++ plan = self.plan(max_trials=1, repeats=5, dimensions=("kv",))+ _, result = self.run_job(plan, measure)+ best = [c for c in result["report"]["candidates"] if c["kind"] == "trial"][0]+ self.assertGreaterEqual(len(best["metrics"]), 5)+++class TestFailuresAreRecorded(TuningCase):+ """A candidate that could not run is evidence about the configuration, never a slow winner."""++ def test_a_boot_failure_is_recorded_and_excluded(self):+ def measure(candidate):+ if candidate.settings:+ raise RuntimeError("the engine failed to boot with these flags")+ return {"tokens_per_s": 50.0}++ _, result = self.run_job(self.plan(max_trials=2, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertEqual(rep["recommendation_available"], False)+ self.assertTrue(rep["failures"])+ self.assertEqual(rep["failures"][0]["status"], "FAIL_BOOT")+ self.assertIn("failed to boot", rep["failures"][0]["reason"])++ def test_a_timeout_is_recorded_as_a_timeout(self):+ def measure(candidate):+ if candidate.settings:+ raise RuntimeError("the measurement timed out after 120s")+ return {"tokens_per_s": 50.0}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ self.assertEqual(result["report"]["failures"][0]["status"], "TIMEOUT")++ def test_no_tokens_is_not_a_slow_configuration(self):+ def measure(candidate):+ return {"tokens_per_s": 0.0}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertFalse(rep["recommendation_available"])+ statuses = [c["status"] for c in rep["candidates"]]+ self.assertIn("NO_TOKENS", statuses)++ def test_a_correctness_failure_disqualifies_a_fast_candidate(self):+ """tokens/s alone is not acceptance."""+ def measure(candidate):+ if candidate.settings:+ return {"tokens_per_s": 500.0, "correct": False}+ return {"tokens_per_s": 50.0, "correct": True}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertFalse(rep["recommendation_available"],+ "a fast but incorrect configuration must never be recommended")+ self.assertTrue(any(f["status"] == "INVALID" for f in rep["failures"]), rep["failures"])++ def test_a_baseline_that_cannot_be_measured_stops_the_sweep(self):+ def measure(candidate):+ raise RuntimeError("no engine here")++ _, result = self.run_job(self.plan(max_trials=5, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertFalse(rep["recommendation_available"])+ self.assertIsNone(rep["baseline"])+ self.assertIn("could not be measured", rep["reason"])+++class TestBounds(TuningCase):+ def test_the_trial_limit_is_respected(self):+ # Count *trials*, not measurement calls: each candidate is measured once as a warmup plus+ # `repeats` times, so counting calls would measure the wrong thing entirely.+ plan = self.plan(max_trials=3, dimensions=("ple_io", "kv"))+ _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})+ self.assertEqual(result["report"]["trials_run"], 3)+ self.assertEqual(len([c for c in result["report"]["candidates"]+ if c["kind"] == "trial"]), 3)+ self.assertLessEqual(result["report"]["baseline"] is not None, True)++ def test_the_time_bound_stops_new_trials(self):+ clock = {"t": 0.0}++ def measure(candidate):+ clock["t"] += 30.0+ return {"tokens_per_s": 60.0}++ plan = self.plan(max_trials=100, dimensions=("kv",))+ plan.total_time_s = 45.0+ tuner = tuning.Tuner(self.tmp / "runs", plan, measure, clock=lambda: clock["t"])+ result = tuner.run()+ self.assertTrue(any(e["state"] == "time_limit" for e in result["events"]),+ "the displayed time bound must actually stop the sweep")++ def test_cancellation_keeps_evidence_and_recommends_nothing(self):+ def measure(candidate):+ if candidate.settings:+ tuner.request_cancel()+ return {"tokens_per_s": 90.0 if candidate.settings else 50.0}++ plan = self.plan(max_trials=10, dimensions=("kv",))+ tuner = tuning.Tuner(self.tmp / "runs", plan, measure)+ result = tuner.run()+ self.assertEqual(result["state"], "cancelled")+ self.assertFalse(result["report"]["recommendation_available"],+ "a cancelled sweep must not produce a winner")+ self.assertTrue(result["report"]["candidates"], "evidence collected before the cancel is kept")+++class TestSearchSpaceIsDisclosed(TuningCase):+ """A bounded sweep must not look like a complete one.++ This is the honesty property that decides whether "no candidate beat the baseline" can be read+ as a conclusion. With four trials out of ninety-six combinations, it cannot — and the report has+ to say so, or a reader will take a partial search for a full one.+ """++ def test_a_bounded_sweep_reports_the_size_of_the_space_it_sampled(self):+ plan = self.plan(max_trials=2, dimensions=("kv",))+ _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})+ rep = result["report"]+ self.assertEqual(rep["trials_run"], 2)+ # `kv` has four values, so the space is four and two trials is a prefix of it.+ self.assertEqual(rep["combinations_total"], 4)+ self.assertTrue(rep["trials_are_a_prefix"])++ def test_a_complete_sweep_is_not_labelled_a_prefix(self):+ plan = self.plan(max_trials=10, dimensions=("kv",))+ _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})+ rep = result["report"]+ self.assertEqual(rep["combinations_total"], 4)+ self.assertEqual(rep["trials_run"], 4, "the whole four-value space is enumerated")+ self.assertFalse(rep["trials_are_a_prefix"])++ def test_the_space_size_accounts_for_every_offered_dimension(self):+ plan = self.plan(max_trials=1, dimensions=("kv", "kv_grow"))+ _, result = self.run_job(plan, lambda c: {"tokens_per_s": 60.0})+ # kv has 4 values, kv_grow has 2 -> 8 combinations.+ self.assertEqual(result["report"]["combinations_total"], 8)++ def test_a_plan_with_no_dimensions_reports_no_space(self):+ _, result = self.run_job(self.plan(max_trials=1), lambda c: {"tokens_per_s": 60.0})+ self.assertEqual(result["report"]["combinations_total"], 0)+++class TestDriftIsGraded(TuningCase):+ """A drift note is only warranted when the drift is material.++ Printing "the comparison is weaker than the repeat count suggests" at +0.0% trains the reader to+ ignore the warning, which is worse than not printing it.+ """++ def test_negligible_drift_is_not_flagged_as_material(self):+ def measure(candidate):+ return {"tokens_per_s": 50.0}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertIsNotNone(rep["drift"])+ self.assertAlmostEqual(rep["drift"]["relative"], 0.0)+ self.assertFalse(rep["drift_material"])++ def test_material_drift_is_flagged(self):+ def measure(candidate):+ return {"tokens_per_s": 40.0 if candidate.kind == "recheck" else 50.0}++ _, result = self.run_job(self.plan(max_trials=1, dimensions=("kv",)), measure)+ rep = result["report"]+ self.assertAlmostEqual(rep["drift"]["relative"], -0.2)+ self.assertTrue(rep["drift_material"])+++class TestExclusiveLease(TuningCase):+ """Tuning must own its devices: a second job, or a serving load, must not share them."""++ def test_a_second_job_is_refused_while_the_lease_is_held(self):+ first = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})+ first._acquire_lease()+ try:+ second = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})+ with self.assertRaises(RuntimeError) as ctx:+ second._acquire_lease()+ self.assertIn("exclusive device lease", str(ctx.exception))+ finally:+ first._release_lease()++ def test_the_lease_is_released_even_when_the_job_fails(self):+ plan = self.plan()+ tuner = tuning.Tuner(self.tmp / "runs", plan, lambda c: (_ for _ in ()).throw(RuntimeError("boom")))+ tuner.run()+ self.assertFalse((tuner.root / "tuning.lease").exists(),+ "a failed job must not leave the devices leased")++ def test_a_stale_lease_is_reported_rather_than_ignored(self):+ stale = self.tmp / "runs" / "job1"+ stale.mkdir(parents=True)+ (stale / "tuning.lease").write_text(json.dumps({"id": "dead", "pid": 1}))+ tuner = tuning.Tuner(self.tmp / "runs", self.plan(), lambda c: {"tokens_per_s": 50.0})+ with self.assertRaises(RuntimeError) as ctx:+ tuner._acquire_lease()+ self.assertIn("dead", str(ctx.exception))+++class TestExportedRetest(TuningCase):+ """A winner is not qualified until the *exported* configuration is measured again."""++ def test_a_configuration_that_loses_its_advantage_on_export_is_withdrawn(self):+ def measure(args):+ # The benchmark-only lever carried the gain; without it the engine is at the baseline.+ return {"tokens_per_s": 90.0 if "--prompt-cache-tail" in args else 50.0}++ outcome = tuning.verify_exported(Path("/engine"), {"--kv": "int8"}, measure)+ self.assertTrue(outcome["verified"])+ self.assertEqual(outcome["median"], 50.0)++ def test_an_exported_configuration_that_fails_to_boot_is_not_verified(self):+ def measure(args):+ raise RuntimeError("the engine failed to boot")++ outcome = tuning.verify_exported(Path("/engine"), {}, measure)+ self.assertFalse(outcome["verified"])+ self.assertIn("failed to run", outcome["reason"])++ def test_an_incorrect_exported_configuration_is_not_verified(self):+ outcome = tuning.verify_exported(Path("/engine"), {}, lambda a: {"tokens_per_s": 100.0,+ "correct": False})+ self.assertFalse(outcome["verified"])+ self.assertIn("correctness", outcome["reason"])+++class TestPersistenceAndReporting(TuningCase):+ def test_the_job_is_reloadable_with_its_report(self):+ def measure(candidate):+ return {"tokens_per_s": 70.0 if candidate.settings else 50.0}++ plan = self.plan(max_trials=1, dimensions=("kv",))+ _, result = self.run_job(plan, measure)+ saved = json.loads((self.tmp / "runs" / "job1" / "job.json").read_text())+ self.assertEqual(saved["state"], "completed")+ self.assertEqual(saved["id"], "job1")+ self.assertTrue(saved["report"]["candidates"])+ self.assertIn("excluded_dimensions", saved["report"])+ self.assertIn("machine", json.dumps(tuning.machine_identity()))++ def test_the_report_names_what_was_excluded_and_why(self):+ plan = tuning.plan_tuning(Path("/nonexistent/strata"), "metal", "m", "generation",+ {"prompt_tokens": 128})+ self.assertIn("vram_reserve", {e["id"] for e in plan.excluded})+ self.assertFalse(plan.engine_flags_known,+ "a plan must record that the engine could not be interrogated")++ def test_objective_selects_the_metric(self):+ self.assertEqual(self.plan(objective="generation").__class__.__name__, "TuningPlan")+ tuner = tuning.Tuner(self.tmp / "runs", self.plan(objective="prefill"),+ lambda c: {"tokens_per_s": 1.0})+ self.assertEqual(tuner._objective_metric(), "prefill_tokens_per_s")+ tuner2 = tuning.Tuner(self.tmp / "runs2", self.plan(objective="latency"),+ lambda c: {"tokens_per_s": 1.0})+ self.assertEqual(tuner2._objective_metric(), "ttft_ms")+++if __name__ == "__main__":+ unittest.main()