modelsaar 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. modelsaar/__init__.py +13 -0
  2. modelsaar/adapters/__init__.py +27 -0
  3. modelsaar/adapters/base.py +274 -0
  4. modelsaar/adapters/ollama.py +317 -0
  5. modelsaar/adapters/openai_compat.py +296 -0
  6. modelsaar/catalogue/__init__.py +72 -0
  7. modelsaar/catalogue/starter.yaml +435 -0
  8. modelsaar/cli.py +880 -0
  9. modelsaar/clientconfig/__init__.py +364 -0
  10. modelsaar/config.py +631 -0
  11. modelsaar/doctor.py +233 -0
  12. modelsaar/evaluation/__init__.py +1 -0
  13. modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
  14. modelsaar/evaluation/harness.py +768 -0
  15. modelsaar/evaluation/judge.py +173 -0
  16. modelsaar/evaluation/sandbox.py +341 -0
  17. modelsaar/evaluation/scoring.py +233 -0
  18. modelsaar/learning.py +227 -0
  19. modelsaar/lifecycle.py +208 -0
  20. modelsaar/pipelines.py +439 -0
  21. modelsaar/probes.py +526 -0
  22. modelsaar/protocol/__init__.py +1 -0
  23. modelsaar/protocol/anthropic.py +401 -0
  24. modelsaar/protocol/decisions.py +229 -0
  25. modelsaar/protocol/openai.py +322 -0
  26. modelsaar/protocol/responses.py +560 -0
  27. modelsaar/protocol/sse.py +181 -0
  28. modelsaar/registry.py +229 -0
  29. modelsaar/responses_store.py +117 -0
  30. modelsaar/routing/__init__.py +1 -0
  31. modelsaar/routing/admission.py +359 -0
  32. modelsaar/routing/affinity.py +131 -0
  33. modelsaar/routing/cascade.py +53 -0
  34. modelsaar/routing/classifier.py +298 -0
  35. modelsaar/routing/decision.py +85 -0
  36. modelsaar/routing/eligibility.py +158 -0
  37. modelsaar/routing/requirements.py +290 -0
  38. modelsaar/routing/router.py +1026 -0
  39. modelsaar/routing/scoring.py +179 -0
  40. modelsaar/routing/tokens.py +114 -0
  41. modelsaar/runtime.py +82 -0
  42. modelsaar/security.py +63 -0
  43. modelsaar/server.py +1546 -0
  44. modelsaar/static/status.html +95 -0
  45. modelsaar/store.py +208 -0
  46. modelsaar/testing/__init__.py +1 -0
  47. modelsaar/testing/fakebackend.py +661 -0
  48. modelsaar-0.2.0.dist-info/METADATA +285 -0
  49. modelsaar-0.2.0.dist-info/RECORD +54 -0
  50. modelsaar-0.2.0.dist-info/WHEEL +5 -0
  51. modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
  52. modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
  53. modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
  54. modelsaar-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,768 @@
