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,233 @@
1
+ """Scorers for evaluation tasks. Executable where possible; never an LLM judge.
2
+
3
+ ``score(task, response)`` returns ``(ok, detail)``. ``ok`` is ``True``/``False``, or ``None`` when
4
+ the task could not be scored at all (currently only ``code_exec`` without an isolation
5
+ backend); the harness counts ``None`` as *skipped* with its own denominator, never as a failure
6
+ and never as a success.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from collections.abc import Callable
14
+ from typing import Any
15
+
16
+ from . import sandbox
17
+
18
+ # Bump whenever a scorer's acceptance rule changes so reports are not compared across rules.
19
+ SCORER_VERSION = "2026.10.12-3"
20
+
21
+ _CODE_BLOCK = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL)
22
+ # Standalone numeric tokens: optional sign (not glued to a preceding word/number, so "25-7"
23
+ # yields 25 and 7), digits with optional thousands commas, optional decimal part.
24
+ _NUMBER = re.compile(r"(?<![\w.])(-?)(\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?(?![\w])")
25
+
26
+ Runner = Callable[[str, str, float], tuple[str, str, int, str]]
27
+
28
+
29
+ def _basic_schema_check(obj: Any, schema: dict[str, Any]) -> bool:
30
+ """Minimal JSON-schema conformance (type/required/additionalProperties/properties types)."""
31
+ t = schema.get("type")
32
+ if t == "object":
33
+ if not isinstance(obj, dict):
34
+ return False
35
+ props = schema.get("properties", {})
36
+ for r in schema.get("required", []):
37
+ if r not in obj:
38
+ return False
39
+ if schema.get("additionalProperties") is False and set(obj) - set(props):
40
+ return False
41
+ return all(_basic_schema_check(obj[k], props[k]) for k in obj if k in props)
42
+ if t == "array":
43
+ return isinstance(obj, list) and all(_basic_schema_check(x, schema.get("items", {})) for x in obj)
44
+ if t == "string":
45
+ return isinstance(obj, str)
46
+ if t == "integer":
47
+ return isinstance(obj, int) and not isinstance(obj, bool)
48
+ if t == "number":
49
+ return isinstance(obj, (int, float)) and not isinstance(obj, bool)
50
+ if t == "boolean":
51
+ return isinstance(obj, bool)
52
+ return True
53
+
54
+
55
+ def normalise_stdout(s: str) -> str:
56
+ """Whitespace rule for ``code_exec`` (applied to BOTH expected and actual output).
57
+
58
+ Trailing whitespace on every line and trailing blank lines are ignored; leading whitespace
59
+ and internal spacing are significant; ``\\r\\n`` is treated as ``\\n``.
60
+ """
61
+ lines = [ln.rstrip() for ln in s.replace("\r\n", "\n").split("\n")]
62
+ while lines and not lines[-1]:
63
+ lines.pop()
64
+ return "\n".join(lines)
65
+
66
+
67
+ def extract_numbers(text: str) -> list[float]:
68
+ out = []
69
+ for sign, intpart, frac in _NUMBER.findall(text):
70
+ try:
71
+ out.append(float(sign + intpart.replace(",", "") + (frac or "")))
72
+ except ValueError:
73
+ continue
74
+ return out
75
+
76
+
77
+ def _number_matches(got: float, want: float, tol: float) -> bool:
78
+ return abs(got - want) <= max(tol, tol * abs(want))
79
+
80
+
81
+ def _tool_definition(task: dict[str, Any], name: str) -> dict[str, Any] | None:
82
+ for t in task.get("tools") or []:
83
+ fn = t.get("function") or {}
84
+ if fn.get("name") == name:
85
+ return fn
86
+ return None
87
+
88
+
89
+ def _score_tool_call(task: dict[str, Any], msg: dict[str, Any], exp: dict[str, Any]) -> tuple[bool, str]:
90
+ """Strict: the call must be well-formed AND carry the arguments the task needs.
91
+
92
+ (Whether the *agent task* was completed is a separate question; this scorer only says the
93
+ tool was invoked correctly.)
94
+ """
95
+ name = exp["name"]
96
+ calls = msg.get("tool_calls") or []
97
+ if not isinstance(calls, list):
98
+ return False, "tool_calls is not a list"
99
+ tool_def = _tool_definition(task, name) or {}
100
+ required = list(((tool_def.get("parameters") or {}).get("required")) or [])
101
+ args_contains: dict[str, str] = exp.get("args_contains") or {}
102
+ names = []
103
+ reasons = []
104
+ for c in calls:
105
+ if not isinstance(c, dict):
106
+ reasons.append("tool call is not an object")
107
+ continue
108
+ fn = c.get("function") or {}
109
+ names.append(fn.get("name"))
110
+ if fn.get("name") != name:
111
+ continue
112
+ cid = c.get("id")
113
+ if not isinstance(cid, str) or not cid.strip():
114
+ reasons.append("tool call has no id")
115
+ continue
116
+ raw = fn.get("arguments")
117
+ if raw is None or raw == "":
118
+ raw = "{}"
119
+ if isinstance(raw, dict):
120
+ args: Any = raw
121
+ else:
122
+ try:
123
+ args = json.loads(raw)
124
+ except (json.JSONDecodeError, TypeError):
125
+ reasons.append("tool call arguments not JSON")
126
+ continue
127
+ if not isinstance(args, dict):
128
+ reasons.append("tool call arguments are not an object")
129
+ continue
130
+ missing = [k for k in required if k not in args]
131
+ if missing:
132
+ reasons.append(f"missing required argument(s) {missing}")
133
+ continue
134
+ params = tool_def.get("parameters")
135
+ if isinstance(params, dict) and not _basic_schema_check(args, params):
136
+ # Declared schema is the contract: a list where a string is required is a wrong call
137
+ # even if its text representation contains the expected substring.
138
+ reasons.append("arguments do not conform to the tool's declared parameter schema")
139
+ continue
140
+ bad = [k for k, sub in args_contains.items() if not isinstance(args.get(k), (str, int, float)) or str(sub) not in str(args.get(k, ""))]
141
+ if bad:
142
+ reasons.append(f"argument(s) {bad} do not contain expected substring(s) {[args_contains[k] for k in bad]}")
143
+ continue
144
+ return True, f"called {name} with id, valid JSON object args {sorted(args)}" + (f", {args_contains}" if args_contains else "")
145
+ if reasons:
146
+ return False, f"tool call {name} rejected: " + "; ".join(reasons)
147
+ return False, f"expected tool call {name}, got {names} / content"
148
+
149
+
150
+ def _score_code_exec(task: dict[str, Any], text: str, exp: dict[str, Any], runner: Runner | None) -> tuple[bool | None, str]:
151
+ """Scored from the trusted runner's result record (see ``sandbox._program``): the harness must
152
+ have completed and *its* captured output must equal the expectation. Text the model code
153
+ prints, including the public sentinel, is never evidence; a missing or foreign record fails."""
154
+ m = _CODE_BLOCK.search(text)
155
+ code = m.group(1) if m else text
156
+ if runner is None:
157
+ backend, reason = sandbox.available()
158
+ if backend is None:
159
+ return None, f"skipped: {reason}"
160
+ runner = sandbox.run
161
+ out, err, rc, backend = runner(code, exp["harness"], float(exp.get("timeout_s", 10.0)))
162
+ rec = sandbox.parse_result(out, getattr(runner, "last_nonce", ""))
163
+ want = normalise_stdout(str(exp["stdout"]))
164
+ problems = []
165
+ if rc != 0:
166
+ problems.append(f"exit code {rc}")
167
+ if rec is None:
168
+ problems.append("no result record from the runner (model code exited or crashed before the harness ran)")
169
+ body = ""
170
+ else:
171
+ if not rec.get("model_ran"):
172
+ problems.append(rec.get("error") or "model code did not run")
173
+ elif not rec.get("harness_completed"):
174
+ problems.append(rec.get("error") or "harness did not complete")
175
+ body = normalise_stdout(str(rec.get("harness_stdout", "")))
176
+ if body != want:
177
+ problems.append(f"harness output {body[:200]!r} != expected {want[:200]!r}")
178
+ if problems:
179
+ return False, f"[{backend}] " + "; ".join(problems) + (f" err={err[-300:]!r}" if err else "")
180
+ return True, f"[{backend}] harness completed with expected output, exit 0"
181
+
182
+
183
+ def score(task: dict[str, Any], response: dict[str, Any], runner: Runner | None = None) -> tuple[bool | None, str]:
184
+ """Return (success, detail) for a successful HTTP response body.
185
+
186
+ ``runner`` (tests only) replaces the sandbox for ``code_exec``; it must have the signature of
187
+ :func:`modelsaar.evaluation.sandbox.run`.
188
+ """
189
+ exp = task["expected"]
190
+ kind = exp["type"]
191
+ try:
192
+ msg = response["choices"][0]["message"]
193
+ except (KeyError, IndexError, TypeError):
194
+ return False, "malformed response"
195
+ content = msg.get("content")
196
+ if isinstance(content, list):
197
+ content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
198
+ text = (content or "").strip()
199
+ low = text.lower()
200
+ if kind == "nonempty":
201
+ return bool(text), "nonempty" if text else "empty"
202
+ if kind == "contains":
203
+ ok = str(exp["value"]).lower() in low
204
+ return ok, f"contains {exp['value']!r}" if ok else f"missing {exp['value']!r}"
205
+ if kind == "contains_any":
206
+ hit = next((v for v in exp["value"] if str(v).lower() in low), None)
207
+ return hit is not None, f"contains {hit!r}" if hit else f"none of {exp['value']}"
208
+ if kind == "number":
209
+ nums = extract_numbers(text)
210
+ if not nums:
211
+ return False, "no numeric token in content"
212
+ want = float(exp["value"])
213
+ tol = float(exp.get("tol", 1e-6))
214
+ got = nums[-1]
215
+ ok = _number_matches(got, want, tol)
216
+ return ok, f"last number {got:g} {'==' if ok else '!='} {want:g} (tol {tol:g}, {len(nums)} numeric token(s))"
217
+ if kind == "tool_call":
218
+ return _score_tool_call(task, msg, exp)
219
+ if kind == "json_schema":
220
+ try:
221
+ obj = json.loads(text)
222
+ except json.JSONDecodeError:
223
+ return False, "content is not JSON"
224
+ if not _basic_schema_check(obj, exp["schema"]):
225
+ return False, "JSON does not conform to schema"
226
+ for k, v in (exp.get("checks") or {}).items():
227
+ if obj.get(k) != v:
228
+ return False, f"field {k}={obj.get(k)!r} != {v!r}"
229
+ return True, "schema-conformant with correct fields"
230
+ if kind == "code_exec":
231
+ return _score_code_exec(task, text, exp, runner)
232
+ return False, f"unknown scorer {kind}"
233
+
modelsaar/learning.py ADDED
@@ -0,0 +1,227 @@
1
+ """Opt-in adaptive learning from outcomes — versioned, holdout-gated, local, reversible.
2
+
3
+ Off by default (``learning.enabled: false``): nothing is recorded and ranking is unchanged. When enabled,
4
+ the gateway keeps **outcome metadata only** — request id, deployment id and fingerprint, task label, one
5
+ boolean, a source tag, a timestamp — in its own state database. No prompt, answer, tool argument or
6
+ caller identity is stored, and nothing is ever sent anywhere.
7
+
8
+ What counts as an outcome:
9
+
10
+ * ``feedback`` — an explicit verdict from the client (``POST /v1/feedback``) for a request it made.
11
+ * ``structural_failure`` — the gateway observed a reliability failure (bad envelope, truncated or failed
12
+ stream, timeout). A successful HTTP response is **not** recorded as a success: completing a response
13
+ is not task success.
14
+
15
+ Outcomes never change routing by themselves. An administrator *builds* a policy version (a snapshot of
16
+ per-(deployment, task) success estimates from the training split), which is scored on a holdout split
17
+ against what the router uses today; only a version that predicts the holdout outcomes better can be
18
+ *activated*, and ``rollback`` returns to the simpler router at once. Estimates are bound to the deployment
19
+ fingerprint, so a changed model invalidates them. There is no exploration: the gateway never sends a
20
+ request to a deployment in order to learn about it.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import json
27
+ import time
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from .config import LearningConfig
31
+ from .registry import Deployment, Measurement
32
+ from .store import Store
33
+
34
+ if TYPE_CHECKING:
35
+ from .routing.router import Router
36
+
37
+ _SCHEMA = """
38
+ CREATE TABLE IF NOT EXISTS outcomes (
39
+ request_id TEXT PRIMARY KEY, deployment_id TEXT NOT NULL, fingerprint TEXT NOT NULL, task TEXT NOT NULL,
40
+ success INTEGER NOT NULL, source TEXT NOT NULL, created_at REAL NOT NULL);
41
+ CREATE TABLE IF NOT EXISTS learned_policies (
42
+ version INTEGER PRIMARY KEY AUTOINCREMENT, created_at REAL NOT NULL, status TEXT NOT NULL,
43
+ report TEXT NOT NULL, cells TEXT NOT NULL);
44
+ """
45
+ STRUCTURAL_FAILURES = frozenset(
46
+ {"upstream_bad_response", "stream_truncated_after_commit", "stream_invalid_after_commit", "stream_failed_after_commit", "stream_timeout_after_commit"}
47
+ )
48
+ _PRIOR_STRENGTH = 4.0
49
+
50
+
51
+ class LearningError(Exception):
52
+ def __init__(self, message: str, status: int = 409, code: str = "learning_refused") -> None:
53
+ super().__init__(message)
54
+ self.message, self.status, self.code = message, status, code
55
+
56
+
57
+ def _holdout(request_id: str, fraction: float) -> bool:
58
+ return int(hashlib.sha256(request_id.encode()).hexdigest()[:8], 16) % 10_000 < fraction * 10_000
59
+
60
+
61
+ class Learning:
62
+ def __init__(self, store: Store | None, cfg: LearningConfig) -> None:
63
+ self.store, self.cfg = store, cfg
64
+ self._active: tuple[int, dict[str, Any]] | None = None
65
+ if store is not None:
66
+ with store._lock:
67
+ store._conn.executescript(_SCHEMA)
68
+ store._conn.commit()
69
+ self._load_active()
70
+
71
+ # ------------------------------------------------------------------ storage helpers
72
+ def _q(self, sql: str, args: tuple = ()) -> list[tuple]:
73
+ with self.store._lock: # type: ignore[union-attr]
74
+ cur = self.store._conn.execute(sql, args) # type: ignore[union-attr]
75
+ rows = cur.fetchall()
76
+ self.store._conn.commit() # type: ignore[union-attr]
77
+ return rows
78
+
79
+ def _load_active(self) -> None:
80
+ rows = self._q("SELECT version, cells FROM learned_policies WHERE status='active' ORDER BY version DESC LIMIT 1")
81
+ self._active = (rows[0][0], json.loads(rows[0][1])) if rows else None
82
+
83
+ def _need(self) -> None:
84
+ if self.store is None:
85
+ raise LearningError("learning needs the state database (server.state_db)", 409, "learning_unavailable")
86
+ if not self.cfg.enabled:
87
+ raise LearningError("learning is disabled (learning.enabled: false); nothing is recorded and no policy can be built", 409, "learning_disabled")
88
+
89
+ # ------------------------------------------------------------------ recording
90
+ def record(self, request_id: str, dep: Deployment, task: str, success: bool, source: str) -> None:
91
+ if self.store is None or not self.cfg.enabled:
92
+ return
93
+ now = time.time()
94
+ self._q(
95
+ "INSERT OR REPLACE INTO outcomes VALUES (?,?,?,?,?,?,?)",
96
+ (request_id, dep.id, dep.fingerprint, task or "conversation", 1 if success else 0, source, now),
97
+ )
98
+ self._q("DELETE FROM outcomes WHERE created_at < ?", (now - self.cfg.retention_days * 86400,))
99
+
100
+ def feedback(self, router: Router, request_id: str, success: bool) -> dict[str, Any]:
101
+ self._need()
102
+ dec = self.store.get_decision(request_id) # type: ignore[union-attr]
103
+ if not dec or dec.get("endpoint") not in ("chat", "responses", "messages") or dec.get("outcome") != "ok" or not dec.get("chosen"):
104
+ raise LearningError(
105
+ f"request {request_id!r} is not a completed chat request in the decision log (retention {router.cfg.observability.retention_days} days); "
106
+ "feedback is accepted only for requests the gateway answered",
107
+ 404,
108
+ "unknown_request",
109
+ )
110
+ dep = router.registry.get(dec["chosen"])
111
+ if dep is None:
112
+ raise LearningError(f"deployment {dec['chosen']} is no longer registered", 404, "unknown_deployment")
113
+ task = str((dec.get("requirements") or {}).get("primary_task") or "conversation")
114
+ self.record(request_id, dep, task, success, "feedback")
115
+ return {"recorded": True, "request_id": request_id, "deployment": dep.id, "task": task, "success": bool(success)}
116
+
117
+ # ------------------------------------------------------------------ policies
118
+ def build(self, router: Router) -> dict[str, Any]:
119
+ """Snapshot per-(deployment, task) success estimates from the training split and score them on the
120
+ holdout split against the router's current estimate (Brier score; lower is better)."""
121
+ self._need()
122
+ from .routing.scoring import quality_estimate
123
+
124
+ fps = {d.id: d for d in router.registry.all()}
125
+ rows = [r for r in self._q("SELECT request_id, deployment_id, fingerprint, task, success FROM outcomes") if r[1] in fps and fps[r[1]].fingerprint == r[2]]
126
+ train = [r for r in rows if not _holdout(r[0], self.cfg.holdout_fraction)]
127
+ hold = [r for r in rows if _holdout(r[0], self.cfg.holdout_fraction)]
128
+
129
+ def baseline(dep_id: str, task: str) -> float:
130
+ d = fps[dep_id]
131
+ kept = d.measurements
132
+ d.measurements = {k: v for k, v in kept.items() if not str(v.source).startswith("learned")}
133
+ try:
134
+ return float(quality_estimate(d, task, router.cfg.routing)[0])
135
+ finally:
136
+ d.measurements = kept
137
+
138
+ agg: dict[tuple[str, str], list[int]] = {}
139
+ for _, dep_id, _, task, ok in train:
140
+ n = agg.setdefault((dep_id, task), [0, 0])
141
+ n[0] += 1
142
+ n[1] += ok
143
+ cells = []
144
+ for (dep_id, task), (n, s) in sorted(agg.items()):
145
+ if n < self.cfg.min_samples:
146
+ continue
147
+ prior = baseline(dep_id, task)
148
+ cells.append({"deployment": dep_id, "fingerprint": fps[dep_id].fingerprint, "task": task, "samples": n, "successes": s, "estimate": round((s + prior * _PRIOR_STRENGTH) / (n + _PRIOR_STRENGTH), 4), "baseline": round(prior, 4)})
149
+ est = {(c["deployment"], c["task"]): c for c in cells}
150
+ scored = [(est[(r[1], r[3])], r[4]) for r in hold if (r[1], r[3]) in est]
151
+ report: dict[str, Any] = {
152
+ "outcomes_usable": len(rows), "train": len(train), "holdout": len(hold), "holdout_scored": len(scored), "cells": len(cells),
153
+ "min_samples": self.cfg.min_samples, "holdout_fraction": self.cfg.holdout_fraction,
154
+ "sources": dict(self._q("SELECT source, COUNT(*) FROM outcomes GROUP BY source")),
155
+ } # fmt: skip
156
+ if not cells:
157
+ report["verdict"] = "insufficient_data"
158
+ elif len(scored) < self.cfg.min_holdout:
159
+ report["verdict"] = "insufficient_holdout"
160
+ else:
161
+ bl = sum((c["estimate"] - y) ** 2 for c, y in scored) / len(scored)
162
+ bb = sum((c["baseline"] - y) ** 2 for c, y in scored) / len(scored)
163
+ report.update(brier_learned=round(bl, 4), brier_baseline=round(bb, 4), verdict="better" if bl < bb - self.cfg.min_improvement else "not_better")
164
+ self._q("INSERT INTO learned_policies (created_at, status, report, cells) VALUES (?,?,?,?)", (time.time(), "built", json.dumps(report), json.dumps(cells)))
165
+ version = self._q("SELECT MAX(version) FROM learned_policies")[0][0]
166
+ return {"version": version, "status": "built", "report": report, "cells": cells}
167
+
168
+ def activate(self, version: int) -> dict[str, Any]:
169
+ self._need()
170
+ rows = self._q("SELECT status, report FROM learned_policies WHERE version=?", (version,))
171
+ if not rows:
172
+ raise LearningError(f"policy version {version} does not exist", 404, "unknown_policy")
173
+ report = json.loads(rows[0][1])
174
+ if report.get("verdict") != "better":
175
+ raise LearningError(
176
+ f"policy v{version} did not beat the current estimates on the holdout split (verdict: {report.get('verdict')}); "
177
+ "the simpler router stays. There is no override",
178
+ 409,
179
+ "holdout_not_passed",
180
+ )
181
+ self._q("UPDATE learned_policies SET status='superseded' WHERE status='active'")
182
+ self._q("UPDATE learned_policies SET status='active' WHERE version=?", (version,))
183
+ self._load_active()
184
+ return {"active": version, "report": report}
185
+
186
+ def rollback(self) -> dict[str, Any]:
187
+ if self.store is None:
188
+ raise LearningError("learning needs the state database", 409, "learning_unavailable")
189
+ was = self._active[0] if self._active else None
190
+ self._q("UPDATE learned_policies SET status='rolled_back' WHERE status='active'")
191
+ self._active = None
192
+ return {"rolled_back": was, "active": None}
193
+
194
+ def purge(self) -> dict[str, Any]:
195
+ if self.store is None:
196
+ raise LearningError("learning needs the state database", 409, "learning_unavailable")
197
+ n = self._q("SELECT COUNT(*) FROM outcomes")[0][0]
198
+ self._q("DELETE FROM outcomes")
199
+ self._q("DELETE FROM learned_policies")
200
+ self._active = None
201
+ return {"outcomes_deleted": n, "policies_deleted": True, "active": None}
202
+
203
+ def status(self) -> dict[str, Any]:
204
+ out: dict[str, Any] = {"enabled": self.cfg.enabled, "active_version": self._active[0] if self._active else None}
205
+ if self.store is not None:
206
+ out["outcomes"] = dict(self._q("SELECT source, COUNT(*) FROM outcomes GROUP BY source"))
207
+ out["policies"] = [{"version": v, "status": s, "created_at": c, "report": json.loads(r)} for v, s, c, r in self._q("SELECT version, status, created_at, report FROM learned_policies ORDER BY version DESC LIMIT 20")]
208
+ return out
209
+
210
+ # ------------------------------------------------------------------ use in ranking
211
+ def apply(self, dep: Deployment) -> None:
212
+ """Attach the active policy's estimates to a deployment as labelled evidence (``learned:v<N>``).
213
+ A harness measurement for the same task always wins; a different fingerprint never matches."""
214
+ if not self._active or not self.cfg.enabled:
215
+ return
216
+ version, cells = self._active
217
+ for c in cells:
218
+ if c["deployment"] != dep.id or c["fingerprint"] != dep.fingerprint:
219
+ continue
220
+ cur = dep.measurements.get(c["task"])
221
+ if cur is not None and cur.quality is not None and cur.samples > 0 and not str(cur.source).startswith("learned"):
222
+ continue
223
+ dep.measurements[c["task"]] = Measurement(
224
+ task=c["task"], quality=c["estimate"], samples=c["samples"], source=f"learned:v{version}",
225
+ p50_ms=cur.p50_ms if cur else None, p95_ms=cur.p95_ms if cur else None, ttft_ms=cur.ttft_ms if cur else None, load_ms=cur.load_ms if cur else None,
226
+ conditions={"basis": "passive outcomes (client feedback + structural failures)", "policy_version": version},
227
+ ) # fmt: skip
modelsaar/lifecycle.py ADDED
@@ -0,0 +1,208 @@
1
+ """Managed model lifecycle — opt-in, explicit, lease- and lock-guarded.
2
+
3
+ Default behaviour is unchanged: the gateway cooperates with user-managed inference servers and
4
+ never loads or unloads anything. Only a backend that declares ``lifecycle.managed: true`` can be
5
+ asked — by an administrator, through ``/admin/lifecycle/*`` or ``modelsaar lifecycle`` — to load or
6
+ unload one of its models. There is no automatic eviction and no model download.
7
+
8
+ Safety rules:
9
+
10
+ * **Locks.** One operation at a time per deployment (``asyncio.Lock``); a second load/unload for the
11
+ same deployment waits for the first instead of racing it.
12
+ * **Leases.** A deployment with an in-flight or uncertain reservation (an implicit lease held by the
13
+ admission layer) or with an unexpired explicit lease is never unloaded: the request is refused with
14
+ ``409``. There is no force option.
15
+ * **No race with dispatch.** While an unload is deciding and executing, the deployment is *draining*:
16
+ the admission layer admits no new request for it, so a dispatch cannot slip in between the busy
17
+ check and the runtime call.
18
+ * **Budgets.** A load goes through the same atomic admission (slots and pool memory budget) as an
19
+ inference request; a load that does not fit is refused, it never evicts another model.
20
+
21
+ What a lease is not: it cannot stop the runtime's own keep-alive expiry, another client talking to
22
+ the runtime directly, or the operating system. The backend stays authoritative for what is loaded;
23
+ residency is re-observed after every operation.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import time
30
+ import uuid
31
+ from collections import deque
32
+ from dataclasses import dataclass
33
+ from typing import TYPE_CHECKING, Any
34
+
35
+ from .adapters.base import AdapterError
36
+ from .registry import Deployment
37
+ from .routing.admission import AdmissionRejected
38
+ from .security import redact
39
+
40
+ if TYPE_CHECKING:
41
+ from .routing.router import Router
42
+
43
+
44
+ class LifecycleError(Exception):
45
+ def __init__(self, message: str, status: int = 409, code: str = "lifecycle_refused") -> None:
46
+ super().__init__(message)
47
+ self.message, self.status, self.code = message, status, code
48
+
49
+
50
+ @dataclass
51
+ class Lease:
52
+ id: str
53
+ deployment: str
54
+ holder: str
55
+ created_at: float
56
+ expires_at: float
57
+
58
+ def as_dict(self) -> dict[str, Any]:
59
+ return {"id": self.id, "deployment": self.deployment, "holder": self.holder, "expires_in_s": round(max(0.0, self.expires_at - time.time()), 1)}
60
+
61
+
62
+ class LifecycleManager:
63
+ def __init__(self, router: Router) -> None:
64
+ self.router = router
65
+ self._locks: dict[str, asyncio.Lock] = {}
66
+ self._leases: dict[str, Lease] = {}
67
+ self.history: deque[dict[str, Any]] = deque(maxlen=50)
68
+
69
+ # ------------------------------------------------------------------ #
70
+ def _cfg(self, dep: Deployment): # type: ignore[no-untyped-def]
71
+ a = self.router.adapters.get(dep.backend_id)
72
+ return a.cfg.lifecycle if a is not None else None
73
+
74
+ def _dep(self, dep_id: str, op: str) -> Deployment:
75
+ dep = self.router.registry.get(dep_id)
76
+ if dep is None:
77
+ raise LifecycleError(f"deployment {dep_id!r} not found", 404, "unknown_deployment")
78
+ lc = self._cfg(dep)
79
+ if lc is None or not lc.managed:
80
+ raise LifecycleError(
81
+ f"backend {dep.backend_id!r} is not managed: the gateway never loads or unloads models on a backend "
82
+ "without `lifecycle.managed: true` (docs/lifecycle.md)",
83
+ 403,
84
+ "backend_not_managed",
85
+ )
86
+ adapter = self.router.adapters[dep.backend_id]
87
+ if op not in adapter.lifecycle_operations():
88
+ raise LifecycleError(
89
+ f"the {dep.backend_type} path of backend {dep.backend_id!r} cannot {op} a model "
90
+ f"(supported here: {sorted(adapter.lifecycle_operations()) or 'nothing'})",
91
+ 501,
92
+ "lifecycle_unsupported",
93
+ )
94
+ return dep
95
+
96
+ def _live_leases(self, dep_id: str | None = None) -> list[Lease]:
97
+ now = time.time()
98
+ for k in [k for k, v in self._leases.items() if v.expires_at <= now]:
99
+ self._leases.pop(k, None)
100
+ return [v for v in self._leases.values() if dep_id is None or v.deployment == dep_id]
101
+
102
+ def _record(self, op: str, dep_id: str, outcome: str, detail: str = "") -> dict[str, Any]:
103
+ rec = {"at": time.time(), "operation": op, "deployment": dep_id, "outcome": outcome, "detail": redact(detail)[:200]}
104
+ self.history.append(rec)
105
+ return rec
106
+
107
+ # ------------------------------------------------------------------ #
108
+ async def load(self, dep_id: str, hold_s: float | None = None, holder: str = "admin") -> dict[str, Any]:
109
+ dep = self._dep(dep_id, "load")
110
+ lc = self._cfg(dep)
111
+ if not dep.healthy or not dep.enabled:
112
+ raise LifecycleError(f"{dep_id} is not a healthy, enabled deployment", 422, "not_loadable")
113
+ if hold_s is not None and not (0 < hold_s <= lc.max_lease_s):
114
+ raise LifecycleError(f"hold_s must be within (0, {lc.max_lease_s:g}] for this backend (lifecycle.max_lease_s)", 400, "invalid_request_error")
115
+ lock = self._locks.setdefault(dep_id, asyncio.Lock())
116
+ async with lock:
117
+ try:
118
+ # Same atomic admission as an inference request: slots and the pool's memory budget.
119
+ reservation = await self.router.admission.acquire(dep, timeout=None)
120
+ except AdmissionRejected as e:
121
+ self._record("load", dep_id, "refused", e.message)
122
+ raise LifecycleError(f"load refused by admission: {e.message}", e.status, "admission_rejected") from e
123
+ keep_alive = lc.keep_alive_s
124
+ if hold_s is not None:
125
+ keep_alive = max(int(hold_s), keep_alive or 0)
126
+ adapter = self.router.adapters[dep.backend_id]
127
+ t0 = time.monotonic()
128
+ try:
129
+ await adapter.load_model(dep, keep_alive, lc.load_timeout_s)
130
+ except AdapterError as e:
131
+ if e.kind == "timeout":
132
+ await reservation.mark_uncertain() # the runtime may still be loading
133
+ else:
134
+ await reservation.release(submitted=e.kind != "connect")
135
+ self._record("load", dep_id, "failed", e.message)
136
+ raise LifecycleError(f"load failed: {redact(e.message)}", 502, "lifecycle_failed") from e
137
+ await reservation.release()
138
+ lease = None
139
+ if hold_s is not None:
140
+ lease = Lease("lease_" + uuid.uuid4().hex[:12], dep_id, holder, time.time(), time.time() + hold_s)
141
+ self._leases[lease.id] = lease
142
+ await self.router.refresh_residency()
143
+ rec = self._record("load", dep_id, "ok", f"{(time.monotonic() - t0) * 1000:.0f}ms keep_alive={keep_alive}")
144
+ now = self.router.registry.get(dep_id)
145
+ return {**rec, "loaded_observed": bool(now and now.loaded), "keep_alive_s": keep_alive, "lease": lease.as_dict() if lease else None}
146
+
147
+ async def unload(self, dep_id: str) -> dict[str, Any]:
148
+ dep = self._dep(dep_id, "unload")
149
+ lc = self._cfg(dep)
150
+ lock = self._locks.setdefault(dep_id, asyncio.Lock())
151
+ adm = self.router.admission
152
+ async with lock:
153
+ adm.draining.add(dep_id) # no new dispatch can be admitted from here on
154
+ try:
155
+ busy = adm.holders(dep)
156
+ if busy:
157
+ self._record("unload", dep_id, "refused", f"{busy} in-flight/uncertain reservation(s)")
158
+ raise LifecycleError(
159
+ f"{dep_id} has {busy} in-flight or uncertain reservation(s); an active model is never unloaded "
160
+ "(retry when it is idle; uncertain holds expire after admission.uncertain_hold_s)",
161
+ 409,
162
+ "deployment_busy",
163
+ )
164
+ leases = self._live_leases(dep_id)
165
+ if leases:
166
+ self._record("unload", dep_id, "refused", f"{len(leases)} lease(s)")
167
+ raise LifecycleError(
168
+ f"{dep_id} is held by {len(leases)} lease(s) ({', '.join(x.id for x in leases)}); release them first",
169
+ 409,
170
+ "deployment_leased",
171
+ )
172
+ adapter = self.router.adapters[dep.backend_id]
173
+ try:
174
+ await adapter.unload_model(dep, lc.load_timeout_s)
175
+ except AdapterError as e:
176
+ self._record("unload", dep_id, "failed", e.message)
177
+ raise LifecycleError(f"unload failed: {redact(e.message)}", 502, "lifecycle_failed") from e
178
+ adm.forget_resident(dep)
179
+ finally:
180
+ adm.draining.discard(dep_id)
181
+ await self.router.refresh_residency()
182
+ now = self.router.registry.get(dep_id)
183
+ return {**self._record("unload", dep_id, "ok"), "loaded_observed": bool(now and now.loaded)}
184
+
185
+ def release(self, lease_id: str) -> dict[str, Any]:
186
+ lease = self._leases.pop(lease_id, None)
187
+ if lease is None:
188
+ raise LifecycleError(f"lease {lease_id!r} not found (expired or already released)", 404, "unknown_lease")
189
+ return {"released": lease.id, "deployment": lease.deployment}
190
+
191
+ def status(self) -> dict[str, Any]:
192
+ backends = {}
193
+ for bid, a in self.router.adapters.items():
194
+ lc = a.cfg.lifecycle
195
+ backends[bid] = {
196
+ "managed": lc.managed,
197
+ "operations": sorted(a.lifecycle_operations()) if lc.managed else [],
198
+ "keep_alive_s": lc.keep_alive_s,
199
+ "max_lease_s": lc.max_lease_s,
200
+ "loaded": sorted(d.id for d in self.router.registry.by_backend(bid) if d.loaded),
201
+ "in_flight": {d.id: n for d in self.router.registry.by_backend(bid) if (n := self.router.admission.holders(d))},
202
+ }
203
+ return {
204
+ "backends": backends,
205
+ "leases": [x.as_dict() for x in self._live_leases()],
206
+ "draining": sorted(self.router.admission.draining),
207
+ "history": list(self.history),
208
+ }