seldon-runtime 0.1.1.dev0__py3-none-any.whl → 0.1.1.dev2__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.
@@ -1,3 +1,3 @@
1
1
  """Standalone Seldon Functions interpreter and local execution client."""
2
2
 
3
- __version__ = "0.1.1.dev0"
3
+ __version__ = "0.1.1.dev2"
@@ -0,0 +1,336 @@
1
+ """Data-only compiler artifacts, independent of hosted bundle authority.
2
+
3
+ An export is one bounded ``manifest.json`` with inline plan/spec data. It cannot
4
+ name other files, endpoints or credentials. Its hashes detect corruption, not a
5
+ trusted publisher: the caller must trust the compiler/export source separately.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import math
13
+ import os
14
+ import stat
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any, Literal, Protocol
18
+
19
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
20
+
21
+ from .contracts import FunctionSpec, Plan, digest
22
+ from .executor import Execution, execute
23
+ from .output_budget import resolve
24
+ from .program_validation import validate_program
25
+ from .provider_error import ProviderError
26
+
27
+ MAX_ARTIFACT_BYTES = 2 * 1024 * 1024
28
+ RUNTIME_VERSION = "0.1.1.dev2"
29
+ _SHA256 = r"^[0-9a-f]{64}$"
30
+ Capability = Literal["chat", "structured_output", "tools"]
31
+ OptimizerContract = Literal[
32
+ "optimizer-correctness-v1",
33
+ "optimizer-correctness-v2",
34
+ "optimizer-correctness-v3",
35
+ "optimizer-correctness-v4",
36
+ "optimizer-correctness-v5",
37
+ "optimizer-correctness-v6",
38
+ "optimizer-correctness-v7",
39
+ "optimizer-correctness-v8",
40
+ ]
41
+
42
+
43
+ class ArtifactError(ValueError):
44
+ """A bounded code only; never includes input data, credentials or file paths."""
45
+
46
+
47
+ class _Data(BaseModel):
48
+ model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
49
+
50
+
51
+ class ModelRequirements(_Data):
52
+ """Execution capabilities, not endpoint discovery or proof of model quality."""
53
+
54
+ protocol: Literal["openai-chat-completions"]
55
+ capabilities: tuple[Capability, ...] = Field(min_length=1, max_length=3)
56
+ context_length: int = Field(strict=True, ge=1, le=100_000_000)
57
+ max_output_tokens: int = Field(strict=True, ge=1, le=10_000_000)
58
+ revision: str | None = Field(max_length=256)
59
+
60
+
61
+ class Evidence(_Data):
62
+ candidate_id: str = Field(min_length=1, max_length=256)
63
+ evaluation_semantics: Literal[
64
+ "evaluation-semantics-v1", "evaluation-semantics-v2", "evaluation-semantics-v3"
65
+ ]
66
+ samples: int = Field(strict=True, ge=0)
67
+
68
+
69
+ class ArtifactManifest(_Data):
70
+ version: Literal["compiler-artifact-v1"]
71
+ compiler_version: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z0-9.+_-]+$")
72
+ # Explicit reviewed reader compatibility, never a version-prefix/range guess.
73
+ # dev2 changes asset delivery only; dev1's token and plan semantics are frozen.
74
+ runtime_version: Literal["0.1.1.dev1", "0.1.1.dev2"]
75
+ optimizer_contract_version: OptimizerContract
76
+ instruction_envelope: Literal["instruction-envelope-v1"] | None
77
+ conditional: bool = Field(strict=True)
78
+ spec: FunctionSpec
79
+ plan: Plan
80
+ models: dict[str, ModelRequirements] = Field(max_length=19)
81
+ evidence: Evidence
82
+ spec_digest: str = Field(pattern=_SHA256)
83
+ plan_digest: str = Field(pattern=_SHA256)
84
+ manifest_digest: str = Field(pattern=_SHA256)
85
+
86
+
87
+ class Provider(Protocol):
88
+ async def __call__(self, payload: dict[str, Any]) -> Any:
89
+ """Await and return decoded output; raise ProviderError for known failures.
90
+
91
+ Transport owns TLS, endpoint/credential origin binding and response limits.
92
+ Unknown exceptions stop execution without automatic fallback or retry.
93
+ """
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class RuntimeBinding:
98
+ """Caller-owned transport and its independently configured model identity."""
99
+
100
+ requirements: ModelRequirements
101
+ invoke: Provider
102
+
103
+
104
+ def _unique_object(pairs):
105
+ result = {}
106
+ for key, value in pairs:
107
+ if key in result:
108
+ raise ArtifactError("artifact_invalid")
109
+ result[key] = value
110
+ return result
111
+
112
+
113
+ def _required_capabilities(plan: Plan, spec: FunctionSpec) -> dict[str, set[str]]:
114
+ required: dict[str, set[str]] = {}
115
+ calls = {call.id: call for call in spec.calls}
116
+
117
+ def add(model, call, *, output_schema=None):
118
+ caps = required.setdefault(model, {"chat"})
119
+ if output_schema or call.response_format:
120
+ caps.add("structured_output")
121
+ if call.tools and not output_schema:
122
+ caps.add("tools")
123
+
124
+ for step in plan.steps:
125
+ if step.op == "llm":
126
+ add(step.model, calls[step.call], output_schema=step.output_schema)
127
+ if plan.fallback:
128
+ for call in spec.calls:
129
+ add(call.model, call)
130
+ return required
131
+
132
+
133
+ def _parse(data: bytes) -> ArtifactManifest:
134
+ if len(data) > MAX_ARTIFACT_BYTES:
135
+ raise ArtifactError("artifact_too_large")
136
+ try:
137
+ raw = json.loads(data, object_pairs_hook=_unique_object)
138
+ if not isinstance(raw, dict):
139
+ raise ValueError
140
+ # Refuse code extensions before Pydantic can reach their validation hooks.
141
+ if raw.get("spec", {}).get("reference_binding") is not None:
142
+ raise ValueError
143
+ if any(
144
+ step.get("op") in {"generated_kernel", "choice", "extract"}
145
+ for step in raw.get("plan", {}).get("steps", [])
146
+ ):
147
+ raise ValueError
148
+ manifest = ArtifactManifest.model_validate(raw)
149
+ if (
150
+ digest({k: v for k, v in raw.items() if k != "manifest_digest"})
151
+ != manifest.manifest_digest
152
+ ):
153
+ raise ValueError
154
+ if (
155
+ manifest.spec.digest != manifest.spec_digest
156
+ or manifest.plan.digest != manifest.plan_digest
157
+ ):
158
+ raise ValueError
159
+ plan = manifest.plan
160
+ contract = manifest.optimizer_contract_version
161
+ if plan.version == "function-plan-v4" and contract in {
162
+ "optimizer-correctness-v1",
163
+ "optimizer-correctness-v2",
164
+ }:
165
+ raise ValueError
166
+ if plan.version == "function-plan-v5" and (
167
+ not manifest.conditional
168
+ or contract in {f"optimizer-correctness-v{i}" for i in range(1, 5)}
169
+ ):
170
+ raise ValueError
171
+ validate_program(plan, manifest.spec)
172
+ required = _required_capabilities(plan, manifest.spec)
173
+ if set(manifest.models) != set(required):
174
+ raise ValueError
175
+ for name, caps in required.items():
176
+ model = manifest.models[name]
177
+ if not caps <= set(model.capabilities):
178
+ raise ValueError
179
+ if len(set(model.capabilities)) != len(model.capabilities):
180
+ raise ValueError
181
+ return manifest
182
+ except ArtifactError:
183
+ raise
184
+ except (ValueError, TypeError, KeyError, AttributeError, RecursionError, ValidationError):
185
+ raise ArtifactError("artifact_invalid") from None
186
+
187
+
188
+ def _bindings(manifest, bindings):
189
+ if set(bindings) != set(manifest.models):
190
+ raise ArtifactError("model_binding_mismatch")
191
+ for name, required in manifest.models.items():
192
+ binding = bindings[name]
193
+ if not isinstance(binding, RuntimeBinding) or not callable(binding.invoke):
194
+ raise ArtifactError("model_binding_mismatch")
195
+ actual = binding.requirements
196
+ if not isinstance(actual, ModelRequirements) or (
197
+ actual.protocol != required.protocol
198
+ or actual.revision != required.revision
199
+ or actual.context_length < required.context_length
200
+ # Omitted max_tokens preserves endpoint-default behavior, so an
201
+ # enlarged endpoint output ceiling cannot silently enlarge the bound.
202
+ or actual.max_output_tokens != required.max_output_tokens
203
+ or not set(required.capabilities) <= set(actual.capabilities)
204
+ ):
205
+ raise ArtifactError("model_binding_mismatch")
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class Artifact:
210
+ _data: bytes
211
+
212
+ def __post_init__(self):
213
+ _parse(self._data)
214
+
215
+ @property
216
+ def manifest(self) -> ArtifactManifest:
217
+ """Return a fresh parsed view; mutating it cannot change the loaded artifact."""
218
+ return _parse(self._data)
219
+
220
+ async def run(
221
+ self, inputs: dict[str, Any], *, bindings: dict[str, RuntimeBinding], timeout: float = 55
222
+ ) -> Execution:
223
+ """Execute using explicitly bound transports; no network setup or retry here."""
224
+ if (
225
+ isinstance(timeout, bool)
226
+ or not isinstance(timeout, (int, float))
227
+ or not (math.isfinite(timeout) and 0 < timeout <= 300)
228
+ ):
229
+ raise ArtifactError("timeout_invalid")
230
+ manifest = self.manifest
231
+ bindings = dict(bindings)
232
+ _bindings(manifest, bindings)
233
+
234
+ async def provider(model, payload):
235
+ required = manifest.models[model]
236
+ needed = {"chat"}
237
+ if payload.get("tools"):
238
+ needed.add("tools")
239
+ if payload.get("response_format"):
240
+ needed.add("structured_output")
241
+ if "primitive" in payload or not needed <= set(required.capabilities):
242
+ raise ArtifactError("model_capability_mismatch")
243
+ bounded, _, _ = resolve(
244
+ payload,
245
+ required,
246
+ manifest.spec.output_token_policy,
247
+ body=lambda value, _: value,
248
+ estimator_for=lambda _: None,
249
+ )
250
+ try:
251
+ return await bindings[model].invoke(bounded)
252
+ except ProviderError as exc:
253
+ # Preserve only the typed facts needed by existing fallback rules;
254
+ # even an accidentally unsafe provider message never escapes.
255
+ known = {
256
+ "upstream_context_refused",
257
+ "upstream_unavailable",
258
+ "rate_limited",
259
+ "content_filter",
260
+ "provider_refusal",
261
+ "content_policy_violation",
262
+ }
263
+ code = exc.code if exc.code in known else "provider_error"
264
+ if exc.upstream_code in {
265
+ "content_filter",
266
+ "provider_refusal",
267
+ "content_policy_violation",
268
+ }:
269
+ code = exc.upstream_code
270
+ raise ProviderError(
271
+ 503,
272
+ code,
273
+ "Provider request failed",
274
+ category="unavailable" if exc.category == "unavailable" else None,
275
+ upstream_status=429 if exc.upstream_status == 429 else None,
276
+ provider_dispatched=exc.provider_dispatched,
277
+ ) from None
278
+ except Exception:
279
+ raise ArtifactError("execution_failed") from None
280
+
281
+ try:
282
+ return await execute(
283
+ manifest.plan,
284
+ manifest.spec,
285
+ inputs,
286
+ provider,
287
+ timeout=timeout,
288
+ contract=manifest.optimizer_contract_version,
289
+ conditional=manifest.conditional,
290
+ serving=True,
291
+ instruction_envelope=manifest.instruction_envelope,
292
+ )
293
+ except ArtifactError:
294
+ raise
295
+ except TimeoutError:
296
+ raise ArtifactError("execution_timeout") from None
297
+ except asyncio.CancelledError:
298
+ raise
299
+ except Exception as exc:
300
+ safe = {"token_limit", "context_unverified", "output_schema", "invalid_provider_output"}
301
+ code = (
302
+ str(exc) if isinstance(exc, ValueError) and str(exc) in safe else "execution_failed"
303
+ )
304
+ raise ArtifactError(code) from None
305
+
306
+
307
+ def load_artifact(directory: str | Path) -> Artifact:
308
+ """Load one regular, bounded manifest beneath a non-symlink export directory.
309
+
310
+ The caller chooses the directory. The manifest has no relative/absolute file
311
+ references, so it cannot cause traversal, fetches or additional file reads.
312
+ """
313
+ directory_fd = file_fd = None
314
+ try:
315
+ directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
316
+ file_fd = os.open(
317
+ "manifest.json", os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory_fd
318
+ )
319
+ info = os.fstat(file_fd)
320
+ if not stat.S_ISREG(info.st_mode):
321
+ raise ArtifactError("artifact_invalid")
322
+ if info.st_size > MAX_ARTIFACT_BYTES:
323
+ raise ArtifactError("artifact_too_large")
324
+ with os.fdopen(file_fd, "rb") as handle:
325
+ file_fd = None
326
+ data = handle.read(MAX_ARTIFACT_BYTES + 1)
327
+ return Artifact(data)
328
+ except ArtifactError:
329
+ raise
330
+ except (OSError, TypeError, ValueError):
331
+ raise ArtifactError("artifact_unavailable") from None
332
+ finally:
333
+ if file_fd is not None:
334
+ os.close(file_fd)
335
+ if directory_fd is not None:
336
+ os.close(directory_fd)
@@ -9,6 +9,7 @@ CONDITIONAL_CONTRACT = "optimizer-correctness-v5"
9
9
  # capability booleans instead of implying conditional creation.
10
10
  EVALUATION_FIDELITY_CONTRACT = "optimizer-correctness-v6"
11
11
  SPAN_GROUNDING_CONTRACT = "optimizer-correctness-v7"
12
+ CORRECTNESS_REPAIR_CONTRACT = "optimizer-correctness-v8"
12
13
  # Learned-step requests delimit the compiler-added instruction and stage inputs
13
14
  # in one developer message (``instruction_envelope.py``). Frozen per run and per
14
15
  # revision; ``None`` keeps the legacy request bytes. No setting creates it yet.
@@ -535,6 +535,7 @@ class FunctionSpec(Contract):
535
535
  "bounded_8192",
536
536
  "context_measured_v1",
537
537
  "context_measured_v2",
538
+ "context_measured_v3",
538
539
  ] = "request"
539
540
  reference_binding: ReferenceBinding | None = None
540
541
  calls: list[RequestContract] = Field(min_length=1, max_length=3)