1
+ """Executable evaluation harness.
2
+
3
+ Procedure (identical in simulated and live mode):
4
+
5
+ 1. Sweep the *calib* split over every eligible generative deployment -> per-deployment,
6
+ per-category quality and latency. These calibrate the fixed-strong / fixed-fast baselines
7
+ and (optionally) are stored as routing evidence.
8
+ 2. Sweep the *test* split over every deployment -> per-deployment results and the offline
9
+ per-task oracle (upper bound; NOT available at runtime).
10
+ 3. Run ``auto`` live through the gateway on the test split (real routing, overhead measured).
11
+ 4. Derive fixed-strong, fixed-fast, deterministic specialist rules and seeded random from the
12
+ test sweep (same requests, same eligibility checks, temperature 0).
13
+
14
+ Every request goes through the real HTTP gateway so hard constraints apply equally to all policies.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import random
22
+ import statistics
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ from collections import defaultdict
27
+ from collections.abc import Callable
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ import httpx
32
+
33
+ from . import sandbox
34
+ from .scoring import SCORER_VERSION, score
35
+
36
+ FIXTURES = Path(__file__).parent / "fixtures" / "tasks.jsonl"
37
+ MAX_TOKENS = 400
38
+ TEMPERATURE = 0
39
+
40
+
41
+ def load_tasks(path: Path | None = None, limit: int = 0) -> list[dict[str, Any]]:
42
+ p = path or FIXTURES
43
+ tasks = [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]
44
+ return tasks[:limit] if limit else tasks
45
+
46
+
47
+ def dataset_revision(tasks: list[dict[str, Any]], path: Path | None = None) -> dict[str, str | None]:
48
+ """sha256 of the task file (when known) and of the canonical JSON of the tasks actually run."""
49
+ p = path or FIXTURES
50
+ file_sha = hashlib.sha256(p.read_bytes()).hexdigest() if p.exists() else None
51
+ canon = "\n".join(json.dumps(t, sort_keys=True, ensure_ascii=False) for t in tasks)
52
+ return {"tasks_file": str(p), "tasks_file_sha256": file_sha, "tasks_run_sha256": hashlib.sha256(canon.encode("utf-8")).hexdigest()}
53
+
54
+
55
+ def _git_commit() -> str | None:
56
+ try:
57
+ p = subprocess.run(["git", "rev-parse", "HEAD"], cwd=Path(__file__).parent, capture_output=True, text=True, timeout=5)
58
+ except (OSError, subprocess.TimeoutExpired):
59
+ return None
60
+ if p.returncode != 0:
61
+ return None
62
+ return p.stdout.strip() or None
63
+
64
+
65
+ def resolve_selectors(deployments: list[dict[str, Any]], selectors: list[str] | None) -> list[str]:
66
+ """Map user-supplied deployment selectors to canonical deployment ids, once.
67
+
68
+ A selector may be a full id (``ollama/qwen3.6:latest``) or a bare model name
69
+ (``qwen3.6:latest``). Unknown or ambiguous selectors raise ``ValueError`` so a typo cannot
70
+ silently shrink the sweep or leave the ``auto`` alias unrestricted.
71
+ """
72
+ out: list[str] = []
73
+ ids = [d["id"] for d in deployments]
74
+ for sel in selectors or []:
75
+ if sel in ids:
76
+ hits = [sel]
77
+ else:
78
+ hits = [d["id"] for d in deployments if d["id"].split("/", 1)[-1] == sel or d.get("model") == sel]
79
+ if not hits:
80
+ raise ValueError(f"unknown deployment selector {sel!r}; discovered deployments: {ids}")
81
+ if len(hits) > 1:
82
+ raise ValueError(f"ambiguous deployment selector {sel!r} matches {hits}; use the full id")
83
+ if hits[0] not in out:
84
+ out.append(hits[0])
85
+ return out
86
+
87
+
88
+ def _request_body(task: dict[str, Any], model: str, simulated: bool) -> dict[str, Any]:
89
+ body: dict[str, Any] = {"model": model, "messages": json.loads(json.dumps(task["messages"])), "temperature": TEMPERATURE, "max_tokens": MAX_TOKENS}
90
+ if task.get("tools"):
91
+ body["tools"] = task["tools"]
92
+ if task.get("response_format"):
93
+ body["response_format"] = task["response_format"]
94
+ if simulated:
95
+ # The fake backend decides correctness from this marker (simulation artefact only).
96
+ marker = f" <!-- eval:{task['category']} -->"
97
+ for m in reversed(body["messages"]):
98
+ if m["role"] == "user":
99
+ if isinstance(m["content"], str):
100
+ m["content"] += marker
101
+ elif isinstance(m["content"], list):
102
+ for p in m["content"]:
103
+ if p.get("type") == "text":
104
+ p["text"] += marker
105
+ break
106
+ break
107
+ return body
108
+
109
+
110
+ def _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
111
+ if n == 0:
112
+ return (0.0, 0.0)
113
+ p = k / n
114
+ denom = 1 + z * z / n
115
+ centre = (p + z * z / (2 * n)) / denom
116
+ half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / denom
117
+ return (max(0.0, centre - half), min(1.0, centre + half))
118
+
119
+
120
+ CHECKPOINT_FORMAT = 2 # records carry task_sha256 + conditions_key; format-1 records are never resumed
121
+
122
+
123
+ def task_identity(task: dict[str, Any]) -> str:
124
+ """sha256 of the task content that determines a result: messages, expected (type, values,
125
+ harness, schema), tools, category/split. Ephemeral fields are not part of a task."""
126
+ return hashlib.sha256(json.dumps(task, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
127
+
128
+
129
+ def eligible_set_key(fingerprints: dict[str, str], simulated: bool = False) -> str:
130
+ """Canonical identity of the eligible deployment set a routed decision chose from: sorted
131
+ deployment ids with their fingerprints (ids only in simulated mode, whose fingerprints embed a
132
+ per-run loopback port). Adding, removing or re-identifying any alternative changes it."""
133
+ items = sorted((k, "" if simulated else v) for k, v in fingerprints.items())
134
+ return hashlib.sha256(json.dumps(items).encode("utf-8")).hexdigest()[:16]
135
+
136
+
137
+ def conditions_key(policy: str, *, scorer_version: str = SCORER_VERSION, max_tokens: int = MAX_TOKENS, temperature: float = TEMPERATURE,
138
+ seed: int | None = None, routing_config_hash: str | None = None, eligible_key: str | None = None) -> str:
139
+ """Stable identity of the experiment conditions a record depends on: scorer version, request
140
+ budgets and, for routed policies (``auto`` and other aliases), the gateway's routing configuration
141
+ hash **and the eligible deployment set** (``eligible_set_key``): a routed result depends on the
142
+ alternatives it could have chosen, so a new or re-identified candidate re-runs the task.
143
+ Fixed-deployment sweeps (``sweep:``/``calib:``/``test:``) depend only on their own deployment.
144
+ The seed matters only for the random baseline. Ports, timestamps and paths are deliberately
145
+ excluded so an unchanged run stays resumable."""
146
+ parts: dict[str, Any] = {"format": CHECKPOINT_FORMAT, "scorer": scorer_version, "max_tokens": max_tokens, "temperature": temperature}
147
+ if policy.startswith("random"):
148
+ parts["seed"] = seed
149
+ if not policy.startswith(("sweep:", "calib:", "test:")):
150
+ parts["routing_config_hash"] = routing_config_hash
151
+ parts["eligible_set"] = eligible_key
152
+ return hashlib.sha256(json.dumps(parts, sort_keys=True).encode("utf-8")).hexdigest()[:24]
153
+
154
+
155
+ class EvalRun:
156
+ """Issues requests, scores them and keeps per-request records.
157
+
158
+ Records are sanitized (ids, status, latency, scorer detail; never prompt text). With a
159
+ ``checkpoint`` path every record is appended as one JSON line immediately; with
160
+ ``resume=True`` a record already in that file is reused only when it is bound to the same
161
+ experiment: same ``(policy, task)`` key, same task content (``task_sha256``), same conditions
162
+ (``conditions_key``: scorer version, budgets, routing configuration for routed policies) and,
163
+ for records that name a deployment, that deployment is still eligible in this run with the
164
+ same fingerprint. Anything else — a changed task or scorer, a removed or changed deployment,
165
+ a format-1 (legacy) record — is re-run and counted in ``resume_rejected``.
166
+ """
167
+
168
+ def __init__(self, gateway_url: str, api_key: str, admin_key: str, simulated: bool, seed: int = 7, checkpoint: Path | None = None, resume: bool = False) -> None:
169
+ self.c = httpx.Client(base_url=gateway_url, headers={"Authorization": f"Bearer {api_key}"}, timeout=300)
170
+ self.admin = httpx.Client(base_url=gateway_url, headers={"Authorization": f"Bearer {admin_key}"}, timeout=60)
171
+ self.simulated = simulated
172
+ self.seed = seed
173
+ self.rng = random.Random(seed)
174
+ self.records: list[dict[str, Any]] = []
175
+ self.fingerprints: dict[str, str] = {}
176
+ self.routing_config_hash: str | None = None # set from /admin/status by run_live/run_simulated
177
+ self.checkpoint = Path(checkpoint) if checkpoint else None
178
+ self.resumed = 0
179
+ self.resume_rejected: dict[str, int] = {}
180
+ self._done: dict[tuple[str, str], dict[str, Any]] = {}
181
+ if resume:
182
+ if not self.checkpoint:
183
+ raise ValueError("--resume needs a checkpoint path (--checkpoint PATH or --out)")
184
+ if self.checkpoint.exists():
185
+ for ln in self.checkpoint.read_text(encoding="utf-8").splitlines():
186
+ if ln.strip():
187
+ rec = json.loads(ln)
188
+ self._done[(rec["policy"], rec["task"])] = rec
189
+ if self.checkpoint:
190
+ self.checkpoint.parent.mkdir(parents=True, exist_ok=True)
191
+
192
+ def deployments(self) -> list[dict[str, Any]]:
193
+ s = self.admin.get("/admin/status").json()
194
+ return [d for d in s["deployments"] if d["role"] == "generative" and d["state"]["healthy"] and d["enabled"] and d["locality"] == "local"]
195
+
196
+ def all_deployments(self) -> list[dict[str, Any]]:
197
+ return list(self.admin.get("/admin/status").json()["deployments"])
198
+
199
+ def _finish(self, rec: dict[str, Any]) -> dict[str, Any]:
200
+ self.records.append(rec)
201
+ if self.checkpoint:
202
+ with open(self.checkpoint, "a", encoding="utf-8") as f:
203
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
204
+ f.flush()
205
+ return rec
206
+
207
+ def _conditions_key(self, policy: str) -> str:
208
+ return conditions_key(policy, seed=self.seed, routing_config_hash=self.routing_config_hash,
209
+ eligible_key=eligible_set_key(self.fingerprints, self.simulated))
210
+
211
+ def _reject(self, reason: str) -> None:
212
+ self.resume_rejected[reason] = self.resume_rejected.get(reason, 0) + 1
213
+
214
+ def _resumable(self, task: dict[str, Any] | str, policy: str) -> dict[str, Any] | None:
215
+ """Return the checkpoint record to reuse for ``(policy, task)`` or None (re-run). ``task`` is
216
+ the task dict; a bare task id (legacy callers/tests) can only match on the id and the
217
+ deployment conditions, and a format-2 record then still requires the task hash."""
218
+ task_id = task if isinstance(task, str) else task["id"]
219
+ prev = self._done.get((policy, task_id))
220
+ if not prev:
221
+ return None
222
+ if prev.get("checkpoint_format") != CHECKPOINT_FORMAT or not prev.get("task_sha256"):
223
+ self._reject("legacy_record_format")
224
+ return None
225
+ if not isinstance(task, str) and prev.get("task_sha256") != task_identity(task):
226
+ self._reject("task_changed")
227
+ return None
228
+ if prev.get("conditions_key") != self._conditions_key(policy):
229
+ self._reject("conditions_changed")
230
+ return None
231
+ dep, fp = prev.get("deployment"), prev.get("fingerprint")
232
+ if dep:
233
+ if self.simulated:
234
+ # The simulated backend is deterministic by construction and is started on a fresh
235
+ # loopback port per run, so its endpoint (part of the fingerprint) differs every time;
236
+ # the deployment must still exist in this run.
237
+ if dep not in self.fingerprints:
238
+ self._reject("deployment_not_eligible")
239
+ return None
240
+ return prev
241
+ if dep not in self.fingerprints:
242
+ self._reject("deployment_not_eligible")
243
+ return None
244
+ if fp and self.fingerprints[dep] != fp:
245
+ self._reject("deployment_changed")
246
+ return None
247
+ if not fp:
248
+ self._reject("record_without_fingerprint")
249
+ return None
250
+ return prev
251
+
252
+ def run_one(self, task: dict[str, Any], model: str, policy: str, enrich: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]:
253
+ prev = self._resumable(task, policy)
254
+ if prev is not None:
255
+ self.resumed += 1
256
+ rec = dict(prev)
257
+ rec["resumed"] = True
258
+ self.records.append(rec) # already in the checkpoint file
259
+ return rec
260
+ body = _request_body(task, model, self.simulated)
261
+ t0 = time.monotonic()
262
+ try:
263
+ r = self.c.post("/v1/chat/completions", json=body)
264
+ except httpx.HTTPError as e:
265
+ rec = {"task": task["id"], "category": task["category"], "split": task["split"], "policy": policy, "model": model, "status": 0, "ok": False, "detail": f"transport: {e}", "latency_ms": (time.monotonic() - t0) * 1000}
266
+ return self._finish(self._bind(rec, task, policy))
267
+ ms = (time.monotonic() - t0) * 1000
268
+ print(f"[eval] {policy:40s} {task['id']:12s} HTTP {r.status_code} {ms/1000:6.1f}s", file=sys.stderr, flush=True)
269
+ rec: dict[str, Any] = {
270
+ "task": task["id"],
271
+ "category": task["category"],
272
+ "split": task["split"],
273
+ "policy": policy,
274
+ "model": model,
275
+ "status": r.status_code,
276
+ "deployment": r.headers.get("x-modelsaar-deployment"),
277
+ "request_id": r.headers.get("x-modelsaar-request-id"),
278
+ "latency_ms": round(ms, 1),
279
+ }
280
+ if rec["deployment"] and rec["deployment"] in self.fingerprints:
281
+ rec["fingerprint"] = self.fingerprints[rec["deployment"]]
282
+ if r.status_code == 200:
283
+ ok, detail = score(task, r.json())
284
+ rec["ok"], rec["detail"] = ok, detail
285
+ if ok is None:
286
+ rec["skipped"] = True
287
+ else:
288
+ rec["ok"] = False
289
+ try:
290
+ err = r.json().get("error", {})
291
+ rec["detail"] = f"HTTP {r.status_code}: {err.get('code')}: {str(err.get('message'))[:160]}"
292
+ rec["violation"] = r.status_code == 422
293
+ except Exception:
294
+ rec["detail"] = f"HTTP {r.status_code}"
295
+ if enrich is not None:
296
+ enrich(rec)
297
+ return self._finish(self._bind(rec, task, policy))
298
+
299
+ def _bind(self, rec: dict[str, Any], task: dict[str, Any], policy: str) -> dict[str, Any]:
300
+ """Attach the experiment identity a later --resume must match."""
301
+ rec["checkpoint_format"] = CHECKPOINT_FORMAT
302
+ rec["task_sha256"] = task_identity(task)
303
+ rec["conditions_key"] = self._conditions_key(policy)
304
+ rec["scorer_version"] = SCORER_VERSION
305
+ return rec
306
+
307
+ def sweep(self, tasks: list[dict[str, Any]], dep_ids: list[str], policy_prefix: str = "sweep") -> dict[str, dict[str, dict[str, Any]]]:
308
+ """Return results[dep_id][task_id] = record."""
309
+ out: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
310
+ for d in dep_ids:
311
+ for t in tasks:
312
+ out[d][t["id"]] = self.run_one(t, d, f"{policy_prefix}:{d}")
313
+ return out
314
+
315
+ def run_auto(self, tasks: list[dict[str, Any]], alias: str = "auto") -> dict[str, dict[str, Any]]:
316
+ def enrich(rec: dict[str, Any]) -> None:
317
+ if rec.get("request_id"):
318
+ try:
319
+ dec = self.admin.get(f"/admin/decisions/{rec['request_id']}").json()
320
+ rec["overhead_ms"] = dec.get("overhead_ms")
321
+ rec["evidence"] = dec.get("evidence")
322
+ rec["inferred_task"] = (dec.get("requirements") or {}).get("primary_task")
323
+ rec["classifier"] = dec.get("classifier")
324
+ except Exception:
325
+ pass
326
+
327
+ return {t["id"]: self.run_one(t, alias, "auto", enrich=enrich) for t in tasks}
328
+
329
+
330
+ def _is_skipped(r: dict[str, Any]) -> bool:
331
+ return bool(r.get("skipped")) or r.get("ok") is None
332
+
333
+
334
+ def summarize(records_by_task: dict[str, dict[str, Any]], tasks: list[dict[str, Any]]) -> dict[str, Any]:
335
+ """Aggregate one policy. ``success`` and its CI are computed over *scored* tasks only
336
+ (``n_scored``); tasks the scorer could not judge are counted in ``skipped`` with the reason,
337
+ so the denominator is always visible."""
338
+ cats: dict[str, list[bool]] = defaultdict(list)
339
+ cat_skipped: dict[str, int] = defaultdict(int)
340
+ lat: list[float] = []
341
+ n_ok = n = n_scored = n_complete = n_viol = n_skipped = 0
342
+ skip_reasons: dict[str, int] = defaultdict(int)
343
+ for t in tasks:
344
+ r = records_by_task.get(t["id"])
345
+ if not r:
346
+ continue
347
+ n += 1
348
+ n_complete += r.get("status") == 200
349
+ n_viol += bool(r.get("violation"))
350
+ if r.get("status") == 200:
351
+ lat.append(r["latency_ms"])
352
+ if _is_skipped(r):
353
+ n_skipped += 1
354
+ cat_skipped[t["category"]] += 1
355
+ skip_reasons[str(r.get("detail") or "skipped")] += 1
356
+ continue
357
+ n_scored += 1
358
+ ok = bool(r.get("ok"))
359
+ n_ok += ok
360
+ cats[t["category"]].append(ok)
361
+ lo, hi = _wilson(n_ok, n_scored)
362
+ per_cat = {}
363
+ for c in sorted(set(cats) | set(cat_skipped)):
364
+ v = cats.get(c, [])
365
+ k = sum(v)
366
+ clo, chi = _wilson(k, len(v))
367
+ per_cat[c] = {"success": round(k / len(v), 3) if v else None, "n": len(v), "skipped": cat_skipped.get(c, 0), "ci95": [round(clo, 3), round(chi, 3)]}
368
+ return {
369
+ "n": n,
370
+ "n_scored": n_scored,
371
+ "skipped": n_skipped,
372
+ "skip_reasons": dict(skip_reasons),
373
+ "success": round(n_ok / n_scored, 3) if n_scored else None,
374
+ "ci95": [round(lo, 3), round(hi, 3)],
375
+ "completion_rate": round(n_complete / n, 3) if n else None,
376
+ "capability_violations": n_viol,
377
+ "p50_ms": round(statistics.median(lat), 1) if lat else None,
378
+ "p95_ms": round(sorted(lat)[max(0, int(len(lat) * 0.95) - 1)], 1) if lat else None,
379
+ "per_category": per_cat,
380
+ }
381
+
382
+
383
+ def rules_policy(task: dict[str, Any], deps: list[dict[str, Any]], strong: str, fast: str) -> str:
384
+ """Deterministic specialist rules. NOTE: receives the gold category label (an advantage auto lacks)."""
385
+ cat = task["category"]
386
+ by_id = {d["id"]: d for d in deps}
387
+ if cat in ("coding", "agent"):
388
+ tagged = [d["id"] for d in deps if "code" in (d.get("tags") or [])]
389
+ return tagged[0] if tagged else strong
390
+ if cat == "document_vision":
391
+ vis = [d["id"] for d in deps if d["capabilities"]["vision"]["value"] == "supported"]
392
+ return vis[0] if vis else strong
393
+ if cat in ("math", "extraction", "rag"):
394
+ return strong
395
+ return fast if fast in by_id else strong
396
+
397
+
398
+ def probe_all(gw) -> list[dict[str, Any]]: # type: ignore[no-untyped-def]
399
+ """Verify capabilities of every local generative deployment before evaluating, through the
400
+ gateway's own admission (the same path as ``POST /admin/probe``): one reservation per deployment,
401
+ so probes never exceed the pool/backend limits. After an *uncertain* timeout the reservation is
402
+ held (the backend may still be computing) and the remaining deployments are NOT probed in this
403
+ run; they are reported with ``deferred: true`` so the caller can re-run `modelsaar probe` later.
404
+ The held reservation carries into the evaluation phase: the evaluator's requests go through the
405
+ gateway and wait for or are refused by the same admission."""
406
+
407
+ from ..probes import run_probes
408
+ from ..routing.admission import AdmissionRejected
409
+
410
+ async def _run() -> list[dict[str, Any]]:
411
+ out = []
412
+ deferred_after: str | None = None
413
+ for d in gw.router.registry.all():
414
+ if not (d.role == "generative" and d.healthy and d.locality == "local"):
415
+ continue
416
+ if deferred_after is not None:
417
+ out.append({"deployment_id": d.id, "fingerprint": d.fingerprint, "results": [], "measurements": [], "errors": [
418
+ f"not probed: a probe of {deferred_after} timed out and its backend may still be computing; the shared "
419
+ "reservation is held as uncertain (re-run `modelsaar probe` later)"], "uncertain": False, "skipped": [], "deferred": True})
420
+ continue
421
+ try:
422
+ reservation = await gw.router.admission.acquire(d, timeout=None)
423
+ except AdmissionRejected as e:
424
+ out.append({"deployment_id": d.id, "fingerprint": d.fingerprint, "results": [], "measurements": [], "errors": [f"not probed: admission refused ({e.message})"], "uncertain": False, "skipped": [], "deferred": True})
425
+ continue
426
+ try:
427
+ rep = await run_probes(gw.router.adapters[d.backend_id], d, gw.store, ["streaming", "tools", "json_object", "json_schema", "vision"], timeout=120)
428
+ except BaseException:
429
+ await reservation.release()
430
+ raise
431
+ if rep.uncertain:
432
+ await reservation.mark_uncertain()
433
+ deferred_after = d.id
434
+ else:
435
+ await reservation.release()
436
+ rec = rep.as_dict()
437
+ rec["deferred"] = False
438
+ out.append(rec)
439
+ return out
440
+
441
+ return gw.run(_run())
442
+
443
+
444
+ def evaluate(
445
+ run: EvalRun,
446
+ tasks: list[dict[str, Any]],
447
+ save_measurements_store=None, # type: ignore[no-untyped-def]
448
+ only: list[str] | None = None,
449
+ conditions: dict[str, Any] | None = None,
450
+ ) -> dict[str, Any]:
451
+ """``only`` must already hold canonical deployment ids (see :func:`resolve_selectors`)."""
452
+ deps = run.deployments()
453
+ if only:
454
+ eligible = {d["id"] for d in deps}
455
+ missing = [i for i in only if i not in eligible]
456
+ if missing:
457
+ raise ValueError(f"selected deployments are not eligible (must be local, healthy, enabled, generative): {missing}")
458
+ deps = [d for d in deps if d["id"] in only]
459
+ dep_ids = [d["id"] for d in deps]
460
+ run.fingerprints = {d["id"]: d["fingerprint"] for d in deps}
461
+ try:
462
+ run.routing_config_hash = run.admin.get("/admin/status").json().get("config_hash")
463
+ except Exception: # pragma: no cover - status is required anyway above
464
+ run.routing_config_hash = None
465
+ calib = [t for t in tasks if t["split"] == "calib"]
466
+ test = [t for t in tasks if t["split"] == "test"]
467
+ backend, backend_reason = sandbox.available()
468
+ report: dict[str, Any] = {
469
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
470
+ "mode": "simulated" if run.simulated else "live",
471
+ "deployments": [
472
+ {
473
+ "id": d["id"],
474
+ "family": d["family"],
475
+ "parameter_size": d["parameter_size"],
476
+ "quantization": d["quantization"],
477
+ "runtime": d["backend_type"],
478
+ "runtime_version": d.get("runtime_version"),
479
+ "context_length": d["context_length"],
480
+ "fingerprint": d["fingerprint"],
481
+ "identity": d.get("identity"),
482
+ "endpoint": d.get("endpoint"),
483
+ "tags": d.get("tags"),
484
+ "memory_gb_estimate": d.get("memory_gb_estimate"),
485
+ }
486
+ for d in deps
487
+ ],
488
+ "n_calib": len(calib),
489
+ "n_test": len(test),
490
+ "sandbox": {"backend": backend, "reason": backend_reason, "code_exec_tasks": sum(1 for t in tasks if t["expected"]["type"] == "code_exec")},
491
+ "conditions": {
492
+ "max_tokens": MAX_TOKENS,
493
+ "temperature": TEMPERATURE,
494
+ "seed": run.seed,
495
+ "scorer_version": SCORER_VERSION,
496
+ "checkpoint_format": CHECKPOINT_FORMAT,
497
+ "routing_config_hash": run.routing_config_hash,
498
+ "git_commit": _git_commit(),
499
+ "sandbox_backend": backend,
500
+ "deployment_fingerprints": dict(run.fingerprints),
501
+ **(conditions or {}),
502
+ },
503
+ "checkpoint": str(run.checkpoint) if run.checkpoint else None,
504
+ }
505
+ if not dep_ids:
506
+ report["error"] = "no eligible local generative deployments"
507
+ return report
508
+ # 1. calibration sweep
509
+ cal = run.sweep(calib, dep_ids, "calib")
510
+ cal_summary = {d: summarize(cal[d], calib) for d in dep_ids}
511
+ strong = max(dep_ids, key=lambda d: (cal_summary[d]["success"] or 0.0, -(cal_summary[d]["p50_ms"] or 1e9)))
512
+ fast = min(dep_ids, key=lambda d: (cal_summary[d]["p50_ms"] or 1e9))
513
+ report["calibration"] = {"per_deployment": cal_summary, "fixed_strong": strong, "fixed_fast": fast}
514
+ # optional: persist measured evidence for routing (per category + latency)
515
+ if save_measurements_store is not None:
516
+ by_fp = {d["id"]: d["fingerprint"] for d in deps}
517
+ by_id = {d["id"]: d for d in deps}
518
+ for d in dep_ids:
519
+ cond = {
520
+ k: v for k, v in report["conditions"].items() if k != "deployment_fingerprints"
521
+ } | {
522
+ "split": "calib",
523
+ "effective_context": by_id[d].get("context_length"),
524
+ "runtime": f"{by_id[d].get('runtime', '')} {by_id[d].get('runtime_version', '')}".strip(),
525
+ "endpoint": by_id[d].get("endpoint"),
526
+ }
527
+ for cat, v in cal_summary[d]["per_category"].items():
528
+ if v["success"] is None:
529
+ continue # nothing scored in this category (e.g. code_exec skipped): no evidence
530
+ save_measurements_store.save_measurement(
531
+ d,
532
+ by_fp[d],
533
+ {"task": cat, "quality": v["success"], "samples": v["n"], "p50_ms": cal_summary[d]["p50_ms"], "p95_ms": cal_summary[d]["p95_ms"], "source": "eval", "conditions": cond},
534
+ )
535
+ try:
536
+ run.admin.post("/admin/refresh")
537
+ except Exception:
538
+ pass
539
+ # 2. test sweep (oracle + per-deployment)
540
+ sw = run.sweep(test, dep_ids, "test")
541
+ oracle: dict[str, dict[str, Any]] = {}
542
+ for t in test:
543
+ recs = [sw[d][t["id"]] for d in dep_ids]
544
+ if all(_is_skipped(r) for r in recs):
545
+ oracle[t["id"]] = {"ok": None, "skipped": True, "detail": recs[0].get("detail"), "status": 200, "latency_ms": min(r["latency_ms"] for r in recs)}
546
+ else:
547
+ oracle[t["id"]] = {"ok": any(r["ok"] for r in recs if not _is_skipped(r)), "status": 200, "latency_ms": min(r["latency_ms"] for r in recs)}
548
+ # 3. auto live
549
+ auto = run.run_auto(test, "auto")
550
+ # 4. derived policies
551
+ fixed_strong = {t["id"]: sw[strong][t["id"]] for t in test}
552
+ fixed_fast = {t["id"]: sw[fast][t["id"]] for t in test}
553
+ rules = {t["id"]: sw[rules_policy(t, deps, strong, fast)][t["id"]] for t in test}
554
+ rnd = {t["id"]: sw[run.rng.choice(dep_ids)][t["id"]] for t in test}
555
+ policies = {
556
+ "auto (live routing)": auto,
557
+ "fixed-strong (calibrated)": fixed_strong,
558
+ "fixed-fast (calibrated)": fixed_fast,
559
+ "rules (gold label, specialist tags)": rules,
560
+ "random (diagnostic)": rnd,
561
+ "oracle (offline upper bound, not available at runtime)": oracle,
562
+ }
563
+ report["results"] = {name: summarize(recs, test) for name, recs in policies.items()}
564
+ report["per_deployment_test"] = {d: summarize(sw[d], test) for d in dep_ids}
565
+ overheads = [r["overhead_ms"] for r in auto.values() if r.get("overhead_ms") is not None]
566
+ report["routing"] = {
567
+ "overhead_ms_mean": round(statistics.mean(overheads), 2) if overheads else None,
568
+ "overhead_ms_p95": round(sorted(overheads)[max(0, int(len(overheads) * 0.95) - 1)], 2) if overheads else None,
569
+ "choices": {t["id"]: auto[t["id"]].get("deployment") for t in test},
570
+ "evidence_levels": dict(sorted(defaultdict(int, {e: sum(1 for r in auto.values() if r.get("evidence") == e) for e in {r.get("evidence") for r in auto.values()}}).items(), key=lambda kv: str(kv[0]))),
571
+ "task_label_accuracy": round(sum(1 for t in test if auto[t["id"]].get("inferred_task") == t["category"]) / len(test), 3) if test else None,
572
+ "routing_mistakes": [t["id"] for t in test if auto[t["id"]]["ok"] is False and oracle[t["id"]]["ok"] is True],
573
+ "classifier": {"used": sum(1 for r in auto.values() if (r.get("classifier") or {}).get("used")), "timeouts": sum(1 for r in auto.values() if (r.get("classifier") or {}).get("status") == "timeout")},
574
+ }
575
+ report["resumed_records"] = run.resumed
576
+ report["resume_rejected"] = dict(run.resume_rejected)
577
+ report["records"] = run.records
578
+ return report
579
+
580
+
581
+ def _fmt(v: Any, width: int, prec: int, na: str = "n/a") -> str:
582
+ """Right-aligned fixed-point number, or ``na`` when there is nothing to show (e.g. all skipped)."""
583
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
584
+ return f"{v:>{width}.{prec}f}"
585
+ return f"{na:>{width}s}"
586
+
587
+
588
+ def render_report(rep: dict[str, Any]) -> str:
589
+ lines = [f"ModelSaar evaluation ({rep['mode']}) - {rep['generated_at']}", ""]
590
+ if rep.get("error"):
591
+ return "\n".join(lines + [f"ERROR: {rep['error']}"])
592
+ lines.append("deployments: " + ", ".join(f"{d['id']} [{d['parameter_size']} {d['quantization']} ctx={d['context_length']}]" for d in rep["deployments"]))
593
+ lines.append(f"calibration: fixed-strong={rep['calibration']['fixed_strong']} fixed-fast={rep['calibration']['fixed_fast']} (n_calib={rep['n_calib']}, n_test={rep['n_test']})")
594
+ sb = rep.get("sandbox") or {}
595
+ if sb.get("backend"):
596
+ lines.append(f"sandbox: {sb['backend']} ({sb.get('reason')}); code_exec tasks executed in isolation")
597
+ else:
598
+ lines.append(f"sandbox: NONE - {sb.get('code_exec_tasks', 0)} code_exec task(s) SKIPPED and excluded from every denominator: {sb.get('reason')}")
599
+ cond = rep.get("conditions") or {}
600
+ lines.append(
601
+ f"conditions: max_tokens={cond.get('max_tokens')} temperature={cond.get('temperature')} seed={cond.get('seed')} "
602
+ f"scorer={cond.get('scorer_version')} tasks_sha256={str(cond.get('tasks_file_sha256') or cond.get('tasks_run_sha256') or '')[:12]} git={str(cond.get('git_commit') or 'unknown')[:12]}"
603
+ )
604
+ if rep.get("checkpoint"):
605
+ rej = rep.get("resume_rejected") or {}
606
+ lines.append(f"checkpoint: {rep['checkpoint']} (resumed {rep.get('resumed_records', 0)} record(s)"
607
+ + (f"; re-run instead of resumed: {', '.join(f'{k}={v}' for k, v in sorted(rej.items()))}" if rej else "") + ")")
608
+ lines.append("")
609
+ lines.append(f"{'policy':55s} {'success':>9s} {'95% CI':>15s} {'scored':>7s} {'skip':>5s} {'complete':>9s} {'viol':>5s} {'p50 ms':>8s} {'p95 ms':>8s}")
610
+ for name, s in rep["results"].items():
611
+ lines.append(
612
+ f"{name:55s} {_fmt(s['success'], 9, 3)} {s['ci95']!s:>15s} {s['n_scored']:>7d} {s['skipped']:>5d} "
613
+ f"{_fmt(s['completion_rate'], 9, 3)} {s['capability_violations']:>5d} {s['p50_ms']!s:>8s} {s['p95_ms']!s:>8s}"
614
+ )
615
+ lines.append("")
616
+ cats = sorted({c for s in rep["results"].values() for c in s["per_category"]})
617
+ lines.append(f"{'per category (success over scored; -- = all skipped)':55s} " + " ".join(f"{c[:10]:>10s}" for c in cats))
618
+ for name, s in rep["results"].items():
619
+ lines.append(f"{name:55s} " + " ".join(_fmt((s["per_category"].get(c) or {}).get("success"), 10, 2, na="--") for c in cats))
620
+ skipped_any = {reason for s in rep["results"].values() for reason in s.get("skip_reasons", {})}
621
+ if skipped_any:
622
+ lines.append("")
623
+ lines.append("skipped (not counted as success or failure): " + "; ".join(sorted(skipped_any)))
624
+ r = rep["routing"]
625
+ lines.append("")
626
+ lines.append(f"routing overhead: mean {r['overhead_ms_mean']} ms, p95 {r['overhead_ms_p95']} ms; task-label accuracy {r['task_label_accuracy']}; evidence levels {r['evidence_levels']}")
627
+ lines.append(f"routing mistakes (auto failed, oracle succeeded): {r['routing_mistakes']}")
628
+ lines.append(f"classifier: {r['classifier']}")
629
+ return "\n".join(lines)
630
+
631
+
632
+ # --------------------------------------------------------------------------- #
633
+ def _checkpoint_path(args) -> Path | None: # type: ignore[no-untyped-def]
634
+ explicit = getattr(args, "checkpoint", None)
635
+ if explicit:
636
+ return Path(explicit)
637
+ out = getattr(args, "out", None)
638
+ return Path(str(out) + ".records.jsonl") if out else None
639
+
640
+
641
+ def run_eval_cli(args) -> None: # type: ignore[no-untyped-def]
642
+ tasks_path = Path(args.tasks) if args.tasks else None
643
+ tasks = load_tasks(tasks_path, args.limit)
644
+ checkpoint = _checkpoint_path(args)
645
+ resume = bool(getattr(args, "resume", False))
646
+ if resume and not checkpoint:
647
+ raise SystemExit("--resume needs --checkpoint PATH (or --out, whose checkpoint is <out>.records.jsonl)")
648
+ conditions = dataset_revision(tasks, tasks_path)
649
+ if args.mode == "simulated":
650
+ rep = run_simulated(tasks, seed=args.seed, checkpoint=checkpoint, resume=resume, conditions=conditions)
651
+ else:
652
+ rep = run_live(args, tasks, checkpoint=checkpoint, resume=resume, conditions=conditions)
653
+ print(render_report(rep))
654
+ if args.out:
655
+ Path(args.out).write_text(json.dumps(rep, indent=2), encoding="utf-8")
656
+ print(f"\nreport written to {args.out}")
657
+
658
+
659
+ def run_simulated(
660
+ tasks: list[dict[str, Any]], seed: int = 7, checkpoint: Path | None = None, resume: bool = False, conditions: dict[str, Any] | None = None
661
+ ) -> dict[str, Any]:
662
+ import tempfile
663
+
664
+ from ..config import BackendConfig, Config, ResourcePool, generate_key, write_key_file
665
+ from ..runtime import GatewayThread, free_port
666
+ from ..testing.fakebackend import FakeBackend, FakeModel
667
+
668
+ fake = FakeBackend(
669
+ [
670
+ FakeModel("sim-small:1b", ["completion", "tools"], 8192, parameter_size="1.0B", loaded=True, token_delay_s=0.0, good_at=["conversation", "summarization", "translation", "decision"]),
671
+ FakeModel("sim-code:7b", ["completion", "tools"], 16384, parameter_size="7B", size_bytes=4_500_000_000, token_delay_s=0.002, good_at=["coding", "agent", "conversation", "rag"]),
672
+ FakeModel("sim-large:27b", ["completion", "tools", "vision", "thinking"], 32768, parameter_size="27B", size_bytes=18_000_000_000, token_delay_s=0.005, good_at=["coding", "math", "extraction", "document_vision", "rag", "summarization", "translation"]),
673
+ ]
674
+ )
675
+ burl = fake.start()
676
+ tmp = Path(tempfile.mkdtemp(prefix="modelsaar-eval-"))
677
+ api_key, admin_key = generate_key("msk"), generate_key("msa")
678
+ write_key_file(tmp / "keys/api_keys", [api_key])
679
+ write_key_file(tmp / "keys/admin_key", [admin_key])
680
+ cfg = Config(
681
+ resource_pools=(ResourcePool(id="sim", max_concurrent=2),),
682
+ backends=(BackendConfig(id="sim", type="ollama", base_url=burl, resource_pool="sim"),),
683
+ deployments=(),
684
+ )
685
+ cfg = cfg.model_copy(update={"server": cfg.server.model_copy(update={"port": free_port()}), "config_path": str(tmp / "config.yaml"), "config_hash": "eval-sim"})
686
+ # Give the code model a 'code' tag so the rules baseline and auto-code alias can use it.
687
+ from ..config import DeploymentOverride
688
+
689
+ cfg = cfg.model_copy(update={"deployments": (DeploymentOverride(backend="sim", model="sim-code:7b", tags=("code",)),)})
690
+ gw = GatewayThread(cfg)
691
+ url = gw.start()
692
+ try:
693
+ probes = probe_all(gw)
694
+ run = EvalRun(url, api_key, admin_key, simulated=True, seed=seed, checkpoint=checkpoint, resume=resume)
695
+ rep = evaluate(run, tasks, save_measurements_store=gw.store, conditions=conditions or dataset_revision(tasks))
696
+ rep["probes"] = probes
697
+ rep["note"] = (
698
+ "SIMULATED: deployments are fake backends whose correctness is scripted per category; this validates the "
699
+ "harness and the routing policy mechanics, NOT real model quality."
700
+ )
701
+ return rep
702
+ finally:
703
+ gw.stop()
704
+ fake.stop()
705
+
706
+
707
+ def restrict_auto_alias(cfg, dep_ids: list[str]): # type: ignore[no-untyped-def]
708
+ """Return a config whose ``auto`` alias may only choose among ``dep_ids`` (canonical ids)."""
709
+ aliases = dict(cfg.aliases)
710
+ aliases["auto"] = aliases["auto"].model_copy(update={"deployments": tuple(dep_ids)})
711
+ return cfg.model_copy(update={"aliases": aliases})
712
+
713
+
714
+ def run_live(args, tasks: list[dict[str, Any]], checkpoint: Path | None = None, resume: bool = False, conditions: dict[str, Any] | None = None) -> dict[str, Any]: # type: ignore[no-untyped-def]
715
+ from ..cli import _load
716
+ from ..config import read_keys
717
+ from ..runtime import GatewayThread, free_port
718
+
719
+ cfg = _load(args)
720
+ # The live evaluation runs its own in-process gateway (own admission) against the same
721
+ # backends. A gateway already listening on the configured port would run uncoordinated
722
+ # inference next to it, so that is refused unless the operator accepts it explicitly.
723
+ from ..cli import _gateway_listening
724
+
725
+ listening = _gateway_listening(cfg)
726
+ if listening is not None and not getattr(args, "allow_concurrent", False):
727
+ what = "a ModelSaar gateway" if listening == "gateway" else "another process"
728
+ raise SystemExit(
729
+ f"{what} is listening on {cfg.server.host}:{cfg.server.port}; a live evaluation would run inference "
730
+ "outside its admission control. Stop it first, or pass --allow-concurrent to accept that."
731
+ )
732
+ cfg = cfg.model_copy(update={"server": cfg.server.model_copy(update={"port": free_port()})})
733
+ api = read_keys(cfg.resolve(cfg.server.api_keys_file))
734
+ adm = read_keys(cfg.resolve(cfg.server.admin_key_file))
735
+ if not api or not adm:
736
+ raise SystemExit("keys missing; run `modelsaar init`")
737
+ selected: list[str] | None = None
738
+ if args.deployments:
739
+ # Resolve selectors ONCE against the discovered registry, then restrict the `auto` alias to the
740
+ # same canonical ids that calibration and every baseline sweep use (fair comparison). The
741
+ # alias lives in the immutable config, so discover, resolve, stop, rebuild, start again.
742
+ gw0 = GatewayThread(cfg)
743
+ url0 = gw0.start()
744
+ try:
745
+ discovered = EvalRun(url0, api[0], adm[0], simulated=False).all_deployments()
746
+ finally:
747
+ gw0.stop()
748
+ try:
749
+ selected = resolve_selectors(discovered, list(args.deployments))
750
+ except ValueError as e:
751
+ raise SystemExit(f"--deployments: {e}") from None
752
+ cfg = restrict_auto_alias(cfg, selected)
753
+ gw = GatewayThread(cfg)
754
+ url = gw.start()
755
+ try:
756
+ probes = probe_all(gw) if args.probe else []
757
+ run = EvalRun(url, api[0], adm[0], simulated=False, seed=args.seed, checkpoint=checkpoint, resume=resume)
758
+ try:
759
+ rep = evaluate(run, tasks, save_measurements_store=gw.store if args.save_measurements else None, only=selected, conditions=conditions or dataset_revision(tasks))
760
+ except ValueError as e:
761
+ raise SystemExit(f"--deployments: {e}") from None
762
+ if selected:
763
+ rep["deployment_filter"] = {"selectors": list(args.deployments), "resolved": selected}
764
+ rep["probes"] = probes
765
+ rep["note"] = "LIVE: real backends from your config; results are specific to the exact deployments/fingerprints listed."
766
+ return rep
767
+ finally:
768
+ gw.stop()