seldon-runtime 0.1.1.dev0__py3-none-any.whl → 0.1.1.dev1__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.dev1"
@@ -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.dev1"
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
+ # Exact runtime identity keeps unpublished semantic readers from being guessed
73
+ # compatible by numeric-prefix comparison (for example dev0 versus dev1).
74
+ runtime_version: Literal["0.1.1.dev1"]
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)
@@ -671,6 +671,7 @@ async def execute(
671
671
  from .contract_versions import (
672
672
  CONDITIONAL_CONTRACT,
673
673
  CONTEXT_CHUNKING_CONTRACT,
674
+ CORRECTNESS_REPAIR_CONTRACT,
674
675
  EVALUATION_FIDELITY_CONTRACT,
675
676
  SPAN_GROUNDING_CONTRACT,
676
677
  )
@@ -678,7 +679,8 @@ async def execute(
678
679
  # v6 freezes the conditional capability separately; ``conditional=False``
679
680
  # (a v6 run created with conditional workflows off) rejects v5 plans.
680
681
  v5_allowed = contract == CONDITIONAL_CONTRACT or (
681
- contract in {EVALUATION_FIDELITY_CONTRACT, SPAN_GROUNDING_CONTRACT}
682
+ contract
683
+ in {EVALUATION_FIDELITY_CONTRACT, SPAN_GROUNDING_CONTRACT, CORRECTNESS_REPAIR_CONTRACT}
682
684
  and conditional is not False
683
685
  )
684
686
  if plan.version == "function-plan-v5" and not v5_allowed:
@@ -689,6 +691,7 @@ async def execute(
689
691
  CONDITIONAL_CONTRACT,
690
692
  EVALUATION_FIDELITY_CONTRACT,
691
693
  SPAN_GROUNDING_CONTRACT,
694
+ CORRECTNESS_REPAIR_CONTRACT,
692
695
  }
693
696
  if plan.version == "function-plan-v4" and contract not in chunking:
694
697
  raise ValueError("plan_version_unsupported")
@@ -12,6 +12,9 @@ remaining context:
12
12
  native primitive's declared allowance must then fit unclamped. Without a
13
13
  registered estimator it makes the byte decision and refuses
14
14
  ``context_unverified``. The byte bound still prices the hold and TPM estimate.
15
+ * ``context_measured_v3`` retains the v2 assumed tokenizer and financial output
16
+ bound, but GLiNER encoder extraction checks input-only context. Other protocols
17
+ retain v2 rules; no historical policy changes.
15
18
 
16
19
  Native primitives retain their bounded request allowance, capped to their own
17
20
  endpoint (and to the policy ceiling) when inherited from a full-request LLM call.
@@ -33,6 +36,7 @@ ENDPOINT_MAX = "endpoint_max"
33
36
  BOUNDED_8192 = "bounded_8192"
34
37
  CONTEXT_MEASURED = "context_measured_v1"
35
38
  CONTEXT_MEASURED_V2 = "context_measured_v2"
39
+ CONTEXT_MEASURED_V3 = "context_measured_v3"
36
40
  MARKER = "seldon_output_token_policy"
37
41
  # Internal key carrying a capability run's frozen wire profile into fit and
38
42
  # admission (the request depends on the host's state form). Never sent.
@@ -46,11 +50,16 @@ ASSUMED_TOKEN_PAD = 32
46
50
  # Policies that size the output allowance themselves instead of honoring the
47
51
  # request's ``max_tokens``. Callers use this set rather than comparing to one value.
48
52
  FULL_REQUEST_POLICIES = frozenset(
49
- {ENDPOINT_MAX, BOUNDED_8192, CONTEXT_MEASURED, CONTEXT_MEASURED_V2}
53
+ {ENDPOINT_MAX, BOUNDED_8192, CONTEXT_MEASURED, CONTEXT_MEASURED_V2, CONTEXT_MEASURED_V3}
50
54
  )
51
55
  POLICIES = frozenset({REQUEST, *FULL_REQUEST_POLICIES})
52
56
  # Policy ceiling below the endpoint maximum. ``endpoint_max`` has none.
53
- _CEILINGS = {BOUNDED_8192: 8192, CONTEXT_MEASURED: 8192, CONTEXT_MEASURED_V2: 8192}
57
+ _CEILINGS = {
58
+ BOUNDED_8192: 8192,
59
+ CONTEXT_MEASURED: 8192,
60
+ CONTEXT_MEASURED_V2: 8192,
61
+ CONTEXT_MEASURED_V3: 8192,
62
+ }
54
63
  _OUTPUT_FIELDS = frozenset({"max_tokens", "max_completion_tokens", "max_output_tokens"})
55
64
 
56
65
 
@@ -72,13 +81,13 @@ def resolve(payload, target, policy, *, body, estimator_for):
72
81
  is the registered provider token counter, or ``None``.
73
82
  """
74
83
  selected = payload.get(MARKER, policy)
75
- if selected == CONTEXT_MEASURED_V2:
84
+ if selected in {CONTEXT_MEASURED_V2, CONTEXT_MEASURED_V3}:
76
85
  # Fit uses the assumed encoding of the provider body. The byte bound
77
86
  # returned by ``_resolve`` still prices the hold.
78
87
  return _resolve(
79
88
  payload,
80
89
  target,
81
- CONTEXT_MEASURED_V2,
90
+ selected,
82
91
  lambda _ignored: assumed_token_count(body(payload, target)),
83
92
  )
84
93
  if selected != CONTEXT_MEASURED:
@@ -161,6 +170,14 @@ def _resolve(payload, target, policy, estimator=None):
161
170
 
162
171
  if type(output_limit) is not int or output_limit > maximum:
163
172
  raise ValueError("token_limit")
164
- if output_limit < 1 or occupied + output_limit > context:
173
+ # GLiNER is an encoder: the returned extraction is not an autoregressive
174
+ # continuation in its input window. Keep output_limit for money/TPM bounds.
175
+ gliner_encoder = (
176
+ selected == CONTEXT_MEASURED_V3
177
+ and resolved.get("primitive", {}).get("kind") == "extract"
178
+ and str(getattr(target, "upstream_model_name", "")).startswith("fastino/gliner")
179
+ )
180
+ context_output = 0 if gliner_encoder else output_limit
181
+ if output_limit < 1 or occupied + context_output > context:
165
182
  raise ContextOverflow()
166
183
  return resolved, input_bound, output_limit
@@ -31,6 +31,7 @@ CHUNK_OPERATORS = {"merge_spans", "merge_records", "merge_labels"}
31
31
 
32
32
 
33
33
  UNALIGNED_MODES = frozenset({"fail", "drop"})
34
+ TOKEN_BOUNDARY_UTF8_V2 = "utf8-v2"
34
35
  # Quotations the kernel cannot place. In ``drop`` mode only these omit a record;
35
36
  # every other validation error still raises.
36
37
  UNPLACEABLE = ("ungrounded_span", "ambiguous_span")
@@ -348,6 +349,11 @@ def validate_config(op, inputs, config):
348
349
  from .components import semantic_contract
349
350
 
350
351
  arity, keys = OPERATORS[op]
352
+ if op == "chunk_text" and isinstance(config, dict) and "token_boundary" in config:
353
+ # Keep historical registries and unmarked plan bytes unchanged.
354
+ if config["token_boundary"] != TOKEN_BOUNDARY_UTF8_V2 or config.get("unit") != "tokens":
355
+ raise ValueError("invalid_kernel_configuration")
356
+ config = {k: v for k, v in config.items() if k != "token_boundary"}
351
357
  if op == "align_spans" and isinstance(config, dict) and "context_policy" in config:
352
358
  if not isinstance(config["context_policy"], str) or config["context_policy"] not in {
353
359
  "strict",
@@ -419,10 +425,15 @@ def _char_chunk_spans(text, size, overlap):
419
425
  ]
420
426
 
421
427
 
422
- def _token_pieces(text):
428
+ def _token_pieces(text, *, token_boundary=None):
423
429
  import tiktoken
424
430
 
425
431
  enc = tiktoken.get_encoding("o200k_base")
432
+ if token_boundary == TOKEN_BOUNDARY_UTF8_V2:
433
+ # A tokenizer token may contain only part of a UTF-8 character.
434
+ return [enc.decode_single_token_bytes(token) for token in enc.encode(text)]
435
+ if token_boundary is not None:
436
+ raise ValueError("invalid_kernel_configuration")
426
437
  pieces, cursor = [], 0
427
438
  for token in enc.encode(text):
428
439
  piece = enc.decode([token])
@@ -449,10 +460,57 @@ def _snap_end(text, start, end, floor):
449
460
  return best or end
450
461
 
451
462
 
452
- def _token_chunk_spans(text, size, overlap, pieces=None, limit=32):
463
+ def _utf8_token_chunk_spans(text, size, overlap, pieces, limit):
464
+ """Count real tokens, cutting only where token and UTF-8 boundaries coincide."""
465
+ from bisect import bisect_right
466
+
467
+ import tiktoken
468
+
469
+ if not text:
470
+ return [(0, 0)]
471
+ byte_offsets, byte_count = {0: 0}, 0
472
+ for index, character in enumerate(text):
473
+ byte_count += len(character.encode())
474
+ byte_offsets[byte_count] = index + 1
475
+ boundaries, encoded_offset = [(0, 0)], 0
476
+ for index, piece in enumerate(pieces):
477
+ if not isinstance(piece, bytes):
478
+ raise ValueError("invalid_kernel_configuration")
479
+ encoded_offset += len(piece)
480
+ if encoded_offset in byte_offsets:
481
+ boundaries.append((index + 1, byte_offsets[encoded_offset]))
482
+ token_offsets = [token for token, _ in boundaries]
483
+ spans, start_index = [], 0
484
+ encoding = tiktoken.get_encoding("o200k_base")
485
+ while start_index < len(boundaries) - 1:
486
+ start_token, start = boundaries[start_index]
487
+ end_index = bisect_right(token_offsets, start_token + size) - 1
488
+ # A substring can tokenize differently from the full source. Verify the
489
+ # emitted request instead of assuming a slice retains its tokenization.
490
+ while end_index > start_index:
491
+ end_token, end = boundaries[end_index]
492
+ if len(encoding.encode(text[start:end])) <= size:
493
+ break
494
+ end_index -= 1
495
+ if end_index == start_index:
496
+ raise ValueError("invalid_chunk_configuration")
497
+ spans.append((start, end))
498
+ if limit is not None and len(spans) > limit:
499
+ raise ValueError("chunk_limit")
500
+ if end == len(text):
501
+ break
502
+ start_index = max(start_index + 1, bisect_right(token_offsets, end_token - overlap) - 1)
503
+ return spans
504
+
505
+
506
+ def _token_chunk_spans(text, size, overlap, pieces=None, limit=32, *, token_boundary=None):
453
507
  """``pieces`` may be precomputed by callers that try many sizes on one text;
454
508
  ``limit=None`` lets context fit inspect chunk sizes beyond the kernel cap."""
455
- pieces = _token_pieces(text) if pieces is None else pieces
509
+ pieces = _token_pieces(text, token_boundary=token_boundary) if pieces is None else pieces
510
+ if token_boundary == TOKEN_BOUNDARY_UTF8_V2:
511
+ return _utf8_token_chunk_spans(text, size, overlap, pieces, limit)
512
+ if token_boundary is not None:
513
+ raise ValueError("invalid_kernel_configuration")
456
514
  count = _chunk_count(len(pieces), size, overlap)
457
515
  if limit is not None and count > limit:
458
516
  raise ValueError("chunk_limit")
@@ -668,7 +726,7 @@ def kernel(op, args, config, diagnostics=None):
668
726
  }
669
727
  size, overlap = config.get("size", 4096), config.get("overlap", 128)
670
728
  spans = (
671
- _token_chunk_spans(text, size, overlap)
729
+ _token_chunk_spans(text, size, overlap, token_boundary=config.get("token_boundary"))
672
730
  if config.get("unit") == "tokens"
673
731
  else _char_chunk_spans(text, size, overlap)
674
732
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: seldon-runtime
3
- Version: 0.1.1.dev0
3
+ Version: 0.1.1.dev1
4
4
  Summary: Standalone Seldon Functions interpreter and local execution client
5
5
  License-Expression: Apache-2.0
6
6
  Project-URL: Source, https://github.com/Deep-Insight-Labs/seldon-runtime
@@ -19,6 +19,8 @@ Requires-Dist: pytest>=8; extra == "dev"
19
19
  Requires-Dist: ruff==0.16.4; extra == "dev"
20
20
  Requires-Dist: build>=1; extra == "dev"
21
21
  Requires-Dist: twine>=6; extra == "dev"
22
+ Provides-Extra: schema
23
+ Requires-Dist: pydantic==2.14.4; extra == "schema"
22
24
  Dynamic: license-file
23
25
 
24
26
  # Seldon Runtime
@@ -32,27 +34,28 @@ Optimization and hosted comparison happen on Seldon. The runtime contains no
32
34
  optimizer, billing service, dashboard or server infrastructure. Its first local
33
35
  model adapter uses pinned GLiNER2 open weights for extraction and classification.
34
36
 
35
- This is a source preview. A source checkout or successful build does not establish
36
- PyPI publication, production feature activation, or quality on your own inputs.
37
+ The first preview, [\`0.1.1.dev0\`](https://pypi.org/project/seldon-runtime/0.1.1.dev0/),
38
+ is available on PyPI. Local execution requires a Seldon deployment with bundle
39
+ delivery enabled for your workspace.
37
40
 
38
41
  ## Install
39
42
 
40
43
  Python 3.11 or later is required. The base interpreter uses Pydantic, jsonschema
41
44
  and tiktoken. Local GLiNER inference additionally needs PyTorch and the model extra.
42
- Before publication, replace the package name below with a locally built wheel.
45
+ The commands below pin the published preview.
43
46
 
44
47
  On Linux, install CPU PyTorch explicitly to avoid downloading CUDA dependencies:
45
48
 
46
49
  ```sh
47
50
  python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
48
- python -m pip install 'seldon-runtime[gliner]'
51
+ python -m pip install 'seldon-runtime[gliner]==0.1.1.dev0'
49
52
  ```
50
53
 
51
54
  On macOS:
52
55
 
53
56
  ```sh
54
57
  python -m pip install torch
55
- python -m pip install 'seldon-runtime[gliner]'
58
+ python -m pip install 'seldon-runtime[gliner]==0.1.1.dev0'
56
59
  ```
57
60
 
58
61
  In a uv environment, use `uv pip install` for the same commands. In a Linux uv
@@ -60,7 +63,7 @@ project, persist the dedicated torch index:
60
63
 
61
64
  ```sh
62
65
  uv add torch --index pytorch=https://download.pytorch.org/whl/cpu
63
- uv add 'seldon-runtime[gliner]'
66
+ uv add 'seldon-runtime[gliner]==0.1.1.dev0'
64
67
  ```
65
68
 
66
69
  The model weights and tokenizer files download on first use. Cache the pinned
@@ -135,6 +138,88 @@ Always close the runner to stop background tasks and attempt a bounded flush.
135
138
 
136
139
  ## Development
137
140
 
141
+ ### Standalone compiler artifacts (unreleased)
142
+
143
+ The separate compiler-artifact reader executes locally compiled user-owned plans.
144
+ It does not use `Runner.load`, hosted Function IDs, a Seldon API key, refresh or
145
+ telemetry. This reader is under development; a public compiler/exporter is not yet
146
+ available. The existing hosted-bundle instructions above remain unchanged.
147
+
148
+ An export directory contains one `manifest.json`, at most 2 MiB. Plan and spec are
149
+ inline; no file paths, URLs, credentials or executable Python are supported. The
150
+ generated [JSON schema](schemas/compiler-artifact-v1.json) defines the envelope.
151
+ Schema generation uses a separately pinned development dependency because supported
152
+ Pydantic versions emit different schema descriptions. Runtime compatibility remains
153
+ `pydantic>=2.2`; all supported versions run the semantic reader tests. Regenerate in
154
+ a development environment with `python -m pip install '.[schema]'` followed by
155
+ `python -m scripts.export_artifact_schema`. CI checks the committed schema using
156
+ that generator's `--check` mode, independently of the runtime compatibility matrix.
157
+
158
+ The manifest freezes the compiler version, exact runtime version (`0.1.1.dev1`),
159
+ optimizer contract (v1–v8), evaluation semantics, instruction envelope, conditional
160
+ permission, plan/spec hashes, model requirements and a small evidence summary.
161
+ `manifest_digest` is the canonical runtime `digest` of all raw manifest fields
162
+ except `manifest_digest`. Plan/spec digests use their validated model `.digest`.
163
+ Omitted/default fields therefore follow the existing runtime serialization contract.
164
+
165
+ Supply endpoint configuration and credentials through your own transport, never
166
+ through the artifact. For example, given an independently configured asynchronous
167
+ `customer_provider(payload)` that returns decoded JSON output:
168
+
169
+ ```python
170
+ from seldon_runtime.artifact import ModelRequirements, RuntimeBinding, load_artifact
171
+
172
+ artifact = load_artifact("./selected-pipeline")
173
+ configured_model = ModelRequirements(
174
+ protocol="openai-chat-completions",
175
+ capabilities=("chat", "structured_output"),
176
+ context_length=8192,
177
+ max_output_tokens=256,
178
+ revision="deployment-1",
179
+ )
180
+ bindings = {"custom": RuntimeBinding(configured_model, customer_provider)}
181
+ result = await artifact.run({"text": "customer input"}, bindings=bindings, timeout=55)
182
+ ```
183
+
184
+ The binding keys must exactly cover the models used by the plan and its explicit
185
+ reference fallback. Configure capabilities and revision from your actual endpoint;
186
+ copying them from an untrusted artifact does not qualify a model. Protocol/revision
187
+ and output ceiling must match, capabilities must cover the requirements, and context
188
+ must be at least the declared size. The reader applies the frozen output/context
189
+ policy before invoking a provider; your transport still owns TLS, credential origin
190
+ binding, response-size limits and protocol decoding. Known transport failures use
191
+ `ProviderError`; untyped failures stop without automatic fallback or retry.
192
+
193
+ This initial handoff supports OpenAI-compatible chat steps and supported deterministic
194
+ operators, including versioned chunking/conditional graphs. Native `choice`/`extract`
195
+ adapters and research `generated_kernel` steps are explicitly rejected. A model
196
+ revision is an operator-supplied identity, not proof of immutable upstream weights.
197
+ Artifacts may contain sensitive prompts/spec text. Digest checks detect corruption,
198
+ not malicious replacement of both the content and its digest; trust the producer
199
+ separately. Linux/macOS filesystem APIs are used; Windows is not qualified.
200
+
201
+ The standalone fixture in `tests/fixtures/compiler-artifact` is generated from the
202
+ runtime test factory, pending a real compiler producer. Installed wheel/sdist probes
203
+ exercise its nonconstant execution through the real interpreter with a deterministic
204
+ provider callback. They do not qualify a live model, compiler selection quality or
205
+ the complete compiler-to-runtime lifecycle.
206
+
207
+ ### Interpreter development
208
+
209
+ The unreleased `0.1.1.dev1` readers support `optimizer-correctness-v8`.
210
+ New `chunk_text` steps may freeze `token_boundary: "utf8-v2"` with `unit: "tokens"`;
211
+ this counts tokenizer tokens without splitting UTF-8 characters. Steps without
212
+ the marker keep their historical chunk boundaries. The kernel still enforces its
213
+ 32-chunk cap, and hosted plans may set a lower fan-out cap.
214
+
215
+ `context_measured_v3` treats native Fastino GLiNER extraction as an encoder input
216
+ window. Its inherited LLM output allowance still bounds financial reservations,
217
+ response sizing and admission tokens; it no longer consumes encoder input context.
218
+ Other native protocols retain `context_measured_v2` context rules. These policies
219
+ are frozen identities: existing bundles and requests keep their saved behavior.
220
+ See [the changelog](CHANGELOG.md). Upgrade readers before creating these new
221
+ contracts; an old runtime must not serve a new marked plan or policy.
222
+
138
223
  ```sh
139
224
  python -m pip install -e '.[dev]'
140
225
  python -m ruff check .
@@ -1,11 +1,12 @@
1
- seldon_runtime/__init__.py,sha256=_2FjrY_GAv9Vz09Kg604JEmCtUxK2yijkL61JxaBJHk,102
1
+ seldon_runtime/__init__.py,sha256=oAbzbbpWLC3efp-ak-oQfu7NWtTQEa-8Wm9Tu9wYZZI,102
2
+ seldon_runtime/artifact.py,sha256=o5ByuYjXDn1LERGLZsrTdMeF2cdX5U07TfuJ1NHmFEM,12692
2
3
  seldon_runtime/attempt_bound.py,sha256=uXGBUBg09Uie75EfSTs_QfSn52tntoJDb8YQ6V_w9GY,1258
3
4
  seldon_runtime/components.py,sha256=y9l9MuYXNT3yuEWWlDDBec7Vb88Z0_5cKEZTuqyOpQE,12215
4
5
  seldon_runtime/conditional.py,sha256=x0Yg0l8T_KlhKvKLVYutbpNGow2vqZRnN9qfcu5jORQ,10867
5
- seldon_runtime/contract_versions.py,sha256=nzZ2LwZht0v_kyiBIwkj6b58L8MWY3uISvxGxyC_9FM,980
6
- seldon_runtime/contracts.py,sha256=ZF3qPLTPlM-_fDjkZ8FFmVuny85jDFU8_8w5Br1ZB00,34729
6
+ seldon_runtime/contract_versions.py,sha256=MnUAEwmnCiJ6O67WwbtOGi33PGZvIyN-O92TZwkek34,1037
7
+ seldon_runtime/contracts.py,sha256=LSgqYxQ4Fz5_hqCQWrjLj3KaGRNJASLj02hj9Valtl8,34760
7
8
  seldon_runtime/deadline.py,sha256=L8xBebhoLM2vlI0C5EhLbELflCaag_AgBD-AptKJDws,1879
8
- seldon_runtime/executor.py,sha256=3PcVNXp-nOo1QkLLnJOst4rDbHYreXMbf3-Ds7q8rzU,34896
9
+ seldon_runtime/executor.py,sha256=Wd6QXS3xm3BdRFjDyMj_C1jzFEXGSGZGIT2MPJv89Y8,35007
9
10
  seldon_runtime/gliner_normalize.py,sha256=V-29aGos27Ay6Eczz3AJ9yroEaZ7BSNw-v20ZqKsjs8,11384
10
11
  seldon_runtime/instruction_envelope.py,sha256=S-riu21kqicDyPnZgKPlpWH_J7IpNo_AGRJ4Jnn1zq4,2719
11
12
  seldon_runtime/json_pointer.py,sha256=r__ji3JyTNDn-bGfc9oVIoA1FAq2UBvbQ-05UBi6_8g,849
@@ -13,18 +14,18 @@ seldon_runtime/local.py,sha256=I9sKUsSZsTjEn4fDrjCzfzscPjb0xXBijhWXjIR6hbM,6873
13
14
  seldon_runtime/local_models.py,sha256=ubqPSabFaXr7E9_1TmMRjl09M20SHqCZmxNqbr_Fo_0,1210
14
15
  seldon_runtime/local_telemetry.py,sha256=fd2u7d7Fr6OOPS50CkmS5tSAXT0DfWrGE-X-Izwa0mw,3405
15
16
  seldon_runtime/native_schema.py,sha256=M2V3FdlGRxeBJ6RjGTb8iLcqmmMhclK6Auh1nh8ic1M,1515
16
- seldon_runtime/output_budget.py,sha256=kmP9mZlawRT7sQUrgdnTOPGjcNoTNjb9fmYlVlhwx-s,7442
17
+ seldon_runtime/output_budget.py,sha256=1TD-t2Bstjy7BGQF89M88KgkIzhyZEw0L9a2VYs4Wdo,8219
17
18
  seldon_runtime/program_validation.py,sha256=s9gF1foKC8j6TVxMfVGdw-u5m4qlPKZ20PS1PDscKVc,6044
18
19
  seldon_runtime/provider_error.py,sha256=IM9H1rDFN-obkDlzDr0f-CXbf5RsYu5jXsj3chTNX3Y,1689
19
20
  seldon_runtime/research_kernels.py,sha256=cMOSYJQD67ngbhcCvkq6pNxrHrgAluBgcMxICo9n-Xw,2162
20
21
  seldon_runtime/runner.py,sha256=AAcZoFr4caUT6BEtjCelc58zvul2wT2hZOAigE2_g9k,20911
21
- seldon_runtime/semantic.py,sha256=F7_ZYEL2t1_2RxfyMIj-Ged6jl8nC3Xb39SWfaMmTbg,27277
22
+ seldon_runtime/semantic.py,sha256=MuLD4YQ8BkQwSVbiy258XrW_G9wCqmq763fkDYRs7a8,30171
22
23
  seldon_runtime/telemetry.py,sha256=2ik9i1vTnTx5U42tPMhsmDC_EcernSov_dxgzAF04uE,6984
23
24
  seldon_runtime/templates.py,sha256=zp48gE-ZEsvd3aU-bH8W7d8-MtS35AqzmSQtpuz7W-4,4379
24
25
  seldon_runtime/tool_wire.py,sha256=s2x3TgbjP26hwe_twAS-ArlbLhEXUQUpohK4VoeXgwE,4279
25
- seldon_runtime-0.1.1.dev0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
26
- seldon_runtime-0.1.1.dev0.dist-info/licenses/NOTICE,sha256=d6FAH8kHaW9m59M6DJFVNLp1y1CkiSmZs3FiYzoWtMk,428
27
- seldon_runtime-0.1.1.dev0.dist-info/METADATA,sha256=2JRIAKwcuOOH2oHPbN7rZ2el6OwFaRyWzyULHUMNpGY,7471
28
- seldon_runtime-0.1.1.dev0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
29
- seldon_runtime-0.1.1.dev0.dist-info/top_level.txt,sha256=OIOoWE_VYJXj3yVmPF3EeSqNJ5DNWZbmSEWB5JMLcTU,15
30
- seldon_runtime-0.1.1.dev0.dist-info/RECORD,,
26
+ seldon_runtime-0.1.1.dev1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
27
+ seldon_runtime-0.1.1.dev1.dist-info/licenses/NOTICE,sha256=d6FAH8kHaW9m59M6DJFVNLp1y1CkiSmZs3FiYzoWtMk,428
28
+ seldon_runtime-0.1.1.dev1.dist-info/METADATA,sha256=GEWRPdp1y0ajEBTOB7OODu6twfMfmqMdAIRsWHVzHJo,12521
29
+ seldon_runtime-0.1.1.dev1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ seldon_runtime-0.1.1.dev1.dist-info/top_level.txt,sha256=OIOoWE_VYJXj3yVmPF3EeSqNJ5DNWZbmSEWB5JMLcTU,15
31
+ seldon_runtime-0.1.1.dev1.dist-info/RECORD,,