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,1026 @@
1
+ """Router: orchestrates discovery, evidence, eligibility, classification, ranking
2
+ and decision recording. It never dispatches; the server does that so that
3
+ response-commitment rules stay in one place.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import logging
11
+ import math
12
+ import time
13
+ from typing import Any
14
+ from urllib.parse import urlsplit
15
+
16
+ from ..adapters import ADAPTER_TYPES, BaseAdapter
17
+ from ..catalogue import apply_catalogue, load_catalogue
18
+ from ..config import Config
19
+ from ..registry import Deployment, Measurement, Registry, merge_capabilities
20
+ from ..store import Store
21
+ from .admission import Admission, AdmissionRejected
22
+ from .affinity import AffinityStore
23
+ from .classifier import LocalClassifier
24
+ from .decision import Decision
25
+ from .eligibility import filter_deployments
26
+ from .requirements import Requirements, analyze_chat
27
+ from .scoring import rank
28
+ from .tokens import estimate_chat_tokens
29
+
30
+ log = logging.getLogger("modelsaar.router")
31
+
32
+
33
+ class NoEligibleDeployment(Exception):
34
+ def __init__(self, decision: Decision) -> None:
35
+ super().__init__("no eligible deployment")
36
+ self.decision = decision
37
+
38
+
39
+ class Router:
40
+ def __init__(self, cfg: Config, store: Store | None = None) -> None:
41
+ self.cfg = cfg
42
+ self.store = store
43
+ self.registry = Registry()
44
+ allowed = set(cfg.security.allowed_backend_hosts)
45
+ for b in cfg.backends:
46
+ parts = urlsplit(b.base_url)
47
+ allowed.add(parts.netloc)
48
+ if parts.hostname:
49
+ allowed.add(parts.hostname)
50
+ self.allowed_hosts = allowed
51
+ self.adapters: dict[str, BaseAdapter] = {}
52
+ for b in cfg.backends:
53
+ cls = ADAPTER_TYPES.get(b.type)
54
+ if not cls:
55
+ raise ValueError(f"unknown backend type {b.type}")
56
+ self.adapters[b.id] = cls(b, allowed)
57
+ self.admission = Admission(cfg.admission, list(cfg.resource_pools), list(cfg.backends))
58
+ self.admission.pool_members = lambda pool_id: [d for d in self.registry.all() if d.resource_pool == pool_id]
59
+ self.affinity = AffinityStore(cfg.affinity)
60
+ self.classifier = LocalClassifier(cfg.routing.classifier)
61
+ self.catalogue = load_catalogue()
62
+ self._refresh_lock = asyncio.Lock()
63
+ self.last_refresh_error: str = ""
64
+ # Alias -> established embedding identity (process memory; mirrored in the state DB).
65
+ self._alias_identity_memory: dict[str, str] = {}
66
+ # Managed lifecycle (opt-in per backend; inert unless a backend sets lifecycle.managed).
67
+ from ..learning import Learning
68
+ from ..lifecycle import LifecycleManager
69
+
70
+ self.lifecycle = LifecycleManager(self)
71
+ # Opt-in adaptive learning (inert unless learning.enabled).
72
+ self.learning = Learning(store, cfg.learning)
73
+
74
+ async def aclose(self) -> None:
75
+ for a in self.adapters.values():
76
+ await a.aclose()
77
+
78
+ # ------------------------------------------------------------------ #
79
+ # Discovery & evidence
80
+ # ------------------------------------------------------------------ #
81
+ async def refresh(self) -> None:
82
+ async with self._refresh_lock:
83
+ deps: list[Deployment] = []
84
+ errors: list[str] = []
85
+ results = await asyncio.gather(
86
+ *[self._discover_backend(bid, a) for bid, a in self.adapters.items()], return_exceptions=True
87
+ )
88
+ for (bid, _), res in zip(self.adapters.items(), results, strict=True):
89
+ if isinstance(res, Exception):
90
+ errors.append(f"{bid}: {res}")
91
+ # keep previous records for this backend but mark unhealthy
92
+ for d in self.registry.by_backend(bid):
93
+ d.healthy = False
94
+ d.last_error = str(res)[:200]
95
+ deps.append(d)
96
+ else:
97
+ deps.extend(res)
98
+ for d in deps:
99
+ self._apply_overrides(d)
100
+ apply_catalogue(d, self.catalogue)
101
+ d.compute_fingerprint()
102
+ self._served_context_memory(d)
103
+ self._apply_stored_evidence(d)
104
+ # A failed residency query must not turn a known-loaded model into "unloaded":
105
+ # carry the previous observation forward until the runtime answers again.
106
+ a = self.adapters.get(d.backend_id)
107
+ if a is not None and getattr(a, "reports_residency", False) and a.last_residency_observation_ok is False:
108
+ prev = self.registry.get(d.id)
109
+ if prev is not None:
110
+ d.loaded = prev.loaded
111
+ d.loaded_observed_at = prev.loaded_observed_at
112
+ self.registry.replace(deps)
113
+ self.last_refresh_error = "; ".join(errors)
114
+ self._reconcile_residency(errors)
115
+
116
+ def _reconcile_residency(self, errors: list[str] | None = None) -> None:
117
+ """Hand the admission layer the backends whose residency was just observed (healthy adapters
118
+ that report it), so assumed-resident weights are replaced by the observation."""
119
+ failed = {e.split(":", 1)[0] for e in (errors or [])}
120
+ observed = {
121
+ bid for bid, a in self.adapters.items()
122
+ if getattr(a, "reports_residency", False) and bid not in failed
123
+ and a.last_residency_observation_ok is True # the residency query itself succeeded
124
+ and all(d.healthy for d in self.registry.by_backend(bid))
125
+ }
126
+ self.admission.reconcile_residency(self.registry.all(), observed)
127
+
128
+ async def _discover_backend(self, bid: str, adapter: BaseAdapter) -> list[Deployment]:
129
+ return await adapter.discover()
130
+
131
+ def _apply_overrides(self, d: Deployment) -> None:
132
+ for o in self.cfg.deployments:
133
+ if o.backend != d.backend_id or o.model != d.model:
134
+ continue
135
+ d.configured = True
136
+ if o.enabled is not None:
137
+ d.enabled = o.enabled
138
+ if o.role:
139
+ d.role = o.role
140
+ if o.context_length:
141
+ d.context_length = o.context_length
142
+ d.raw_metadata["num_ctx_source"] = "operator override"
143
+ if o.max_output_tokens:
144
+ d.max_output_tokens = o.max_output_tokens
145
+ if o.tags is not None:
146
+ d.tags = list(o.tags)
147
+ if o.catalogue_id:
148
+ d.catalogue_id = o.catalogue_id
149
+ if o.memory_gb_estimate:
150
+ d.memory_gb_estimate = o.memory_gb_estimate
151
+ d.memory_estimate_provenance = "operator override"
152
+ if o.capabilities:
153
+ merge_capabilities(
154
+ d, {k: v for k, v in o.capabilities.model_dump().items() if v != "unknown"}, "operator",
155
+ note="config deployments[] override",
156
+ )
157
+ if o.quality_prior:
158
+ d.quality_prior = dict(o.quality_prior)
159
+ d.quality_prior_provenance = "operator"
160
+ if o.intended_use_note:
161
+ d.intended_use_note = o.intended_use_note
162
+
163
+ def _apply_stored_evidence(self, d: Deployment) -> None:
164
+ if not self.store:
165
+ return
166
+ probes = self.store.load_probes(d.id, d.fingerprint)
167
+ caps = {k: v["value"] for k, v in probes.items()}
168
+ if caps:
169
+ merge_capabilities(d, caps, "probe", note="stored probe for current fingerprint") # type: ignore[arg-type]
170
+ stale = self.store.stale_probe_fingerprints(d.id, d.fingerprint)
171
+ if stale:
172
+ d.raw_metadata["invalidated_probe_fingerprints"] = stale
173
+ for m in self.store.load_measurements(d.id, d.fingerprint):
174
+ d.measurements[m["task"]] = Measurement(**m)
175
+ self.learning.apply(d)
176
+
177
+ _PS_SOURCE = "ollama /api/ps (currently loaded)"
178
+
179
+ def _served_context_memory(self, d: Deployment) -> None:
180
+ """Ollama reports the served context only while a model is loaded. Every observation is recorded
181
+ per deployment fingerprint; a backend that opted in (``remember_served_context``) keeps using the
182
+ last observation after the model unloads instead of the assumed default. A Modelfile ``num_ctx``,
183
+ an operator override or a declared backend default always win."""
184
+ if d.backend_type != "ollama" or not self.store:
185
+ return
186
+ key = f"served_ctx:{d.id}:{d.fingerprint}"
187
+ src = str(d.raw_metadata.get("num_ctx_source") or "")
188
+ if src == self._PS_SOURCE and d.context_length:
189
+ self.store.set_meta(key, f"{d.context_length}|{time.time():.0f}")
190
+ return
191
+ a = self.adapters.get(d.backend_id)
192
+ if not src.startswith("assumed") or a is None or not getattr(a.cfg, "remember_served_context", False):
193
+ return
194
+ raw = self.store.get_meta(key)
195
+ if not raw:
196
+ return
197
+ try:
198
+ ctx_s, at_s = raw.split("|", 1)
199
+ ctx, at = int(ctx_s), float(at_s)
200
+ except ValueError:
201
+ return
202
+ if ctx > 0:
203
+ d.context_length = ctx
204
+ d.raw_metadata["num_ctx_source"] = (
205
+ f"remembered: last observed via ollama /api/ps at {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))} "
206
+ "for this fingerprint (opt-in backends[].remember_served_context; not re-verified while unloaded)"
207
+ )
208
+
209
+ async def refresh_residency(self) -> None:
210
+ """Cheap update of loaded/healthy flags without full discovery."""
211
+ for bid, a in self.adapters.items():
212
+ ok, msg = await a.health()
213
+ loaded = await a.loaded_models() if ok else None
214
+ for d in self.registry.by_backend(bid):
215
+ d.healthy = ok
216
+ d.health_checked_at = time.time()
217
+ d.last_error = "" if ok else msg
218
+ if loaded is None:
219
+ continue # no observation (runtime down or /api/ps failed): keep the previous flags
220
+ d.loaded = d.model in loaded
221
+ if d.loaded:
222
+ d.loaded_observed_at = time.time()
223
+ # The served context is observable only now: pick it up on the cheap residency refresh
224
+ # too (not only on full discovery), unless a Modelfile or the operator fixed it.
225
+ lc = (loaded.get(d.model) or {}).get("context_length")
226
+ src = str(d.raw_metadata.get("num_ctx_source") or "")
227
+ if d.backend_type == "ollama" and isinstance(lc, int) and lc > 0:
228
+ d.raw_metadata["observed_served_context"] = lc
229
+ if src != "modelfile" and not src.startswith("operator"):
230
+ d.context_length = lc
231
+ d.raw_metadata["num_ctx_source"] = self._PS_SOURCE
232
+ self._served_context_memory(d)
233
+ self._reconcile_residency()
234
+
235
+ # ------------------------------------------------------------------ #
236
+ # Alias availability (truthful /v1/models)
237
+ # ------------------------------------------------------------------ #
238
+ def usable_generative(self) -> list[Deployment]:
239
+ return [
240
+ d
241
+ for d in self.registry.all()
242
+ if d.enabled and d.healthy and d.role == "generative"
243
+ and (self.cfg.security.locality_mode == "allow_remote" or d.locality == "local")
244
+ ]
245
+
246
+ def alias_contract(self, name: str) -> dict[str, Any] | None:
247
+ a = self.cfg.aliases.get(name)
248
+ if not a:
249
+ return None
250
+ pool = self.usable_generative()
251
+ if a.deployments:
252
+ pool = [d for d in pool if d.id in a.deployments]
253
+ if a.require_tags:
254
+ pool = [d for d in pool if set(a.require_tags) <= set(d.tags)]
255
+ if a.require_vision:
256
+ pool = [d for d in pool if d.cap("vision") == "supported"]
257
+ if not pool:
258
+ return None
259
+ ctx = [d.context_length for d in pool if d.context_length]
260
+ return {
261
+ "id": name,
262
+ "profile": a.profile,
263
+ "deployments": [d.id for d in pool],
264
+ # Truthful contract: the alias guarantees only what *every* member provides.
265
+ "context_length_min": min(ctx) if ctx else None,
266
+ "context_length_max": max(ctx) if ctx else None,
267
+ "tools": "supported" if all(d.cap("tools") == "supported" for d in pool) else (
268
+ "partial" if any(d.cap("tools") == "supported" for d in pool) else "unsupported"
269
+ ),
270
+ "vision": "supported" if all(d.cap("vision") == "supported" for d in pool) else (
271
+ "partial" if any(d.cap("vision") == "supported" for d in pool) else "unsupported"
272
+ ),
273
+ "json_schema": "supported" if all(d.cap("json_schema") == "supported" for d in pool) else (
274
+ "partial" if any(d.cap("json_schema") == "supported" for d in pool) else "unsupported"
275
+ ),
276
+ "description": a.description,
277
+ }
278
+
279
+ def models_listing(self) -> list[dict[str, Any]]:
280
+ out: list[dict[str, Any]] = []
281
+ now = int(time.time())
282
+ for name in self.cfg.aliases:
283
+ c = self.alias_contract(name)
284
+ if c:
285
+ out.append({"id": name, "object": "model", "created": now, "owned_by": "modelsaar", "modelsaar": c})
286
+ for d in self.registry.all():
287
+ if not (d.enabled and d.healthy):
288
+ continue
289
+ if self.cfg.security.locality_mode == "local_only" and d.locality != "local":
290
+ continue
291
+ out.append(
292
+ {
293
+ "id": d.id,
294
+ "object": "model",
295
+ "created": now,
296
+ "owned_by": d.backend_id,
297
+ "modelsaar": {
298
+ "role": d.role,
299
+ "context_length": d.context_length,
300
+ "tools": d.cap("tools"),
301
+ "vision": d.cap("vision"),
302
+ "json_schema": d.cap("json_schema"),
303
+ "locality": d.locality,
304
+ },
305
+ }
306
+ )
307
+ return out
308
+
309
+ # ------------------------------------------------------------------ #
310
+ # Routing
311
+ # ------------------------------------------------------------------ #
312
+ def resolve_model(self, requested: str) -> tuple[str | None, Deployment | None]:
313
+ """Return (alias_name, explicit_deployment)."""
314
+ if requested in self.cfg.aliases:
315
+ return requested, None
316
+ d = self.registry.get(requested)
317
+ if d:
318
+ return None, d
319
+ # Allow bare model names when unambiguous across backends.
320
+ matches = [x for x in self.registry.all() if x.model == requested]
321
+ if len(matches) == 1:
322
+ return None, matches[0]
323
+ return None, None
324
+
325
+ async def route_chat(self, body: dict[str, Any], headers: dict[str, str], caller_id: str) -> Decision:
326
+ t0 = time.monotonic()
327
+ dec = Decision(config_hash=self.cfg.config_hash, registry_version=self.registry.version)
328
+ dec.requested_model = str(body.get("model", ""))
329
+ dec.stream = bool(body.get("stream"))
330
+ alias_name, explicit = self.resolve_model(dec.requested_model)
331
+ if alias_name is None and explicit is None:
332
+ dec.outcome = "unknown_model"
333
+ dec.reasons.append(f"model {dec.requested_model!r} is neither an alias nor a known deployment")
334
+ dec.remedies.append("GET /v1/models lists the available aliases and deployments")
335
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
336
+ raise NoEligibleDeployment(dec)
337
+ alias = self.cfg.aliases.get(alias_name) if alias_name else None
338
+ dec.alias = alias_name
339
+ dec.explicit = explicit is not None
340
+ hint = body.get("modelsaar") if isinstance(body.get("modelsaar"), dict) else {}
341
+ profile = hint.get("profile") if hint else None
342
+ if profile not in ("quality", "balanced", "fast"):
343
+ profile = alias.profile if alias else self.cfg.routing.default_profile
344
+ dec.profile = profile
345
+
346
+ thinking_possible = any(d.cap("thinking") == "supported" for d in self.registry.all())
347
+ req = analyze_chat(body, self.cfg.routing.token_estimate, thinking_possible)
348
+ request_fields = set(body.keys())
349
+
350
+ # --- hard filters, pass 1: estimates only. No request content leaves the gateway here. ---
351
+ deps = self.registry.all()
352
+
353
+ labels: dict[str, str] = {}
354
+
355
+ def _filter(exact: dict[str, int] | None):
356
+ return filter_deployments(
357
+ deps,
358
+ req,
359
+ self.cfg.security,
360
+ alias=alias,
361
+ explicit_model=explicit.id if explicit else None,
362
+ feasibility=self.admission.feasibility,
363
+ backend_unsupported_fields=lambda d: self.adapters[d.backend_id].unsupported_fields(),
364
+ request_fields=request_fields,
365
+ exact_input_tokens=exact,
366
+ exact_labels=labels,
367
+ )
368
+
369
+ res = _filter(None)
370
+ # Pass 2: tokenizer-based counts, only for deployments that passed every policy and
371
+ # capability filter (eligible, or excluded by the context estimate alone). A deployment
372
+ # that is remote under local_only, disabled, unhealthy or lacks a capability never
373
+ # receives the prompt.
374
+ allowed = [d for d in res.eligible] + [
375
+ d
376
+ for d in deps
377
+ for e in res.exclusions
378
+ if e.deployment_id == d.id and e.reasons and all(r.startswith("effective context ") and "<" in r for r in e.reasons)
379
+ ]
380
+ exact = await self._exact_counts(body, req, allowed, labels)
381
+ if exact:
382
+ dec.requirements_note = "tokenizer counts used: " + ", ".join(
383
+ f"{did}={exact[did]} ({labels.get(did) or 'tokenize:' + did.split('/', 1)[0] + '+template-estimate'})" for did in sorted(exact)
384
+ )
385
+ res = _filter(exact)
386
+ dec.exclusions = res.blockers_summary()
387
+ dec.remedies = sorted({r for e in res.exclusions for r in e.remedies})
388
+
389
+ # --- optional classifier (only refines the task label) ------------
390
+ if res.eligible and self.classifier.should_run(req):
391
+ cdep, why = self._classifier_deployment()
392
+ if cdep is None:
393
+ dec.classifier = {"used": False, "status": "unavailable", "note": why}
394
+ else:
395
+ try:
396
+ reservation = await self.admission.acquire(cdep, timeout=self.cfg.routing.classifier.timeout_s)
397
+ except AdmissionRejected:
398
+ reservation = None
399
+ dec.classifier = {"used": False, "status": "skipped", "note": "classifier deployment at capacity"}
400
+ if reservation is not None:
401
+ out = None
402
+ try:
403
+ out = await self.classifier.classify(self.adapters[cdep.backend_id], cdep, body, req)
404
+ finally:
405
+ if out is not None and out.status == "timeout":
406
+ # The classifier may still be generating: hold its slot as uncertain.
407
+ await reservation.mark_uncertain()
408
+ else:
409
+ await reservation.release()
410
+ dec.classifier = out.as_dict()
411
+ if out.used and out.task and out.confidence is not None and out.confidence >= 0.5:
412
+ req.tasks[out.task] = max(req.tasks.get(out.task, 0.0), round(out.confidence, 2))
413
+ req.primary_task = out.task
414
+ req.signals.append(f"classifier:{out.task}@{out.confidence:.2f}")
415
+ elif self.cfg.routing.classifier.enabled:
416
+ dec.classifier = {"used": False, "status": "skipped", "note": "deterministic classification was not ambiguous"}
417
+ dec.requirements = req.as_dict()
418
+
419
+ if not res.eligible:
420
+ only_admission = [
421
+ e for e in res.exclusions if e.reasons and all(r.startswith(("admission queue", "circuit open")) for r in e.reasons)
422
+ ]
423
+ if only_admission:
424
+ dec.outcome = "admission_rejected"
425
+ dec.reasons.append(
426
+ f"{len(only_admission)} otherwise-eligible deployment(s) are at capacity or circuit-broken; retry shortly"
427
+ )
428
+ else:
429
+ dec.outcome = "no_eligible"
430
+ dec.reasons.append("no deployment satisfies all hard requirements")
431
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
432
+ self._record(dec)
433
+ raise NoEligibleDeployment(dec)
434
+
435
+ # --- affinity ------------------------------------------------------
436
+ affinity_dep: str | None = None
437
+ session_key, source, ignored_hints = self.affinity.extract_session(headers, body)
438
+ if "session_id" in body:
439
+ dec.compat["session_id"] = (
440
+ "consumed as caller-scoped conversation affinity (client-compatibility field; not forwarded to the backend)"
441
+ if source == "body:session_id" else f"present but superseded by {source} (fixed precedence); not forwarded"
442
+ )
443
+ if self.cfg.affinity.mode == "session" and session_key:
444
+ e = self.affinity.get(caller_id, session_key)
445
+ if e:
446
+ affinity_dep = e.deployment_id
447
+ dec.affinity = {"session_source": source, "pinned": e.deployment_id, "status": "found"}
448
+ else:
449
+ dec.affinity = {"session_source": source, "status": "new"}
450
+ else:
451
+ dec.affinity = {"session_source": source, "status": "stateless" if not session_key else "disabled"}
452
+ if ignored_hints:
453
+ dec.affinity["ignored_hints"] = ignored_hints # other sources carried a different id; precedence is fixed
454
+ if self.cfg.affinity.tool_round_trip_affinity and req.is_tool_result_turn and req.outstanding_tool_call_ids:
455
+ e = self.affinity.lookup_tool_round(caller_id, req.outstanding_tool_call_ids)
456
+ if e:
457
+ affinity_dep = e.deployment_id
458
+ dec.affinity["tool_round_trip"] = e.deployment_id
459
+ eligible_ids = {d.id for d in res.eligible}
460
+ if affinity_dep and affinity_dep not in eligible_ids:
461
+ # Hard policy is revalidated every request: a pinned deployment that no longer
462
+ # qualifies is not used; a tool round trip must not be handed to another model.
463
+ if req.is_tool_result_turn and dec.affinity.get("tool_round_trip"):
464
+ dec.outcome = "affinity_broken"
465
+ dec.reasons.append(
466
+ f"tool round trip was started on {affinity_dep}, which is no longer eligible; refusing cross-model handover"
467
+ )
468
+ dec.remedies.append("retry once the original deployment is healthy, or start a new run")
469
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
470
+ self._record(dec)
471
+ raise NoEligibleDeployment(dec)
472
+ dec.affinity["status"] = "pinned_ineligible_rerouted"
473
+ affinity_dep = None
474
+
475
+ # --- rank ----------------------------------------------------------
476
+ weights = getattr(self.cfg.routing.profiles, profile)
477
+ cands = rank(res.eligible, req.primary_task, weights, self.cfg.routing, affinity_dep, tasks=req.tasks)
478
+ # A pinned deployment that is still eligible always wins (continuity beats score).
479
+ if affinity_dep:
480
+ for i, c in enumerate(cands):
481
+ if c.deployment.id == affinity_dep:
482
+ if i != 0:
483
+ cands.insert(0, cands.pop(i))
484
+ c.notes.append("affinity: pinned deployment kept")
485
+ break
486
+ if self.cfg.routing.replica_scheduling == "least_loaded" and not affinity_dep and cands:
487
+ top = cands[0].deployment
488
+ group = [c for c in cands if c.deployment.identity and c.deployment.identity == top.identity and c.deployment.role == top.role]
489
+ if len({c.deployment.backend_id for c in group}) > 1:
490
+ occ = {c.deployment.id: round(self.admission.occupancy(c.deployment), 3) for c in group}
491
+ order = sorted(group, key=lambda c: (occ[c.deployment.id], cands.index(c)))
492
+ dec.scheduling = {"policy": "least_loaded", "replicas": [c.deployment.id for c in order], "occupancy": occ}
493
+ if order[0] is not cands[0]:
494
+ order[0].notes.append(f"replica scheduling: least occupied replica of {top.id} ({occ[order[0].deployment.id]} vs {occ[top.id]})")
495
+ cands.insert(0, cands.pop(cands.index(order[0])))
496
+ for c in cands:
497
+ mv = self.admission.memory_view(c.deployment)
498
+ if mv is not None:
499
+ c.notes.append(f"memory: pool {mv['pool']} ~{mv['estimated_gb']}/{mv['memory_gb']} GB with this deployment (weights-only estimates)")
500
+ if c.deployment.id in mv["unknown"]:
501
+ c.notes.append("memory estimate unknown for this deployment (admitted under unknown_memory_policy=allow)")
502
+ dec.candidates = [c.as_dict() for c in cands]
503
+ chosen = cands[0]
504
+ # Continuity: a request that is tied to the deployment that started the exchange is never
505
+ # handed to another model by failover; it fails and the client decides.
506
+ if req.is_tool_result_turn and dec.affinity.get("tool_round_trip"):
507
+ dec.failover_allowed = False
508
+ dec.failover_note = "tool round trip in progress; cross-model handover refused"
509
+ elif req.needs_continuation:
510
+ dec.failover_allowed = False
511
+ dec.failover_note = "reasoning continuation state present; cross-model handover refused"
512
+ elif affinity_dep and chosen.deployment.id == affinity_dep:
513
+ dec.failover_allowed = False
514
+ dec.failover_note = f"session pinned to {affinity_dep}; failover would break continuity"
515
+ dec.chosen = chosen.deployment.id
516
+ dec.evidence = chosen.evidence.split(' (blend')[0]
517
+ dec.reasons.extend(self._reasons(dec, chosen, len(res.eligible), len(res.exclusions)))
518
+ if dec.scheduling:
519
+ dec.reasons.append(
520
+ f"replica scheduling: {dec.chosen} is the least occupied of {len(dec.scheduling['replicas'])} verified replicas "
521
+ f"(same model identity on different backends); occupancy {dec.scheduling['occupancy']}"
522
+ )
523
+ cas = alias.cascade if alias else None
524
+ if cas and cas.enabled:
525
+ if body.get("stream"):
526
+ dec.cascade = {"not_applied": "streaming request: the first byte commits the response, so no second stage is possible"}
527
+ elif not dec.failover_allowed:
528
+ dec.cascade = {"not_applied": dec.failover_note}
529
+ else:
530
+ first = rank(res.eligible, req.primary_task, getattr(self.cfg.routing.profiles, cas.first_profile), self.cfg.routing, None, tasks=req.tasks)
531
+ stages = [first[0].deployment.id]
532
+ for c in cands: # later stages follow the alias's own ranking
533
+ if c.deployment.id not in stages and len(stages) < cas.max_stages:
534
+ stages.append(c.deployment.id)
535
+ if len(stages) < 2:
536
+ dec.cascade = {"not_applied": "only one eligible deployment"}
537
+ else:
538
+ dec.cascade = {"stages": stages, "escalate_on": list(cas.escalate_on), "trace": []}
539
+ dec.chosen = stages[0]
540
+ dec.reasons.append(
541
+ f"cascade: {stages[0]} answers first (best under the {cas.first_profile} profile); escalation to "
542
+ f"{' then '.join(stages[1:])} only on a structural trigger ({', '.join(cas.escalate_on)})"
543
+ )
544
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
545
+ dec.outcome = "routed"
546
+ # Session pinning happens after a successful dispatch (server calls pin_session), so a
547
+ # pre-commit failover pins the deployment that actually answered.
548
+ if self.cfg.affinity.mode == "session" and session_key:
549
+ dec._session = (session_key, source) # type: ignore[attr-defined] # not serialized
550
+ return dec
551
+
552
+ # ------------------------------------------------------------------ #
553
+ # Embedding contracts
554
+ # ------------------------------------------------------------------ #
555
+ def _embedding_identity_blocker(self, contract, d: Deployment, expected: str) -> str | None: # type: ignore[no-untyped-def]
556
+ """A member is interchangeable only when its identity is known and equal to the alias's
557
+ established identity (see ``_alias_identity``). Single-member aliases with an unknown
558
+ identity are allowed (nothing to interchange) but the decision says so."""
559
+ if len(contract.deployments) == 1 and not expected:
560
+ return None
561
+ if not d.identity:
562
+ return (
563
+ f"identity unknown for {d.id} (a model-name match is not an identity); declare "
564
+ f"backends[].models[].identity to treat it as a replica of alias {contract.alias!r}"
565
+ )
566
+ if expected and d.identity != expected:
567
+ src = "embeddings[].identity" if contract.identity else "the identity established for this alias"
568
+ return (
569
+ f"identity {d.identity[:24]} ({d.identity_source}) differs from {src} {expected[:24]}; "
570
+ "changed identity requires an explicit re-indexing decision"
571
+ )
572
+ return None
573
+
574
+ def _alias_identity(self, contract, members: list[Deployment]) -> tuple[str, str | None]: # type: ignore[no-untyped-def]
575
+ """Establish the alias's identity BEFORE any dispatch, atomically for this process (this
576
+ runs synchronously inside the event loop and the anchor is persisted before returning, so
577
+ two concurrent first requests see the same anchor).
578
+
579
+ Precedence: ``embeddings[].identity`` (declared) > the identity recorded for the alias >
580
+ the verified identity of the first member *in contract order* whose identity is known.
581
+ Members with a different known identity are excluded from then on; members with an unknown
582
+ identity are never interchangeable (single-member aliases excepted). The anchor is a
583
+ configured member's verified identity, never something learned from a response, so the
584
+ first-use race cannot bind two embedding spaces. The second value is a note when the
585
+ configuration was ambiguous (several known identities) and the deterministic choice was made."""
586
+ expected = contract.identity or self._recorded_embedding_identity(contract.alias)
587
+ if expected:
588
+ return expected, None
589
+ by_id = {d.id: d for d in members}
590
+ ordered = [by_id[did] for did in contract.deployments if did in by_id]
591
+ known = [d.identity for d in ordered if d.identity]
592
+ if not known:
593
+ return "", None
594
+ anchor = known[0]
595
+ self._anchor_embedding_identity(contract.alias, anchor)
596
+ note = None
597
+ if len(set(known)) > 1:
598
+ note = (
599
+ f"alias {contract.alias!r} members declare {len(set(known))} different identities; anchored to "
600
+ f"{anchor[:16]} (first member in contract order with a verified identity) before dispatch — "
601
+ "declare embeddings[].identity to make this explicit"
602
+ )
603
+ return anchor, note
604
+
605
+ def _anchor_embedding_identity(self, alias: str, identity: str) -> None:
606
+ self._alias_identity_memory[alias] = identity
607
+ if self.store:
608
+ try:
609
+ self.store.set_meta(f"embedding_identity:{alias}", identity)
610
+ except Exception: # pragma: no cover
611
+ pass
612
+
613
+ def _recorded_embedding_identity(self, alias: str) -> str:
614
+ mem = self._alias_identity_memory.get(alias)
615
+ if mem:
616
+ return mem
617
+ if not self.store:
618
+ return ""
619
+ try:
620
+ v = self.store.get_meta(f"embedding_identity:{alias}") or ""
621
+ except Exception: # pragma: no cover
622
+ return ""
623
+ if v:
624
+ self._alias_identity_memory[alias] = v
625
+ return v
626
+
627
+ def record_embedding_identity(self, alias: str, dep: Deployment) -> None:
628
+ """Kept for callers: the alias identity is established before dispatch (``_alias_identity``),
629
+ so a response can only confirm it. A response from a different identity is impossible because
630
+ such a member is excluded before dispatch."""
631
+ if dep.identity and not self._recorded_embedding_identity(alias):
632
+ self._anchor_embedding_identity(alias, dep.identity)
633
+
634
+ def embedding_request_problem(self, body: dict[str, Any], contract, dep: Deployment) -> str | None: # type: ignore[no-untyped-def]
635
+ """Request options that would change the alias's space are refused, not forwarded."""
636
+ fmt = body.get("encoding_format")
637
+ if fmt not in (None, "float"):
638
+ return f"encoding_format={fmt!r} is not supported by this gateway's embedding contract (only float)"
639
+ dims = body.get("dimensions")
640
+ expected = (contract.dimensions if contract else None) or dep.embedding_dimensions
641
+ if dims is not None and expected and int(dims) != expected:
642
+ return f"dimensions={dims} would change the embedding space of {contract.alias if contract else dep.id} ({expected}-d)"
643
+ return None
644
+
645
+ def pin_session(self, dec: Decision, caller_id: str, dep_id: str) -> None:
646
+ sess = getattr(dec, "_session", None)
647
+ if sess:
648
+ self.affinity.set(caller_id, sess[0], dep_id, sess[1])
649
+
650
+ async def _exact_counts(
651
+ self, body: dict[str, Any], req: Requirements, candidates: list[Deployment], labels: dict[str, str] | None = None
652
+ ) -> dict[str, int]:
653
+ """Ask runtimes with a tokenizer endpoint (vLLM /tokenize) for text token counts, only for
654
+ ``candidates`` (already policy-filtered by the caller) whose estimate is within +-50% of the
655
+ context limit. All calls share one wall-clock deadline (routing.token_estimate.exact_count_deadline_s);
656
+ a deployment that is not counted in time keeps its estimate. The result is the tokenizer count
657
+ of the text plus the gateway's template/message/image overhead estimate, so it is labelled
658
+ ``tokenize:<backend>+template-estimate`` rather than exact. Runtimes that can count the whole
659
+ request with their own chat template (vLLM ``/tokenize`` with messages, llama.cpp
660
+ ``/apply-template`` + ``/tokenize``) are asked for that first; their count replaces the text and
661
+ template estimate entirely (only the per-image allowance is added) and is labelled as exact in
662
+ ``labels``."""
663
+ if not req.tokens or not candidates:
664
+ return {}
665
+
666
+ text: str | None = None
667
+ out: dict[str, int] = {}
668
+ deadline = time.monotonic() + self.cfg.routing.token_estimate.exact_count_deadline_s
669
+ for d in candidates:
670
+ if not (d.enabled and d.healthy and d.role == "generative" and d.context_length):
671
+ continue
672
+ est_total = req.tokens.input_estimate + req.tokens.output_allowance + (
673
+ req.tokens.reasoning_allowance if d.cap("thinking") == "supported" else 0
674
+ )
675
+ if not (0.5 * d.context_length <= est_total <= 1.5 * d.context_length):
676
+ continue
677
+ adapter = self.adapters.get(d.backend_id)
678
+ if adapter is None:
679
+ continue
680
+ remaining = deadline - time.monotonic()
681
+ if remaining <= 0:
682
+ break
683
+ if adapter.tokenize_chat.__func__ is not BaseAdapter.tokenize_chat: # type: ignore[attr-defined]
684
+ try:
685
+ got = await asyncio.wait_for(adapter.tokenize_chat(d, body), timeout=remaining)
686
+ except Exception: # noqa: BLE001 - counting is best effort; the estimate stands
687
+ got = None
688
+ if got and got[0] > 0:
689
+ out[d.id] = got[0] + req.tokens.images * self.cfg.routing.token_estimate.image_tokens
690
+ if labels is not None:
691
+ labels[d.id] = got[1] + (" + image allowance" if req.tokens.images else "")
692
+ continue
693
+ remaining = deadline - time.monotonic()
694
+ if remaining <= 0:
695
+ break
696
+ if adapter.tokenize.__func__ is BaseAdapter.tokenize: # type: ignore[attr-defined]
697
+ continue
698
+ if text is None:
699
+ text = self._countable_text(body)
700
+ try:
701
+ n = await asyncio.wait_for(adapter.tokenize(d, text), timeout=remaining)
702
+ except Exception: # noqa: BLE001 - counting is best effort; the estimate stands
703
+ n = None
704
+ if isinstance(n, int) and n > 0:
705
+ # Keep the per-message/template/image overheads on top of the tokenizer's text count.
706
+ overhead = req.tokens.input_estimate - math.ceil(len(text) / self.cfg.routing.token_estimate.chars_per_token)
707
+ out[d.id] = n + max(0, overhead)
708
+ return out
709
+
710
+ @staticmethod
711
+ def _countable_text(body: dict[str, Any]) -> str:
712
+ """Everything in the request that reaches the model as text: message content, reasoning
713
+ content, tool calls, tool definitions and the response_format schema."""
714
+ from .tokens import _text_of
715
+
716
+ parts: list[str] = []
717
+ for m in body.get("messages") or []:
718
+ if isinstance(m, dict):
719
+ t, _ = _text_of(m.get("content"))
720
+ parts.append(t)
721
+ if isinstance(m.get("reasoning_content"), str):
722
+ parts.append(m["reasoning_content"])
723
+ if m.get("tool_calls"):
724
+ parts.append(json.dumps(m["tool_calls"]))
725
+ for t in body.get("tools") or []:
726
+ parts.append(json.dumps(t))
727
+ if isinstance(body.get("response_format"), dict):
728
+ parts.append(json.dumps(body["response_format"]))
729
+ return "\n".join(parts)
730
+
731
+ def _classifier_deployment(self) -> tuple[Deployment | None, str]:
732
+ """The classifier receives an excerpt of the user's message, so it must be a local
733
+ deployment unless the operator opted in twice: routing.classifier.allow_remote AND
734
+ security.locality_mode=allow_remote."""
735
+ c = self.cfg.routing.classifier
736
+ d = self.registry.get(f"{c.backend}/{c.model}")
737
+ if d is None:
738
+ return None, "configured classifier deployment not found"
739
+ if not (d.healthy and d.enabled):
740
+ return None, "configured classifier deployment is disabled or unhealthy"
741
+ if c.mode == "decision" and d.role != "decision":
742
+ return None, (
743
+ f"classifier mode 'decision' needs a decision-model deployment (role=decision); {d.id} has role {d.role}"
744
+ )
745
+ if c.mode == "chat" and d.role != "generative":
746
+ return None, (
747
+ f"classifier mode 'chat' needs a generative deployment; {d.id} has role {d.role}"
748
+ + (" (set routing.classifier.mode: decision for a decision model)" if d.role == "decision" else "")
749
+ )
750
+ if d.locality != "local" and not (c.allow_remote and self.cfg.security.locality_mode == "allow_remote"):
751
+ return None, (
752
+ f"classifier deployment {d.id} is not local ({d.locality_evidence[:60]}); message excerpts stay on the host"
753
+ " unless routing.classifier.allow_remote and security.locality_mode=allow_remote are both set"
754
+ )
755
+ return d, ""
756
+
757
+ def _reasons(self, dec: Decision, chosen, n_eligible: int, n_excluded: int) -> list[str]:
758
+ r = []
759
+ req = dec.requirements
760
+ needs = []
761
+ if req.get("needs_tools"):
762
+ needs.append("tool support")
763
+ if req.get("needs_vision"):
764
+ needs.append("image input")
765
+ if req.get("needs_json_schema"):
766
+ needs.append("strict JSON schema")
767
+ if req.get("needs_continuation"):
768
+ needs.append("reasoning continuation")
769
+ r.append(
770
+ f"task={req.get('primary_task')} ({'ambiguous' if req.get('ambiguous') else 'clear'}); "
771
+ f"required: {', '.join(needs) if needs else 'no special capabilities'}; "
772
+ f"context need ~{(req.get('tokens') or {}).get('total')} tokens"
773
+ )
774
+ if n_excluded:
775
+ r.append(f"{n_excluded} deployment(s) excluded by hard filters; {n_eligible} eligible")
776
+ if n_eligible == 1:
777
+ r.append("single eligible deployment; ranking skipped (minimal overhead)")
778
+ else:
779
+ r.append(
780
+ f"{chosen.deployment.id} ranked first on profile {dec.profile}: quality {chosen.quality:.2f} "
781
+ f"({chosen.evidence}), latency cost {chosen.latency_cost:.2f}, "
782
+ f"{'resident' if chosen.deployment.loaded else 'not resident'}"
783
+ )
784
+ if chosen.evidence == "uncalibrated":
785
+ r.append("evidence level: UNCALIBRATED prior - run `modelsaar eval` to measure this deployment")
786
+ return r
787
+
788
+ def _record(self, dec: Decision) -> None:
789
+ if self.store and self.cfg.observability.decision_log:
790
+ try:
791
+ self.store.save_decision(dec.request_id, dec.as_dict(), self.cfg.observability.retention_days)
792
+ except Exception as e: # pragma: no cover
793
+ log.warning("decision log write failed: %s", e)
794
+
795
+ def record(self, dec: Decision) -> None:
796
+ self._record(dec)
797
+ if self.cfg.learning.enabled and dec.chosen and dec.endpoint in ("chat", "responses", "messages"):
798
+ from ..learning import STRUCTURAL_FAILURES
799
+
800
+ if dec.outcome in STRUCTURAL_FAILURES:
801
+ dep = self.registry.get(dec.chosen)
802
+ if dep is not None:
803
+ self.learning.record(dec.request_id, dep, str(dec.requirements.get("primary_task") or "conversation"), False, "structural_failure")
804
+
805
+ # ------------------------------------------------------------------ #
806
+ async def route_embeddings(self, body: dict[str, Any], caller_id: str) -> Decision:
807
+ t0 = time.monotonic()
808
+ dec = Decision(config_hash=self.cfg.config_hash, registry_version=self.registry.version, endpoint="embeddings")
809
+ dec.requested_model = str(body.get("model", ""))
810
+ req = Requirements(role="embedding")
811
+ contract = next((c for c in self.cfg.embeddings if c.alias == dec.requested_model), None)
812
+ candidates: list[Deployment] = []
813
+ if contract:
814
+ dec.alias = contract.alias
815
+ for did in contract.deployments:
816
+ d = self.registry.get(did)
817
+ if d:
818
+ candidates.append(d)
819
+ else:
820
+ dec.exclusions[did] = ["deployment not discovered"]
821
+ else:
822
+ _, explicit = self.resolve_model(dec.requested_model)
823
+ if explicit:
824
+ candidates = [explicit]
825
+ dec.explicit = True
826
+ if not candidates and contract:
827
+ dec.outcome = "no_eligible"
828
+ dec.reasons.append(
829
+ f"embedding contract {contract.alias!r} references deployments that are not discovered; "
830
+ "fallback to a different model is refused"
831
+ )
832
+ dec.remedies.append("restore the contract's model or run an explicit re-indexing migration")
833
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
834
+ self._record(dec)
835
+ raise NoEligibleDeployment(dec)
836
+ if not candidates:
837
+ dec.outcome = "unknown_model"
838
+ dec.reasons.append(f"embedding model/alias {dec.requested_model!r} not found")
839
+ dec.remedies.append("declare an embeddings contract in config or use a discovered embedding deployment id")
840
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
841
+ raise NoEligibleDeployment(dec)
842
+ res = filter_deployments(candidates, req, self.cfg.security, feasibility=self.admission.feasibility)
843
+ dec.exclusions.update(res.blockers_summary())
844
+ if contract and contract.dimensions:
845
+ keep = []
846
+ for d in res.eligible:
847
+ if d.embedding_dimensions and d.embedding_dimensions != contract.dimensions:
848
+ dec.exclusions[d.id] = [
849
+ f"embedding dimensions {d.embedding_dimensions} differ from contract {contract.dimensions}"
850
+ ]
851
+ else:
852
+ keep.append(d)
853
+ res.eligible = keep
854
+ if contract:
855
+ expected, note = self._alias_identity(contract, candidates)
856
+ if note:
857
+ dec.reasons.append(note)
858
+ dec.remedies.append("set embeddings[].identity to the verified identity the index was built with")
859
+ keep = []
860
+ for d in res.eligible:
861
+ why = self._embedding_identity_blocker(contract, d, expected)
862
+ if why:
863
+ dec.exclusions[d.id] = [why]
864
+ if "re-index" not in " ".join(dec.remedies):
865
+ dec.remedies.append(
866
+ "members of an embeddings alias must be one verified identity (shared digest or a declared "
867
+ "backends[].models[].identity); after changing the model, re-index and set embeddings[].identity"
868
+ )
869
+ else:
870
+ keep.append(d)
871
+ res.eligible = keep
872
+ if not res.eligible:
873
+ dec.outcome = "no_eligible"
874
+ dec.reasons.append("no deployment satisfies the embedding contract; fallback to an incompatible model is refused")
875
+ dec.remedies.append("restore the contract's model or run an explicit re-indexing migration")
876
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
877
+ self._record(dec)
878
+ raise NoEligibleDeployment(dec)
879
+ # Prefer resident deployment among contract members (all are the same model revision by contract).
880
+ res.eligible.sort(key=lambda d: (not d.loaded, d.id))
881
+ dec.chosen = res.eligible[0].id
882
+ dec.evidence = "contract"
883
+ dec.reasons.append(
884
+ f"embedding contract {'alias ' + contract.alias if contract else 'explicit deployment'}; "
885
+ f"{dec.chosen} selected ({'resident' if res.eligible[0].loaded else 'not resident'})"
886
+ )
887
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
888
+ dec.outcome = "routed"
889
+ return dec
890
+
891
+ # ------------------------------------------------------------------ #
892
+ def route_role(self, role: str, endpoint: str, requested: str, chat_body: dict[str, Any], needs_vision: bool, signal: str) -> Decision:
893
+ """Choose a special-purpose deployment (``guardrail`` / ``ocr``) for a pipeline endpoint: an explicit
894
+ deployment id with that role, or ``auto`` -> every deployment of the role that passes the hard
895
+ filters (enabled, healthy, locality, memory feasibility, effective context for ``chat_body``, vision
896
+ when images are sent), resident first, then by id. Chat aliases are not valid here and a chat
897
+ deployment is never substituted: role mismatch is a hard exclusion."""
898
+ t0 = time.monotonic()
899
+ dec = Decision(config_hash=self.cfg.config_hash, registry_version=self.registry.version, endpoint=endpoint)
900
+ dec.requested_model = requested
901
+ req = Requirements(role=role, needs_vision=needs_vision)
902
+ req.tokens = estimate_chat_tokens(chat_body, self.cfg.routing.token_estimate, False)
903
+ req.signals.append(signal)
904
+
905
+ def fail(outcome: str, reason: str, remedy: str, record: bool = True) -> NoEligibleDeployment:
906
+ dec.outcome = outcome
907
+ dec.reasons.append(reason)
908
+ dec.remedies.append(remedy)
909
+ dec.requirements = req.as_dict()
910
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
911
+ if record:
912
+ self._record(dec)
913
+ return NoEligibleDeployment(dec)
914
+
915
+ if requested == "auto":
916
+ candidates = [d for d in self.registry.all() if d.role == role]
917
+ if not candidates:
918
+ raise fail(
919
+ "no_eligible",
920
+ f"no deployment with role {role} is registered",
921
+ f"install a {role} model the catalogue recognises, or set deployments[].role: {role} for the model that serves this purpose",
922
+ )
923
+ else:
924
+ alias_name, explicit = self.resolve_model(requested)
925
+ if explicit is None:
926
+ raise fail(
927
+ "unknown_model",
928
+ f"model {requested!r} is not a known deployment" + (f" (chat aliases are not valid here; use 'auto' or a {role} deployment id)" if alias_name else ""),
929
+ f"use 'auto' or the id of a deployment with role {role}",
930
+ record=False,
931
+ )
932
+ candidates = [explicit]
933
+ dec.explicit = True
934
+ res = filter_deployments(candidates, req, self.cfg.security, feasibility=self.admission.feasibility)
935
+ if needs_vision:
936
+ keep = []
937
+ for d in res.eligible:
938
+ if d.cap("vision") == "supported":
939
+ keep.append(d)
940
+ else:
941
+ dec.exclusions[d.id] = [f"request carries an image; capability vision is {d.cap('vision')} for this deployment"]
942
+ res.eligible = keep
943
+ dec.exclusions.update(res.blockers_summary())
944
+ dec.remedies.extend(sorted({r for e in res.exclusions for r in e.remedies}))
945
+ dec.requirements = req.as_dict()
946
+ if not res.eligible:
947
+ raise fail("no_eligible", f"no {role} deployment satisfies all hard requirements", f"see blockers; a chat model is never substituted for a {role} model")
948
+ res.eligible.sort(key=lambda d: (not d.loaded, d.id))
949
+ chosen = res.eligible[0]
950
+ dec.chosen = chosen.id
951
+ dec.candidates = [{"deployment": d.id, "loaded": d.loaded} for d in res.eligible]
952
+ dec.evidence = "explicit" if dec.explicit else "deterministic"
953
+ dec.reasons.append(
954
+ f"{role} deployment {'requested explicitly' if dec.explicit else 'selected among ' + str(len(res.eligible)) + ' eligible'}; "
955
+ f"{chosen.id} ({'resident' if chosen.loaded else 'not resident'})"
956
+ )
957
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
958
+ dec.outcome = "routed"
959
+ return dec
960
+
961
+ async def route_decisions(self, body: dict[str, Any], caller_id: str, needs_vision: bool = False) -> Decision:
962
+ """Choose the decision model for ``POST /v1/decisions``: an explicit deployment id (or bare model
963
+ name) with ``role == "decision"``, or ``auto`` → every decision-role deployment that passes the
964
+ hard filters (enabled, healthy, locality policy, memory feasibility, vision when images are sent),
965
+ resident ones first, then by id. No quality scoring applies: decision models are not measured by
966
+ the evaluation harness, so the choice is deterministic and fully explained in the record."""
967
+ t0 = time.monotonic()
968
+ dec = Decision(config_hash=self.cfg.config_hash, registry_version=self.registry.version, endpoint="decisions")
969
+ dec.requested_model = str(body.get("model", ""))
970
+ req = Requirements(role="decision", needs_vision=needs_vision)
971
+ nq = len(body.get("questions") or {}) if isinstance(body.get("questions"), dict) else 0
972
+ req.signals.append(f"decisions:{nq} question(s){' + images' if needs_vision else ''}")
973
+ candidates: list[Deployment]
974
+ if dec.requested_model == "auto":
975
+ candidates = [d for d in self.registry.all() if d.role == "decision"]
976
+ if not candidates:
977
+ dec.outcome = "no_eligible"
978
+ dec.reasons.append("no decision-model deployment is discovered (a model whose capabilities list 'decision')")
979
+ dec.remedies.append("pull a decision model (e.g. Ollama nimble, clef or laya) and refresh discovery")
980
+ dec.requirements = req.as_dict()
981
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
982
+ self._record(dec)
983
+ raise NoEligibleDeployment(dec)
984
+ else:
985
+ alias_name, explicit = self.resolve_model(dec.requested_model)
986
+ if explicit is None:
987
+ dec.outcome = "unknown_model"
988
+ dec.reasons.append(
989
+ f"model {dec.requested_model!r} is not a known deployment"
990
+ + (" (chat aliases are not valid here; use 'auto' or a decision deployment id)" if alias_name else "")
991
+ )
992
+ dec.remedies.append("use 'auto' or the id of a discovered decision-model deployment (role decision)")
993
+ dec.requirements = req.as_dict()
994
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
995
+ raise NoEligibleDeployment(dec)
996
+ candidates = [explicit]
997
+ dec.explicit = True
998
+ res = filter_deployments(candidates, req, self.cfg.security, feasibility=self.admission.feasibility)
999
+ if needs_vision:
1000
+ keep = []
1001
+ for d in res.eligible:
1002
+ if d.cap("vision") == "supported":
1003
+ keep.append(d)
1004
+ else:
1005
+ dec.exclusions[d.id] = [f"request carries images; capability vision is {d.cap('vision')} for this decision model"]
1006
+ res.eligible = keep
1007
+ dec.exclusions.update(res.blockers_summary())
1008
+ dec.remedies.extend(sorted({r for e in res.exclusions for r in e.remedies}))
1009
+ dec.requirements = req.as_dict()
1010
+ if not res.eligible:
1011
+ dec.outcome = "no_eligible"
1012
+ dec.reasons.append("no decision-model deployment satisfies all hard requirements")
1013
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
1014
+ self._record(dec)
1015
+ raise NoEligibleDeployment(dec)
1016
+ res.eligible.sort(key=lambda d: (not d.loaded, d.id))
1017
+ chosen = res.eligible[0]
1018
+ dec.chosen = chosen.id
1019
+ dec.evidence = "explicit" if dec.explicit else "deterministic"
1020
+ dec.reasons.append(
1021
+ f"decision model {'requested explicitly' if dec.explicit else 'selected among ' + str(len(res.eligible)) + ' eligible decision deployment(s)'}; "
1022
+ f"{chosen.id} ({'resident' if chosen.loaded else 'not resident'})"
1023
+ )
1024
+ dec.overhead_ms = (time.monotonic() - t0) * 1000
1025
+ dec.outcome = "routed"
1026
+ return dec