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,359 @@
1
+ """Admission control: bounded queues, shared-resource concurrency, reservations,
2
+ uncertain-occupancy holds, and per-backend circuit breakers.
3
+
4
+ Feasibility checks are non-reserving. A reservation is acquired atomically
5
+ (backend slot + pool slot) immediately before dispatch and released when the
6
+ upstream call completes. If completion cannot be confirmed (client
7
+ disconnected mid-stream), the reservation is kept as *uncertain* for a bounded
8
+ hold period, because an HTTP disconnect does not prove the backend stopped.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import time
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass, field
17
+
18
+ from ..config import AdmissionConfig, BackendConfig, ResourcePool
19
+ from ..registry import Deployment
20
+
21
+
22
+ @dataclass
23
+ class _Slot:
24
+ limit: int
25
+ max_queue: int
26
+ queue_timeout_s: float
27
+ active: int = 0
28
+ waiting: int = 0
29
+ uncertain: int = 0
30
+ cond: asyncio.Condition = field(default_factory=asyncio.Condition)
31
+ # Memory budget (pools only). holders counts active+uncertain reservations per deployment so
32
+ # a deployment's weights are counted once however many requests it serves concurrently.
33
+ memory_gb: float | None = None
34
+ memory_margin_gb: float = 0.0
35
+ unknown_memory_policy: str = "allow"
36
+ holders: dict[str, int] = field(default_factory=dict)
37
+ # Weights assumed resident after a dispatch completed: a request slot is released when the
38
+ # response ends, but the model's weights stay loaded in the runtime. The assumption is kept
39
+ # (conservatively counted against the budget) until a residency observation reconciles it or
40
+ # the pool's assumed_residency_ttl_s expires. dep_id -> monotonic time of the last completion.
41
+ assumed_resident: dict[str, float] = field(default_factory=dict)
42
+ assumed_residency_ttl_s: float | None = None
43
+
44
+ @property
45
+ def used(self) -> int:
46
+ return self.active + self.uncertain
47
+
48
+ def hold(self, dep_id: str) -> None:
49
+ self.holders[dep_id] = self.holders.get(dep_id, 0) + 1
50
+
51
+ def unhold(self, dep_id: str, assume_resident: bool = True) -> None:
52
+ n = self.holders.get(dep_id, 0) - 1
53
+ if n <= 0:
54
+ self.holders.pop(dep_id, None)
55
+ if self.memory_gb is not None and assume_resident:
56
+ # The slot is free; the weights are not. Keep them counted until reconciled.
57
+ self.assumed_resident[dep_id] = time.monotonic()
58
+ else:
59
+ self.holders[dep_id] = n
60
+
61
+ def assumed(self) -> set[str]:
62
+ """Deployments whose weights are assumed resident (TTL applied)."""
63
+ if self.assumed_residency_ttl_s is not None:
64
+ cutoff = time.monotonic() - self.assumed_residency_ttl_s
65
+ for k in [k for k, t in self.assumed_resident.items() if t < cutoff]:
66
+ self.assumed_resident.pop(k, None)
67
+ return set(self.assumed_resident)
68
+
69
+
70
+ @dataclass
71
+ class Circuit:
72
+ threshold: int
73
+ cooldown_s: float
74
+ failures: int = 0
75
+ opened_at: float | None = None
76
+
77
+ def is_open(self) -> bool:
78
+ if self.opened_at is None:
79
+ return False
80
+ if time.time() - self.opened_at >= self.cooldown_s:
81
+ return False # half-open: allow a probe request
82
+ return True
83
+
84
+ def record_failure(self) -> None:
85
+ self.failures += 1
86
+ if self.failures >= self.threshold:
87
+ self.opened_at = time.time()
88
+
89
+ def record_success(self) -> None:
90
+ self.failures = 0
91
+ self.opened_at = None
92
+
93
+
94
+ class Reservation:
95
+ def __init__(self, admission: Admission, slots: list[_Slot], dep_id: str) -> None:
96
+ self._adm = admission
97
+ self._slots = slots
98
+ self.dep_id = dep_id
99
+ self._released = False
100
+ self.acquired_at = time.monotonic()
101
+
102
+ async def release(self, *, submitted: bool = True) -> None:
103
+ """Free the slot. ``submitted=False`` means no work ever reached the runtime (the connection
104
+ was refused before the request was sent), so nothing could have loaded: the weights are not
105
+ assumed resident. Any outcome where loading or computation may have started keeps the
106
+ conservative assumption."""
107
+ if self._released:
108
+ return
109
+ self._released = True
110
+ for s in self._slots:
111
+ async with s.cond:
112
+ s.active = max(0, s.active - 1)
113
+ s.unhold(self.dep_id, assume_resident=submitted)
114
+ s.cond.notify_all()
115
+
116
+ async def mark_uncertain(self) -> None:
117
+ """Convert this reservation into an uncertain-occupancy hold for a bounded time."""
118
+ if self._released:
119
+ return
120
+ self._released = True
121
+ hold = self._adm.cfg.uncertain_hold_s
122
+ for s in self._slots:
123
+ async with s.cond:
124
+ s.active = max(0, s.active - 1)
125
+ s.uncertain += 1
126
+ self._adm.uncertain_events += 1
127
+
128
+ async def _expire() -> None:
129
+ await asyncio.sleep(hold)
130
+ for s in self._slots:
131
+ async with s.cond:
132
+ s.uncertain = max(0, s.uncertain - 1)
133
+ s.unhold(self.dep_id) # the hold counted the weights until now
134
+ s.cond.notify_all()
135
+
136
+ task = asyncio.create_task(_expire())
137
+ self._adm._tasks.add(task)
138
+ task.add_done_callback(self._adm._tasks.discard)
139
+
140
+
141
+ class Admission:
142
+ def __init__(self, cfg: AdmissionConfig, pools: list[ResourcePool], backends: list[BackendConfig]) -> None:
143
+ self.cfg = cfg
144
+ self._pools: dict[str, _Slot] = {
145
+ p.id: _Slot(
146
+ p.max_concurrent,
147
+ p.max_queue,
148
+ p.queue_timeout_s,
149
+ memory_gb=p.memory_gb,
150
+ memory_margin_gb=p.memory_margin_gb,
151
+ unknown_memory_policy=p.unknown_memory_policy,
152
+ assumed_residency_ttl_s=p.assumed_residency_ttl_s,
153
+ )
154
+ for p in pools
155
+ }
156
+ # Set by the router: deployments sharing a pool (for resident-weight accounting).
157
+ self.pool_members: Callable[[str], list[Deployment]] = lambda pool_id: []
158
+ self._backends: dict[str, _Slot] = {
159
+ b.id: _Slot(b.max_concurrent, cfg.max_queue, cfg.queue_timeout_s) for b in backends
160
+ }
161
+ self._circuits: dict[str, Circuit] = {
162
+ b.id: Circuit(b.circuit_failure_threshold, b.circuit_cooldown_s) for b in backends
163
+ }
164
+ self._tasks: set[asyncio.Task] = set()
165
+ # Deployments the lifecycle manager is unloading right now: nothing new is admitted for them.
166
+ self.draining: set[str] = set()
167
+ self.uncertain_events = 0
168
+ self.rejected_queue_full = 0
169
+ self.queue_timeouts = 0
170
+
171
+ def _slots_for(self, dep: Deployment) -> list[_Slot]:
172
+ slots: list[_Slot] = []
173
+ b = self._backends.get(dep.backend_id)
174
+ if b:
175
+ slots.append(b)
176
+ if dep.resource_pool and dep.resource_pool in self._pools:
177
+ slots.append(self._pools[dep.resource_pool])
178
+ return slots
179
+
180
+ def circuit(self, backend_id: str) -> Circuit | None:
181
+ return self._circuits.get(backend_id)
182
+
183
+ def holders(self, dep: Deployment) -> int:
184
+ """Active plus uncertain reservations currently held for ``dep`` (its implicit leases)."""
185
+ return max((s.holders.get(dep.id, 0) for s in self._slots_for(dep)), default=0)
186
+
187
+ def occupancy(self, dep: Deployment) -> float:
188
+ """How busy the backend and pool behind ``dep`` are right now: the largest (in-flight + uncertain +
189
+ queued) / limit over its slots. 0 = idle, >= 1 = a new request would queue."""
190
+ return max(((s.used + s.waiting) / max(1, s.limit) for s in self._slots_for(dep)), default=0.0)
191
+
192
+ def forget_resident(self, dep: Deployment) -> None:
193
+ """An unload was confirmed by the runtime: the weights are no longer assumed resident."""
194
+ for s in self._slots_for(dep):
195
+ s.assumed_resident.pop(dep.id, None)
196
+
197
+ def feasibility(self, dep: Deployment) -> str | None:
198
+ """Non-reserving check; returns a blocker string or None."""
199
+ if dep.id in self.draining:
200
+ return "deployment is being unloaded by the lifecycle manager"
201
+ c = self._circuits.get(dep.backend_id)
202
+ if c and c.is_open():
203
+ return f"circuit open for backend {dep.backend_id} after {c.failures} consecutive failures"
204
+ for s in self._slots_for(dep):
205
+ if s.used >= s.limit and s.waiting >= s.max_queue:
206
+ return "admission queue full for this deployment's resource pool/backend"
207
+ return self.memory_blocker(dep)
208
+
209
+ # ---------------------------------------------------------------- #
210
+ # Memory budget
211
+ # ---------------------------------------------------------------- #
212
+ def memory_view(self, dep: Deployment) -> dict | None:
213
+ """What the pool budget would look like with ``dep`` dispatched. None when the pool has no
214
+ memory budget. Estimates are weights-only (provenance on each deployment); KV/workspace
215
+ and runtime overhead are covered only by memory_margin_gb. Unified memory is counted once
216
+ per pool; a deployment is counted once however many requests it serves."""
217
+ pool_id = dep.resource_pool
218
+ s = self._pools.get(pool_id) if pool_id else None
219
+ if s is None or s.memory_gb is None:
220
+ return None
221
+ members = {d.id: d for d in self.pool_members(pool_id)}
222
+ members.setdefault(dep.id, dep)
223
+ # Counted once each: active/uncertain holders, the candidate, members observed loaded, and
224
+ # members assumed resident since their last completion (not yet reconciled by an observation).
225
+ counted: set[str] = set(s.holders) | {dep.id} | {d.id for d in members.values() if d.loaded} | (s.assumed() & set(members))
226
+ total = 0.0
227
+ unknown: list[str] = []
228
+ for did in sorted(counted):
229
+ d = members.get(did)
230
+ est = d.memory_gb_estimate if d else None
231
+ if est is None:
232
+ unknown.append(did)
233
+ else:
234
+ total += est
235
+ return {
236
+ "pool": pool_id,
237
+ "memory_gb": s.memory_gb,
238
+ "margin_gb": s.memory_margin_gb,
239
+ "counted": sorted(counted),
240
+ "assumed_resident": sorted(s.assumed() & set(members)),
241
+ "estimated_gb": round(total, 2),
242
+ "unknown": unknown,
243
+ "policy_unknown": s.unknown_memory_policy,
244
+ # With unknown_memory_policy=reject an unknown member anywhere in the count blocks admission:
245
+ # a resident or reserved model of unknown size makes the whole budget unverifiable.
246
+ "fits": total + s.memory_margin_gb <= s.memory_gb and not (unknown and s.unknown_memory_policy == "reject"),
247
+ }
248
+
249
+ def memory_blocker(self, dep: Deployment) -> str | None:
250
+ v = self.memory_view(dep)
251
+ if v is None:
252
+ return None
253
+ if dep.memory_gb_estimate is None and v["policy_unknown"] == "reject":
254
+ return (
255
+ f"memory estimate unknown for {dep.id} and pool {v['pool']} has unknown_memory_policy=reject "
256
+ f"(declare memory_gb_estimate under backends[].models or deployments[] overrides)"
257
+ )
258
+ if v["unknown"] and v["policy_unknown"] == "reject":
259
+ return (
260
+ f"memory estimate unknown for {', '.join(v['unknown'])} already counted in pool {v['pool']} "
261
+ f"(resident or reserved) and the pool has unknown_memory_policy=reject; the budget cannot be verified "
262
+ "(declare memory_gb_estimate for every member or unload the unknown model)"
263
+ )
264
+ if not v["fits"]:
265
+ return (
266
+ f"memory budget: pool {v['pool']} memory_gb={v['memory_gb']} < resident+reserved estimate "
267
+ f"{v['estimated_gb']} GB + margin {v['margin_gb']} GB (counted: {', '.join(v['counted'])}; "
268
+ f"{dep.id} estimate {dep.memory_gb_estimate} GB from {dep.memory_estimate_provenance or 'unknown'}"
269
+ f"{'; unknown: ' + ', '.join(v['unknown']) if v['unknown'] else ''})"
270
+ )
271
+ return None
272
+
273
+ def reconcile_residency(self, deployments: list[Deployment], observed_backends: set[str]) -> None:
274
+ """Apply a residency observation. For every backend in ``observed_backends`` the registry's
275
+ ``loaded`` flags are the truth, so assumptions about its deployments are dropped (a model the
276
+ runtime reports loaded is counted through ``loaded``; one it reports unloaded is no longer
277
+ counted). Deployments of backends that cannot report residency keep their assumption."""
278
+ by_id = {d.id: d for d in deployments}
279
+ for s in self._pools.values():
280
+ for did in list(s.assumed_resident):
281
+ d = by_id.get(did)
282
+ if d is None or d.backend_id in observed_backends:
283
+ s.assumed_resident.pop(did, None)
284
+
285
+ async def acquire(self, dep: Deployment, timeout: float | None = None) -> Reservation:
286
+ slots = self._slots_for(dep)
287
+ acquired: list[_Slot] = []
288
+ try:
289
+ for s in slots:
290
+ t = timeout if timeout is not None else s.queue_timeout_s
291
+ await self._acquire_one(s, t)
292
+ acquired.append(s)
293
+ # Atomic with the slot: the memory check runs after the pool slot is held, so two
294
+ # concurrent admissions cannot both pass against the same free budget.
295
+ # Checked in the same step as the hold below (no await in between): an unload that has started
296
+ # draining this deployment can never be overtaken by a dispatch.
297
+ if dep.id in self.draining:
298
+ raise AdmissionRejected("deployment is being unloaded by the lifecycle manager", status=503)
299
+ why = self.memory_blocker(dep)
300
+ if why:
301
+ raise AdmissionRejected(why, status=503)
302
+ for s in acquired:
303
+ s.hold(dep.id)
304
+ except BaseException:
305
+ for s in acquired:
306
+ async with s.cond:
307
+ s.active = max(0, s.active - 1)
308
+ s.cond.notify_all()
309
+ raise
310
+ return Reservation(self, acquired, dep.id)
311
+
312
+ async def _acquire_one(self, s: _Slot, timeout: float) -> None:
313
+ async with s.cond:
314
+ if s.used >= s.limit:
315
+ if s.waiting >= s.max_queue:
316
+ self.rejected_queue_full += 1
317
+ raise AdmissionRejected("admission queue full", status=429)
318
+ s.waiting += 1
319
+ try:
320
+ deadline = time.monotonic() + timeout
321
+ while s.used >= s.limit:
322
+ remaining = deadline - time.monotonic()
323
+ if remaining <= 0:
324
+ self.queue_timeouts += 1
325
+ raise AdmissionRejected("admission queue timeout", status=503)
326
+ try:
327
+ await asyncio.wait_for(s.cond.wait(), timeout=remaining)
328
+ except asyncio.TimeoutError:
329
+ self.queue_timeouts += 1
330
+ raise AdmissionRejected("admission queue timeout", status=503)
331
+ finally:
332
+ s.waiting -= 1
333
+ s.active += 1
334
+
335
+ def stats(self) -> dict[str, dict[str, int]]:
336
+ out: dict[str, dict[str, int]] = {}
337
+ for k, s in {**{f"backend:{k}": v for k, v in self._backends.items()}, **{f"pool:{k}": v for k, v in self._pools.items()}}.items():
338
+ out[k] = {"limit": s.limit, "active": s.active, "waiting": s.waiting, "uncertain": s.uncertain}
339
+ if k.startswith("pool:") and s.memory_gb is not None:
340
+ members = {d.id: d for d in self.pool_members(k[5:])}
341
+ reserved = sum((members[d].memory_gb_estimate or 0.0) for d in s.holders if d in members)
342
+ out[k].update(
343
+ {
344
+ "memory_gb": s.memory_gb,
345
+ "memory_margin_gb": s.memory_margin_gb,
346
+ "memory_reserved_gb": round(reserved, 2),
347
+ "memory_holders": sorted(s.holders),
348
+ "memory_assumed_resident": sorted(s.assumed() & set(members)),
349
+ "unknown_memory_policy": s.unknown_memory_policy,
350
+ }
351
+ )
352
+ return out
353
+
354
+
355
+ class AdmissionRejected(Exception):
356
+ def __init__(self, message: str, status: int = 503) -> None:
357
+ super().__init__(message)
358
+ self.message = message
359
+ self.status = status
@@ -0,0 +1,131 @@
1
+ """Session/run affinity, scoped to the authenticated caller.
2
+
3
+ A session key comes only from explicit, documented sources, in this fixed
4
+ order of precedence: the request's ``modelsaar.session`` hint, the client-
5
+ compatibility body field ``session_id`` (llama.cpp-style clients such as
6
+ Odysseus), a configured request header (e.g. ``X-ModelSaar-Session``,
7
+ ``X-OpenWebUI-Chat-Id``), a configured body field (``prompt_cache_key``).
8
+ When several sources carry *different* values the first one wins and the
9
+ others are reported as ignored in the routing decision (``affinity.ignored_hints``);
10
+ identical values are not a conflict. API keys are never used as conversation
11
+ ids and a shared system prompt is never treated as a session.
12
+
13
+ Tool round trips are kept on the same deployment even without a session id by
14
+ remembering the tool_call ids issued in the previous assistant turn.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import threading
21
+ import time
22
+ from collections import OrderedDict
23
+ from dataclasses import dataclass
24
+ from typing import Any
25
+
26
+ from ..config import AffinityConfig
27
+
28
+
29
+ @dataclass
30
+ class AffinityEntry:
31
+ deployment_id: str
32
+ expires_at: float
33
+ source: str
34
+
35
+
36
+ class AffinityStore:
37
+ def __init__(self, cfg: AffinityConfig) -> None:
38
+ self.cfg = cfg
39
+ self._lock = threading.Lock()
40
+ self._sessions: OrderedDict[str, AffinityEntry] = OrderedDict()
41
+ self._tool_rounds: OrderedDict[str, AffinityEntry] = OrderedDict()
42
+
43
+ @staticmethod
44
+ def _scope(caller_id: str, key: str) -> str:
45
+ return hashlib.sha256(f"{caller_id}\x00{key}".encode()).hexdigest()[:32]
46
+
47
+ def session_hints(self, headers: dict[str, str], body: dict[str, Any]) -> list[tuple[str, str]]:
48
+ """Every explicit session hint present, as (source, key), in precedence order."""
49
+ found: list[tuple[str, str]] = []
50
+ hint = body.get("modelsaar") or {}
51
+ if isinstance(hint, dict) and hint.get("session"):
52
+ found.append(("body:modelsaar.session", str(hint["session"])[:256]))
53
+ sid = body.get("session_id")
54
+ if isinstance(sid, str) and sid.strip():
55
+ found.append(("body:session_id", sid[:256]))
56
+ lower = {k.lower(): v for k, v in headers.items()}
57
+ for h in self.cfg.session_headers:
58
+ v = lower.get(h.lower())
59
+ if v:
60
+ found.append((f"header:{h}", str(v)[:256]))
61
+ for f in self.cfg.body_fields:
62
+ if f == "session_id":
63
+ continue # built in above, with validation
64
+ v = body.get(f)
65
+ if isinstance(v, str) and v:
66
+ found.append((f"body:{f}", v[:256]))
67
+ return found
68
+
69
+ def extract_session(self, headers: dict[str, str], body: dict[str, Any]) -> tuple[str | None, str, list[str]]:
70
+ """(key, source, ignored_sources): the highest-precedence hint wins; other sources with a DIFFERENT value
71
+ are listed as ignored so the decision shows the conflict. Deterministic: precedence never depends on
72
+ the order of fields in the request."""
73
+ hints = self.session_hints(headers, body)
74
+ if not hints:
75
+ return None, "none", []
76
+ source, key = hints[0]
77
+ ignored = [src for src, k in hints[1:] if k != key]
78
+ return key, source, ignored
79
+
80
+ def extract_session_key(self, headers: dict[str, str], body: dict[str, Any]) -> tuple[str | None, str]:
81
+ key, source, _ = self.extract_session(headers, body)
82
+ return key, source
83
+
84
+ def get(self, caller_id: str, session_key: str) -> AffinityEntry | None:
85
+ k = self._scope(caller_id, session_key)
86
+ with self._lock:
87
+ e = self._sessions.get(k)
88
+ if e and e.expires_at > time.time():
89
+ self._sessions.move_to_end(k)
90
+ return e
91
+ if e:
92
+ self._sessions.pop(k, None)
93
+ return None
94
+
95
+ def set(self, caller_id: str, session_key: str, deployment_id: str, source: str) -> None:
96
+ k = self._scope(caller_id, session_key)
97
+ with self._lock:
98
+ self._sessions[k] = AffinityEntry(deployment_id, time.time() + self.cfg.ttl_s, source)
99
+ self._sessions.move_to_end(k)
100
+ while len(self._sessions) > self.cfg.max_sessions:
101
+ self._sessions.popitem(last=False)
102
+
103
+ # Tool round trips ------------------------------------------------------
104
+ @staticmethod
105
+ def _round_key(caller_id: str, tool_call_ids: list[str]) -> str:
106
+ return hashlib.sha256(("\x00".join([caller_id, *sorted(tool_call_ids)])).encode()).hexdigest()[:32]
107
+
108
+ def remember_tool_calls(self, caller_id: str, tool_call_ids: list[str], deployment_id: str) -> None:
109
+ if not tool_call_ids:
110
+ return
111
+ k = self._round_key(caller_id, tool_call_ids)
112
+ with self._lock:
113
+ self._tool_rounds[k] = AffinityEntry(deployment_id, time.time() + min(self.cfg.ttl_s, 1800), "tool_round_trip")
114
+ while len(self._tool_rounds) > self.cfg.max_sessions:
115
+ self._tool_rounds.popitem(last=False)
116
+
117
+ def lookup_tool_round(self, caller_id: str, tool_call_ids: list[str]) -> AffinityEntry | None:
118
+ if not tool_call_ids:
119
+ return None
120
+ # Try the exact set first, then any single id (parallel calls answered one at a time).
121
+ keys = [self._round_key(caller_id, tool_call_ids)] + [self._round_key(caller_id, [i]) for i in tool_call_ids]
122
+ with self._lock:
123
+ for k in keys:
124
+ e = self._tool_rounds.get(k)
125
+ if e and e.expires_at > time.time():
126
+ return e
127
+ return None
128
+
129
+ def stats(self) -> dict[str, int]:
130
+ with self._lock:
131
+ return {"sessions": len(self._sessions), "tool_rounds": len(self._tool_rounds)}
@@ -0,0 +1,53 @@
1
+ """Cascades: try the lower-overhead deployment first, escalate on a *structural* failure.
2
+
3
+ Opt-in per alias (``aliases.<name>.cascade.enabled``). Every stage is drawn from the deployments that
4
+ passed the same hard filters for this request, so a cascade can never weaken a requirement. Because the
5
+ gateway never switches models after a response is committed, a cascade exists only for **non-streaming**
6
+ requests (the first answer is complete before anything is sent to the client) and never inside a tool
7
+ round trip, a reasoning continuation or a pinned session.
8
+
9
+ Escalation triggers are deterministic checks of the answer's structure — truncated by the output limit,
10
+ empty, not the JSON that was requested, no tool call although one was required. They are not a quality
11
+ judgement: a fluent wrong answer is accepted, and no model's self-reported confidence is consulted.
12
+ The last stage's answer is returned as it is, even if it also fails a check; nothing is repaired.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from typing import Any
19
+
20
+ TRIGGERS = ("length", "empty", "invalid_json", "missing_tool_call")
21
+ _JSON_TYPES = {"object": dict, "array": list, "string": str, "boolean": bool}
22
+
23
+
24
+ def acceptance_problem(request: dict[str, Any], response: dict[str, Any], triggers: tuple[str, ...]) -> str | None:
25
+ """Return the trigger (with a short reason) that this answer hits, or None when it is accepted."""
26
+ choice = (response.get("choices") or [{}])[0]
27
+ msg = choice.get("message") or {}
28
+ content = msg.get("content")
29
+ text = content if isinstance(content, str) else ""
30
+ calls = msg.get("tool_calls") or []
31
+ if "length" in triggers and choice.get("finish_reason") == "length":
32
+ return "length: the answer was cut off by the output limit"
33
+ if "empty" in triggers and not text.strip() and not calls:
34
+ return "empty: no content and no tool call"
35
+ tc = request.get("tool_choice")
36
+ if "missing_tool_call" in triggers and (tc == "required" or isinstance(tc, dict)) and not calls:
37
+ return "missing_tool_call: a tool call was required and none was returned"
38
+ rf = request.get("response_format") if isinstance(request.get("response_format"), dict) else {}
39
+ if "invalid_json" in triggers and rf.get("type") in ("json_object", "json_schema") and not calls:
40
+ try:
41
+ doc = json.loads(text)
42
+ except (json.JSONDecodeError, ValueError):
43
+ return "invalid_json: the content is not valid JSON"
44
+ schema = (rf.get("json_schema") or {}).get("schema") if rf.get("type") == "json_schema" else {"type": "object"}
45
+ if isinstance(schema, dict):
46
+ want = _JSON_TYPES.get(str(schema.get("type")))
47
+ if want and (not isinstance(doc, want) or (want is not bool and isinstance(doc, bool))):
48
+ return f"invalid_json: top-level value is not of type {schema.get('type')}"
49
+ if isinstance(doc, dict):
50
+ missing = [k for k in schema.get("required") or [] if k not in doc]
51
+ if missing:
52
+ return f"invalid_json: required keys missing: {missing[:5]}"
53
+ return None