seldon-runtime 0.1.1.dev0__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.
@@ -0,0 +1,544 @@
1
+ """Customer-facing ``Runner``: load an activated Function bundle and run it locally."""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import http.client
6
+ import json
7
+ import math
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import time
12
+ import urllib.error
13
+ import urllib.request
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import NamedTuple
17
+
18
+ from . import __version__
19
+ from .contracts import FunctionSpec, Plan, Step, digest
20
+ from .executor import execute, failure_reason
21
+ from .local import LocalModels
22
+ from .local_telemetry import bounded_reason
23
+ from .telemetry import Telemetry
24
+ from .tool_wire import decode_output
25
+
26
+ DEFAULT_BASE_URL = "https://api.seldon-ai.com"
27
+ BUNDLE_VERSION = "function-bundle-v1"
28
+ INELIGIBLE = {
29
+ "not_activated",
30
+ "hosted_only_model",
31
+ "plan_version",
32
+ "reference_bound",
33
+ "disabled",
34
+ }
35
+ GRACE_SECONDS = 86400
36
+ REFRESH_SECONDS = 900
37
+ AGREEMENT_MIN = 0.95
38
+ CONFORMANCE_VERSION = "function-conformance-v1"
39
+ CONFORMANCE_REF = re.compile(
40
+ r"/v1/seldon/functions/[A-Za-z0-9_-]{1,80}/conformance\?revision=[A-Za-z0-9_-]{1,80}"
41
+ )
42
+ _RESULT_KEYS = {"agreement", "samples", "p50_ms", "p95_ms", "passed"}
43
+
44
+
45
+ class _Cached(NamedTuple):
46
+ etag: str
47
+ expires: float
48
+ bundle: dict
49
+ plan: Plan
50
+ spec: FunctionSpec
51
+
52
+
53
+ class LocalExecutionError(Exception):
54
+ """``str(exc)`` is a bounded lowercase code; ``.reason`` holds the same code."""
55
+
56
+ def __init__(self, reason):
57
+ super().__init__(reason)
58
+ self.reason = reason
59
+
60
+
61
+ def _now():
62
+ return time.time()
63
+
64
+
65
+ def _release(version):
66
+ match = re.match(r"\d+(?:\.\d+)*", version)
67
+ parts = tuple(int(p) for p in match.group().split(".")) if match else (0,)
68
+ return parts + (0,) * (4 - len(parts))
69
+
70
+
71
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
72
+ def redirect_request(self, *_args, **_kwargs):
73
+ return None # urllib would forward Authorization to the redirect target
74
+
75
+
76
+ _OPENER = urllib.request.build_opener(_NoRedirect)
77
+
78
+
79
+ async def _urllib_http(method, url, headers, body):
80
+ def call():
81
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
82
+ try:
83
+ timeout = 10 if url.endswith(("/local-usage", "/local-status")) else 60
84
+ with _OPENER.open(request, timeout=timeout) as response:
85
+ return response.status, dict(response.headers.items()), response.read()
86
+ except urllib.error.HTTPError as exc:
87
+ return exc.code, dict(exc.headers.items()), exc.read()
88
+ except http.client.HTTPException:
89
+ raise OSError("transport_error") from None
90
+
91
+ status, headers, data = await asyncio.to_thread(call)
92
+ return status, {k.lower(): v for k, v in headers.items()}, data
93
+
94
+
95
+ def _atomic_write(path, data):
96
+ tmp = None
97
+ try:
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+ fd, tmp = tempfile.mkstemp(dir=path.parent)
100
+ with os.fdopen(fd, "w") as handle: # mkstemp creates the file 0o600
101
+ json.dump(data, handle)
102
+ os.replace(tmp, path)
103
+ except OSError:
104
+ # ponytail: caches are only optimisations; without them offline grace/verify reuse is lost.
105
+ if tmp:
106
+ try:
107
+ os.unlink(tmp)
108
+ except OSError:
109
+ pass
110
+
111
+
112
+ def _signed(body):
113
+ return digest({k: v for k, v in body.items() if k != "expires_at"})
114
+
115
+
116
+ def _validate(body, etag):
117
+ try:
118
+ if body["version"] != BUNDLE_VERSION or _signed(body) != etag:
119
+ raise ValueError
120
+ plan = Plan.model_validate(body["plan"])
121
+ spec = FunctionSpec.model_validate(body["spec"])
122
+ if plan.digest != body["plan_digest"] or spec.digest != body["contract_digest"]:
123
+ raise ValueError
124
+ expires = datetime.fromisoformat(body["expires_at"]).timestamp()
125
+ minimum = _release(body["runtime_min_version"])
126
+ except Exception:
127
+ raise LocalExecutionError("bundle_invalid") from None
128
+ if minimum > _release(__version__):
129
+ raise LocalExecutionError("runtime_upgrade_required")
130
+ return expires, plan, spec
131
+
132
+
133
+ class Runner:
134
+ def __init__(
135
+ self,
136
+ function_id,
137
+ api_key,
138
+ fallback,
139
+ base_url,
140
+ cache_file,
141
+ http,
142
+ provider,
143
+ allow_unverified,
144
+ telemetry=True,
145
+ ):
146
+ self._function_id = function_id
147
+ self._api_key = api_key
148
+ self._fallback = fallback
149
+ self._base_url = base_url.rstrip("/")
150
+ self._cache_file = cache_file
151
+ self._http = http
152
+ self._provider = provider
153
+ self._injected = provider is not None
154
+ self._allow_unverified = allow_unverified
155
+ self._bundle = self._plan = self._spec = self._etag = self._expires_at = None
156
+ self._stopped = self._task = None
157
+ self._refused = None # why the last refresh declined a newer bundle
158
+ self._checked_at = 0.0
159
+ self._verification = None
160
+ self._telemetry = Telemetry(self, telemetry)
161
+
162
+ @classmethod
163
+ async def load(
164
+ cls,
165
+ function_id,
166
+ api_key,
167
+ *,
168
+ fallback="seldon",
169
+ base_url=DEFAULT_BASE_URL,
170
+ cache_dir=None,
171
+ http=None,
172
+ provider=None,
173
+ allow_unverified=False,
174
+ telemetry=True,
175
+ ):
176
+ if fallback not in ("seldon", "raise") and not (
177
+ isinstance(fallback, dict)
178
+ and set(fallback) == {"endpoint", "api_key"}
179
+ and all(isinstance(v, str) and v for v in fallback.values())
180
+ ):
181
+ raise ValueError("invalid_fallback")
182
+ if not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", str(function_id)):
183
+ raise LocalExecutionError("function_not_found")
184
+ root = Path(cache_dir) if cache_dir else Path.home() / ".cache" / "seldon"
185
+ env = hashlib.sha256(base_url.rstrip("/").encode()).hexdigest()[:16] # per environment
186
+ runner = cls(
187
+ function_id,
188
+ api_key,
189
+ fallback,
190
+ base_url,
191
+ root / "bundles" / env / f"{function_id}.json",
192
+ http or _urllib_http,
193
+ provider,
194
+ allow_unverified,
195
+ telemetry,
196
+ )
197
+ await runner._fetch(runner._read_cache())
198
+ runner._checked_at = _now()
199
+ runner._task = asyncio.create_task(runner._refresh_loop())
200
+ runner._telemetry.start()
201
+ return runner
202
+
203
+ async def _refresh_loop(self):
204
+ while True:
205
+ # a task restarted on a new loop checks at once when a check is overdue
206
+ await asyncio.sleep(max(0.0, self._checked_at + REFRESH_SECONDS - _now()))
207
+ self._checked_at = _now()
208
+ try:
209
+ await self.refresh()
210
+ except Exception: # ponytail: one failed check must not end revalidation
211
+ pass
212
+
213
+ async def aclose(self):
214
+ if self._task:
215
+ try:
216
+ self._task.cancel()
217
+ await self._task
218
+ except (
219
+ asyncio.CancelledError,
220
+ RuntimeError,
221
+ ): # RuntimeError: its loop is closed
222
+ pass
223
+ await self._telemetry.close()
224
+
225
+ async def flush_telemetry(self):
226
+ """Await one bounded best-effort flush; never changes execution or funding."""
227
+ await self._telemetry.flush()
228
+
229
+ def status(self):
230
+ """Local observation only: no model, network or cache reads are performed."""
231
+ reason = self._stopped or self._refused
232
+ state = "stopped" if self._stopped else "refresh_refused" if self._refused else "serving"
233
+ if not self._stopped and _now() >= self._expires_at:
234
+ state, reason = "expired", reason or "bundle_expired"
235
+ return {
236
+ "reporting_id": self._telemetry.reporting_id,
237
+ "revision_id": self._bundle["revision_id"],
238
+ "runtime_version": __version__,
239
+ "model_versions": {
240
+ k: v["hf_revision"] for k, v in self._bundle["local_models"].items()
241
+ },
242
+ "verification": dict(self._verification) if self._verification else None,
243
+ "state": state,
244
+ "reason": bounded_reason(reason) if reason else None,
245
+ }
246
+
247
+ async def refresh(self):
248
+ """One conditional revalidation; never raises, never touches the request path."""
249
+ current = _Cached(self._etag, self._expires_at, self._bundle, self._plan, self._spec)
250
+ try:
251
+ await self._fetch(current)
252
+ except LocalExecutionError as exc:
253
+ if exc.reason.startswith("local_ineligible") or exc.reason in (
254
+ "function_not_found",
255
+ "unauthorized",
256
+ ):
257
+ self._stopped = exc.reason
258
+ try: # a restart must not serve a revoked bundle from disk
259
+ self._cache_file.unlink()
260
+ except OSError:
261
+ pass
262
+ elif exc.reason != "bundle_unavailable": # Seldon answered; the bundle was refused
263
+ self._refused = exc.reason
264
+
265
+ async def _install(self, etag, expires, bundle, plan, spec):
266
+ provider = self._provider
267
+ if bundle is not self._bundle: # the same object was gated when it was installed
268
+ try:
269
+ models = bundle["local_models"]
270
+ if not self._injected:
271
+ provider = LocalModels(models).provider
272
+ except Exception: # a malformed bundle must not raise out of refresh()
273
+ raise LocalExecutionError("bundle_invalid") from None
274
+ if not self._allow_unverified:
275
+ result = self._read_result(bundle)
276
+ if result is None:
277
+ result, cacheable = await self._replay(bundle, plan, spec, provider)
278
+ if cacheable:
279
+ self._write_result(bundle, result)
280
+ if not result["passed"]:
281
+ raise LocalExecutionError("conformance_failed")
282
+ self._set(etag, expires, bundle, plan, spec, provider)
283
+
284
+ def _set(self, etag, expires, bundle, plan, spec, provider):
285
+ self._provider = provider
286
+ # one synchronous swap: a call sees the old or the new bundle, never a mix
287
+ self._etag, self._expires_at, self._bundle = etag, expires, bundle
288
+ self._plan, self._spec = plan, spec
289
+ self._verification = self._read_result(bundle)
290
+
291
+ def _read_cache(self):
292
+ try:
293
+ cached = json.loads(self._cache_file.read_text())
294
+ etag, expires, bundle = (
295
+ cached["etag"],
296
+ float(cached["expires_at"]),
297
+ cached["bundle"],
298
+ )
299
+ _, plan, spec = _validate(bundle, etag)
300
+ return _Cached(etag, expires, bundle, plan, spec)
301
+ except Exception:
302
+ return None
303
+
304
+ def _write_cache(self):
305
+ _atomic_write(
306
+ self._cache_file,
307
+ {
308
+ "etag": self._etag,
309
+ "expires_at": self._expires_at,
310
+ "bundle": self._bundle,
311
+ },
312
+ )
313
+
314
+ def _result_file(self, bundle):
315
+ models = bundle["local_models"] # whole entries: a changed pin or threshold re-verifies
316
+ key = digest({"plan": bundle["plan_digest"], "models": models, "runtime": __version__})
317
+ # <cache root>/bundles/<env>/<fn>.json -> <cache root>/verify/<env>/<key>.json
318
+ return self._cache_file.parents[2] / "verify" / self._cache_file.parent.name / f"{key}.json"
319
+
320
+ def _read_result(self, bundle):
321
+ try:
322
+ result = json.loads(self._result_file(bundle).read_text())
323
+ ok = isinstance(result, dict) and set(result) == _RESULT_KEYS
324
+ return result if ok and isinstance(result["passed"], bool) else None
325
+ except Exception:
326
+ return None
327
+
328
+ def _write_result(self, bundle, result):
329
+ _atomic_write(self._result_file(bundle), result)
330
+
331
+ async def verify(self):
332
+ """Replay the conformance set against the current bundle; always re-measures."""
333
+ bundle = self._bundle
334
+ result, cacheable = await self._replay(bundle, self._plan, self._spec, self._provider)
335
+ if self._bundle is bundle:
336
+ self._verification = result
337
+ if cacheable:
338
+ self._write_result(bundle, result)
339
+ return result
340
+
341
+ async def _conformance(self, bundle):
342
+ ref = bundle.get("conformance_ref")
343
+ if not isinstance(ref, str) or not CONFORMANCE_REF.fullmatch(ref):
344
+ raise LocalExecutionError("conformance_unavailable") # never send the key elsewhere
345
+ headers = {"Authorization": f"Bearer {self._api_key}"}
346
+ try:
347
+ status, _, data = await self._http("GET", f"{self._base_url}{ref}", headers, None)
348
+ except OSError:
349
+ status = None
350
+ if status in (401, 403):
351
+ raise LocalExecutionError("unauthorized")
352
+ try:
353
+ body = json.loads(data) if status == 200 else None
354
+ items = body["items"]
355
+ if (
356
+ body["version"] != CONFORMANCE_VERSION
357
+ or body["plan_digest"] != bundle["plan_digest"]
358
+ ):
359
+ raise ValueError
360
+ if (
361
+ not isinstance(items, list)
362
+ or not items
363
+ or not all(
364
+ isinstance(i, dict)
365
+ and isinstance(i.get("input"), dict)
366
+ and isinstance(i.get("output_digest"), str)
367
+ for i in items
368
+ )
369
+ ):
370
+ raise ValueError
371
+ except (ValueError, KeyError, TypeError):
372
+ raise LocalExecutionError("conformance_unavailable") from None
373
+ return items
374
+
375
+ async def _replay(self, bundle, plan, spec, provider):
376
+ items = await self._conformance(bundle)
377
+ plan = plan.model_copy(update={"fallback": False}) # measure the local program only
378
+
379
+ async def local_only(model, payload): # the fallback route is never used here
380
+ if "primitive" not in payload:
381
+ raise ValueError("provider_unavailable")
382
+ return await provider(model, payload)
383
+
384
+ agreed, times, reason = 0, [], None
385
+ for item in items: # ponytail: sequential; batch if verify time bites (max 200 items)
386
+ try:
387
+ result = await execute(
388
+ plan,
389
+ spec,
390
+ item["input"],
391
+ local_only,
392
+ contract=bundle["optimizer_contract_version"],
393
+ serving=True,
394
+ )
395
+ except Exception as exc:
396
+ reason = reason or failure_reason(exc)
397
+ continue
398
+ times.append(result.elapsed_ms)
399
+ agreed += digest(result.output) == item["output_digest"]
400
+ if not times: # nothing ran: an environment problem, not a measurement
401
+ raise LocalExecutionError(reason)
402
+ times.sort()
403
+
404
+ def pct(p): # nearest rank
405
+ return int(times[math.ceil(p * len(times) / 100) - 1]) if times else None
406
+
407
+ agreement = agreed / len(items)
408
+ result = {
409
+ "agreement": agreement,
410
+ "samples": len(items),
411
+ "p50_ms": pct(50),
412
+ "p95_ms": pct(95),
413
+ "passed": agreement >= AGREEMENT_MIN,
414
+ }
415
+ # a failing result is cached only if every item ran: partial raises may be environmental
416
+ return result, result["passed"] or len(times) == len(items)
417
+
418
+ async def _fetch(self, cached):
419
+ headers = {"Authorization": f"Bearer {self._api_key}"}
420
+ if cached:
421
+ headers["If-None-Match"] = f'"{cached.etag}"'
422
+ url = f"{self._base_url}/v1/seldon/functions/{self._function_id}/bundle"
423
+ try:
424
+ status, response, data = await self._http("GET", url, headers, None)
425
+ except OSError:
426
+ status = None
427
+ if status == 200:
428
+ try:
429
+ body = json.loads(data)
430
+ etag = response.get("etag", "").removeprefix("W/").strip('"')
431
+ expires, plan, spec = _validate(body, etag)
432
+ except (ValueError, AttributeError):
433
+ raise LocalExecutionError("bundle_invalid") from None
434
+ await self._install(etag, expires, body, plan, spec)
435
+ elif status == 304 and cached:
436
+ await self._install(*cached._replace(expires=_now() + GRACE_SECONDS))
437
+ elif status == 409:
438
+ try:
439
+ reason = (json.loads(data).get("details") or {}).get("reason")
440
+ except (ValueError, AttributeError):
441
+ reason = None
442
+ raise LocalExecutionError(
443
+ f"local_ineligible_{reason}" if reason in INELIGIBLE else "local_ineligible"
444
+ )
445
+ elif status in (401, 403):
446
+ raise LocalExecutionError("unauthorized")
447
+ elif status == 404:
448
+ raise LocalExecutionError("function_not_found")
449
+ elif cached and _now() < cached.expires: # offline grace
450
+ await self._install(*cached)
451
+ return
452
+ else:
453
+ raise LocalExecutionError("bundle_unavailable")
454
+ self._stopped = self._refused = None
455
+ self._write_cache()
456
+
457
+ async def _post(self, url, key, model, payload):
458
+ body = {"model": model, **payload}
459
+ body.pop("seldon_output_token_policy", None)
460
+ headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
461
+ try:
462
+ status, _, data = await self._http("POST", url, headers, json.dumps(body).encode())
463
+ except OSError:
464
+ raise ValueError("provider_unavailable") from None
465
+ if status != 200:
466
+ raise ValueError("provider_unavailable")
467
+ try:
468
+ raw = json.loads(data)
469
+ choice = raw["choices"][0]
470
+ message = choice["message"]
471
+ refused = choice.get("finish_reason") == "content_filter" or message.get("refusal")
472
+ output = None if refused else decode_output(raw, payload)
473
+ except (ValueError, KeyError, IndexError, TypeError, AttributeError):
474
+ raise ValueError("invalid_provider_output") from None
475
+ if refused:
476
+ raise ValueError("provider_refusal")
477
+ return output
478
+
479
+ async def _route(self, provider, model, payload):
480
+ if "primitive" in payload:
481
+ return await provider(model, payload)
482
+ if isinstance(self._fallback, dict):
483
+ endpoint, key = (
484
+ self._fallback["endpoint"].rstrip("/"),
485
+ self._fallback["api_key"],
486
+ )
487
+ elif self._fallback == "seldon":
488
+ endpoint, key = f"{self._base_url}/v1", self._api_key
489
+ else:
490
+ raise ValueError("provider_unavailable")
491
+ return await self._post(f"{endpoint}/chat/completions", key, model, payload)
492
+
493
+ async def __call__(self, inputs):
494
+ started, bundle = time.monotonic(), self._bundle
495
+ try:
496
+ result = await self._call(inputs)
497
+ except Exception:
498
+ self._telemetry.record(bundle, (time.monotonic() - started) * 1000, failed=True)
499
+ raise
500
+ self._telemetry.record(
501
+ bundle,
502
+ (time.monotonic() - started) * 1000,
503
+ fallback=result["fallback_reason"],
504
+ )
505
+ return result
506
+
507
+ async def _call(self, inputs):
508
+ if self._stopped: # definitive answer from Seldon: no fallback policy
509
+ raise LocalExecutionError(self._stopped)
510
+ if self._task is None or self._task.done():
511
+ # ponytail: the loop that ran load() may be gone; no bundle request is made here
512
+ self._task = asyncio.create_task(self._refresh_loop())
513
+ plan, spec, bundle, provider = (
514
+ self._plan,
515
+ self._spec,
516
+ self._bundle,
517
+ self._provider,
518
+ )
519
+ expired = None
520
+ if _now() >= self._expires_at: # Seldon unreachable past the grace window
521
+ if self._fallback == "raise" or not plan.fallback:
522
+ raise LocalExecutionError(self._refused or "bundle_expired")
523
+ plan = Plan(
524
+ steps=[Step(id=c.id, op="llm", model=c.model, call=c.id) for c in spec.calls]
525
+ )
526
+ expired = self._refused or "bundle_expired"
527
+ elif self._fallback == "raise":
528
+ plan = plan.model_copy(update={"fallback": False})
529
+ try:
530
+ result = await execute(
531
+ plan,
532
+ spec,
533
+ inputs,
534
+ lambda model, payload: self._route(provider, model, payload),
535
+ contract=bundle["optimizer_contract_version"],
536
+ serving=True,
537
+ )
538
+ except Exception as exc:
539
+ raise LocalExecutionError(failure_reason(exc)) from None
540
+ return {
541
+ "output": result.output,
542
+ "fallback_used": bool(expired) or result.fallback_used,
543
+ "fallback_reason": expired or result.fallback_reason,
544
+ }