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.
- seldon_runtime/__init__.py +3 -0
- seldon_runtime/attempt_bound.py +35 -0
- seldon_runtime/components.py +316 -0
- seldon_runtime/conditional.py +277 -0
- seldon_runtime/contract_versions.py +15 -0
- seldon_runtime/contracts.py +859 -0
- seldon_runtime/deadline.py +51 -0
- seldon_runtime/executor.py +852 -0
- seldon_runtime/gliner_normalize.py +274 -0
- seldon_runtime/instruction_envelope.py +57 -0
- seldon_runtime/json_pointer.py +26 -0
- seldon_runtime/local.py +173 -0
- seldon_runtime/local_models.py +27 -0
- seldon_runtime/local_telemetry.py +108 -0
- seldon_runtime/native_schema.py +33 -0
- seldon_runtime/output_budget.py +166 -0
- seldon_runtime/program_validation.py +137 -0
- seldon_runtime/provider_error.py +42 -0
- seldon_runtime/research_kernels.py +77 -0
- seldon_runtime/runner.py +544 -0
- seldon_runtime/semantic.py +684 -0
- seldon_runtime/telemetry.py +197 -0
- seldon_runtime/templates.py +109 -0
- seldon_runtime/tool_wire.py +116 -0
- seldon_runtime-0.1.1.dev0.dist-info/METADATA +178 -0
- seldon_runtime-0.1.1.dev0.dist-info/RECORD +30 -0
- seldon_runtime-0.1.1.dev0.dist-info/WHEEL +5 -0
- seldon_runtime-0.1.1.dev0.dist-info/licenses/LICENSE +202 -0
- seldon_runtime-0.1.1.dev0.dist-info/licenses/NOTICE +9 -0
- seldon_runtime-0.1.1.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Native record-schema translation and typed native contract failure codes."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def structured_schema(schema):
|
|
5
|
+
"""Translate only representable record schemas; never flatten relationships."""
|
|
6
|
+
if schema.get("type") != "object" or not schema.get("properties"):
|
|
7
|
+
raise ValueError("unsupported_native_schema")
|
|
8
|
+
structures = {}
|
|
9
|
+
for name, collection in schema["properties"].items():
|
|
10
|
+
record = collection.get("items", {})
|
|
11
|
+
if (
|
|
12
|
+
collection.get("type") != "array"
|
|
13
|
+
or record.get("type") != "object"
|
|
14
|
+
or not record.get("properties")
|
|
15
|
+
):
|
|
16
|
+
raise ValueError("unsupported_native_schema")
|
|
17
|
+
fields = []
|
|
18
|
+
for field, value in record["properties"].items():
|
|
19
|
+
if value.get("type") not in ("string", ["string", "null"], ["null", "string"]):
|
|
20
|
+
raise ValueError("unsupported_native_schema")
|
|
21
|
+
fields.append(
|
|
22
|
+
{"name": field, "dtype": "str", "description": value.get("description", field)}
|
|
23
|
+
)
|
|
24
|
+
structures[name] = fields
|
|
25
|
+
return {"structures": structures}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Typed, deterministic native contract failures (W6). A malformed response stays
|
|
29
|
+
# ``invalid_provider_output``; none of these is a provider outage or a retry signal.
|
|
30
|
+
SCHEMA_MISMATCH = "native_output_schema_mismatch"
|
|
31
|
+
INVALID_GROUNDED_SPAN = "invalid_grounded_span"
|
|
32
|
+
UNGROUNDED_QUOTATION = "ungrounded_quotation"
|
|
33
|
+
NATIVE_CONTRACT_ERRORS = frozenset({SCHEMA_MISMATCH, INVALID_GROUNDED_SPAN, UNGROUNDED_QUOTATION})
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Resolve compiler output allowance before identity, reservation and dispatch.
|
|
2
|
+
|
|
3
|
+
Legacy request policy preserves the existing wire request and token estimate.
|
|
4
|
+
Full-request policies budget the complete request and use the selected offering's
|
|
5
|
+
remaining context:
|
|
6
|
+
|
|
7
|
+
* ``endpoint_max`` allows the endpoint's full ``max_output_tokens``.
|
|
8
|
+
* ``bounded_8192`` allows at most 8,192 output tokens (reasoning included where
|
|
9
|
+
the endpoint counts it as output).
|
|
10
|
+
* ``context_measured_v1`` sizes like ``bounded_8192`` but decides context fit
|
|
11
|
+
from a provider-published token count registered for the offering pin. A
|
|
12
|
+
native primitive's declared allowance must then fit unclamped. Without a
|
|
13
|
+
registered estimator it makes the byte decision and refuses
|
|
14
|
+
``context_unverified``. The byte bound still prices the hold and TPM estimate.
|
|
15
|
+
|
|
16
|
+
Native primitives retain their bounded request allowance, capped to their own
|
|
17
|
+
endpoint (and to the policy ceiling) when inherited from a full-request LLM call.
|
|
18
|
+
|
|
19
|
+
A policy value is part of frozen run/spec identity. Never change the ceiling of
|
|
20
|
+
an existing policy; add a new policy value instead.
|
|
21
|
+
|
|
22
|
+
Pure leaf (stdlib + tiktoken + ``contracts``) so the staged ``seldon_runtime``
|
|
23
|
+
wheel refuses exactly the requests the hosted transport refuses. Server lookups
|
|
24
|
+
(the wire body and a registered token counter) are passed in by ``output_limits``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from copy import deepcopy
|
|
28
|
+
|
|
29
|
+
from .contracts import canonical
|
|
30
|
+
|
|
31
|
+
REQUEST = "request"
|
|
32
|
+
ENDPOINT_MAX = "endpoint_max"
|
|
33
|
+
BOUNDED_8192 = "bounded_8192"
|
|
34
|
+
CONTEXT_MEASURED = "context_measured_v1"
|
|
35
|
+
CONTEXT_MEASURED_V2 = "context_measured_v2"
|
|
36
|
+
MARKER = "seldon_output_token_policy"
|
|
37
|
+
# Internal key carrying a capability run's frozen wire profile into fit and
|
|
38
|
+
# admission (the request depends on the host's state form). Never sent.
|
|
39
|
+
PROFILE_KEY = "seldon_wire_profile"
|
|
40
|
+
# Assumed tokenizer for models that have not published one. The 1.15 factor and
|
|
41
|
+
# the flat 32-token margin keep the estimate above an OpenAI encoding of the
|
|
42
|
+
# same text. It decides fit only; holds stay on the byte bound.
|
|
43
|
+
ASSUMED_TOKEN_ESTIMATE = "o200k_base_assumed"
|
|
44
|
+
ASSUMED_TOKEN_MARGIN = 1.15
|
|
45
|
+
ASSUMED_TOKEN_PAD = 32
|
|
46
|
+
# Policies that size the output allowance themselves instead of honoring the
|
|
47
|
+
# request's ``max_tokens``. Callers use this set rather than comparing to one value.
|
|
48
|
+
FULL_REQUEST_POLICIES = frozenset(
|
|
49
|
+
{ENDPOINT_MAX, BOUNDED_8192, CONTEXT_MEASURED, CONTEXT_MEASURED_V2}
|
|
50
|
+
)
|
|
51
|
+
POLICIES = frozenset({REQUEST, *FULL_REQUEST_POLICIES})
|
|
52
|
+
# Policy ceiling below the endpoint maximum. ``endpoint_max`` has none.
|
|
53
|
+
_CEILINGS = {BOUNDED_8192: 8192, CONTEXT_MEASURED: 8192, CONTEXT_MEASURED_V2: 8192}
|
|
54
|
+
_OUTPUT_FIELDS = frozenset({"max_tokens", "max_completion_tokens", "max_output_tokens"})
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def assumed_token_count(value) -> int:
|
|
58
|
+
"""Upper estimate of provider tokens for ``value`` using ``o200k_base``."""
|
|
59
|
+
import math
|
|
60
|
+
|
|
61
|
+
import tiktoken
|
|
62
|
+
|
|
63
|
+
text = value if isinstance(value, str) else canonical(value)
|
|
64
|
+
counted = len(tiktoken.get_encoding("o200k_base").encode(text))
|
|
65
|
+
return math.ceil(counted * ASSUMED_TOKEN_MARGIN) + ASSUMED_TOKEN_PAD
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def resolve(payload, target, policy, *, body, estimator_for):
|
|
69
|
+
"""``output_limits.resolve_payload`` with its server lookups passed in.
|
|
70
|
+
|
|
71
|
+
``body(payload, target)`` is the JSON the provider receives; ``estimator_for(target)``
|
|
72
|
+
is the registered provider token counter, or ``None``.
|
|
73
|
+
"""
|
|
74
|
+
selected = payload.get(MARKER, policy)
|
|
75
|
+
if selected == CONTEXT_MEASURED_V2:
|
|
76
|
+
# Fit uses the assumed encoding of the provider body. The byte bound
|
|
77
|
+
# returned by ``_resolve`` still prices the hold.
|
|
78
|
+
return _resolve(
|
|
79
|
+
payload,
|
|
80
|
+
target,
|
|
81
|
+
CONTEXT_MEASURED_V2,
|
|
82
|
+
lambda _ignored: assumed_token_count(body(payload, target)),
|
|
83
|
+
)
|
|
84
|
+
if selected != CONTEXT_MEASURED:
|
|
85
|
+
return _resolve(payload, target, selected)
|
|
86
|
+
estimator = estimator_for(target)
|
|
87
|
+
if estimator is None:
|
|
88
|
+
try:
|
|
89
|
+
return _resolve(payload, target, BOUNDED_8192)
|
|
90
|
+
except ContextOverflow:
|
|
91
|
+
raise ValueError("context_unverified") from None
|
|
92
|
+
return _resolve(payload, target, CONTEXT_MEASURED, estimator)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ContextOverflow(ValueError):
|
|
96
|
+
"""The request does not fit the endpoint context; other limits are separate."""
|
|
97
|
+
|
|
98
|
+
def __init__(self):
|
|
99
|
+
super().__init__("token_limit")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _resolve(payload, target, policy, estimator=None):
|
|
103
|
+
omitted_limit = payload.get(MARKER) == REQUEST and "max_tokens" not in payload
|
|
104
|
+
resolved = deepcopy(payload)
|
|
105
|
+
resolved.pop(MARKER, None)
|
|
106
|
+
resolved.pop(PROFILE_KEY, None)
|
|
107
|
+
selected = policy
|
|
108
|
+
maximum = getattr(target, "max_output_tokens", None)
|
|
109
|
+
context = getattr(target, "context_length", None)
|
|
110
|
+
if (
|
|
111
|
+
selected not in POLICIES
|
|
112
|
+
or type(maximum) is not int
|
|
113
|
+
or maximum < 1
|
|
114
|
+
or type(context) is not int
|
|
115
|
+
or context < 1
|
|
116
|
+
):
|
|
117
|
+
raise ValueError("token_limit")
|
|
118
|
+
|
|
119
|
+
ceiling = min(maximum, _CEILINGS.get(selected, maximum))
|
|
120
|
+
framing = 256 * len(resolved["messages"])
|
|
121
|
+
if selected in FULL_REQUEST_POLICIES and "primitive" not in resolved:
|
|
122
|
+
# Include schema/tool instructions and every other input-bearing field.
|
|
123
|
+
complete_input = {k: v for k, v in resolved.items() if k not in _OUTPUT_FIELDS}
|
|
124
|
+
input_bound = len(canonical(complete_input).encode()) + framing
|
|
125
|
+
occupied = estimator(complete_input) if estimator else input_bound
|
|
126
|
+
output_limit = min(ceiling, context - occupied)
|
|
127
|
+
for alias in _OUTPUT_FIELDS - {"max_tokens"}:
|
|
128
|
+
resolved.pop(alias, None)
|
|
129
|
+
resolved["max_tokens"] = output_limit
|
|
130
|
+
else:
|
|
131
|
+
# Compiler request contracts use max_tokens only. Other aliases would
|
|
132
|
+
# permit dispatch to exceed the amount accounted for by the old path.
|
|
133
|
+
if any(alias in resolved for alias in _OUTPUT_FIELDS - {"max_tokens"}):
|
|
134
|
+
raise ValueError("token_limit")
|
|
135
|
+
input_bound = len(canonical(resolved["messages"]).encode()) + framing
|
|
136
|
+
if resolved.get("tools") is not None:
|
|
137
|
+
# Tool schemas are paid input; old content-only request bounds stay frozen.
|
|
138
|
+
input_bound = (
|
|
139
|
+
len(
|
|
140
|
+
canonical(
|
|
141
|
+
{k: v for k, v in resolved.items() if k not in _OUTPUT_FIELDS}
|
|
142
|
+
).encode()
|
|
143
|
+
)
|
|
144
|
+
+ framing
|
|
145
|
+
)
|
|
146
|
+
if "primitive" in resolved:
|
|
147
|
+
input_bound += len(canonical(resolved["primitive"]).encode())
|
|
148
|
+
occupied = estimator(resolved) if estimator else input_bound
|
|
149
|
+
# Omission is a frozen request choice: reserve the endpoint's possible
|
|
150
|
+
# output without adding a generation option the caller never supplied.
|
|
151
|
+
output_limit = resolved.get(
|
|
152
|
+
"max_tokens", min(maximum, context - occupied) if omitted_limit else 2048
|
|
153
|
+
)
|
|
154
|
+
if selected in FULL_REQUEST_POLICIES:
|
|
155
|
+
if type(output_limit) is not int or output_limit < 1:
|
|
156
|
+
raise ValueError("token_limit")
|
|
157
|
+
output_limit = min(output_limit, ceiling)
|
|
158
|
+
if not estimator:
|
|
159
|
+
output_limit = min(output_limit, context - input_bound)
|
|
160
|
+
resolved["max_tokens"] = output_limit
|
|
161
|
+
|
|
162
|
+
if type(output_limit) is not int or output_limit > maximum:
|
|
163
|
+
raise ValueError("token_limit")
|
|
164
|
+
if output_limit < 1 or occupied + output_limit > context:
|
|
165
|
+
raise ContextOverflow()
|
|
166
|
+
return resolved, input_bound, output_limit
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Plan graph, kernel configuration and schema-path validation before evaluation."""
|
|
2
|
+
|
|
3
|
+
from .contracts import reference
|
|
4
|
+
from .semantic import OPERATORS, validate_config
|
|
5
|
+
from .tool_wire import request_schema
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def validate_program(plan, spec):
|
|
9
|
+
"""Validate graph, kernel configuration and known schema paths before evaluation."""
|
|
10
|
+
schemas = {"input": spec.input_schema}
|
|
11
|
+
calls = {c.id: c for c in spec.calls}
|
|
12
|
+
completed = {}
|
|
13
|
+
conditional = plan.version == "function-plan-v5"
|
|
14
|
+
if conditional:
|
|
15
|
+
from .conditional import (
|
|
16
|
+
binding_states,
|
|
17
|
+
predicate_refs,
|
|
18
|
+
validate_graph,
|
|
19
|
+
validate_predicate_schema,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
validate_graph(plan)
|
|
23
|
+
call_states = binding_states(plan, spec)
|
|
24
|
+
arity = {
|
|
25
|
+
"copy": 1,
|
|
26
|
+
"parse_json": 1,
|
|
27
|
+
"lookup": 1,
|
|
28
|
+
"compare": 2,
|
|
29
|
+
"filter": 1,
|
|
30
|
+
"map": 1,
|
|
31
|
+
"decimal_sum": 1,
|
|
32
|
+
"decimal_add": 2,
|
|
33
|
+
"decimal_multiply": 2,
|
|
34
|
+
}
|
|
35
|
+
for step in plan.steps:
|
|
36
|
+
if step.op == "generated_kernel":
|
|
37
|
+
from .research_kernels import require
|
|
38
|
+
|
|
39
|
+
require().validate_step(step)
|
|
40
|
+
if conditional:
|
|
41
|
+
completed = call_states[step.id]
|
|
42
|
+
if step.op in OPERATORS:
|
|
43
|
+
validate_config(step.op, step.inputs, step.config)
|
|
44
|
+
if (
|
|
45
|
+
step.op == "align_spans"
|
|
46
|
+
and step.config.get("context_policy") == "hint"
|
|
47
|
+
and (spec.evaluation is None or spec.evaluation.span_context_policy != "hint")
|
|
48
|
+
):
|
|
49
|
+
raise ValueError("span_context_hint_not_authorized")
|
|
50
|
+
if step.op in {*arity, "object"}:
|
|
51
|
+
from .executor import validate_kernel_config
|
|
52
|
+
|
|
53
|
+
validate_kernel_config(step.op, step.config)
|
|
54
|
+
if step.op in arity and len(step.inputs) != arity[step.op]:
|
|
55
|
+
raise ValueError("invalid_kernel_inputs")
|
|
56
|
+
if step.op == "object":
|
|
57
|
+
fields = step.config.get("fields")
|
|
58
|
+
if (
|
|
59
|
+
not isinstance(fields, list)
|
|
60
|
+
or len(fields) != len(step.inputs)
|
|
61
|
+
or any(not isinstance(f, str) for f in fields)
|
|
62
|
+
or len(set(fields)) != len(fields)
|
|
63
|
+
):
|
|
64
|
+
raise ValueError("invalid_kernel_configuration")
|
|
65
|
+
if step.op == "lookup" and not isinstance(step.config.get("key"), str):
|
|
66
|
+
raise ValueError("invalid_kernel_configuration")
|
|
67
|
+
if step.op == "compare" and step.config.get("operator", "eq") not in {"eq", "lt"}:
|
|
68
|
+
raise ValueError("invalid_kernel_configuration")
|
|
69
|
+
if step.op in {"map", "filter"}:
|
|
70
|
+
reference("input#" + step.config.get("path", "invalid"))
|
|
71
|
+
if step.op == "filter" and "equals" not in step.config:
|
|
72
|
+
raise ValueError("invalid_kernel_configuration")
|
|
73
|
+
refs = list(step.inputs)
|
|
74
|
+
if conditional:
|
|
75
|
+
refs.extend((step.incoming or {}).values())
|
|
76
|
+
if step.predicate:
|
|
77
|
+
refs.extend(predicate_refs(step.predicate))
|
|
78
|
+
if step.op in {"llm", "choice", "extract"}:
|
|
79
|
+
if step.call not in calls:
|
|
80
|
+
raise ValueError("unknown_call")
|
|
81
|
+
for b in spec.bindings:
|
|
82
|
+
if b.call == step.call:
|
|
83
|
+
root, path = reference(b.source)
|
|
84
|
+
if root != "input" and root not in completed:
|
|
85
|
+
raise ValueError("missing_intermediate_call")
|
|
86
|
+
refs.append((completed.get(root, root)) + "#" + path)
|
|
87
|
+
if step.output_binding == "call":
|
|
88
|
+
completed[step.call] = step.id
|
|
89
|
+
resolved_schemas = {}
|
|
90
|
+
for ref in refs:
|
|
91
|
+
root, path = reference(ref)
|
|
92
|
+
schema = schemas.get(root)
|
|
93
|
+
for raw in path.split("/")[1:] if path else []:
|
|
94
|
+
if not schema:
|
|
95
|
+
break
|
|
96
|
+
key = raw.replace("~1", "/").replace("~0", "~")
|
|
97
|
+
if schema.get("type") == "array":
|
|
98
|
+
if not key.isdigit():
|
|
99
|
+
raise ValueError("invalid_array_index")
|
|
100
|
+
schema = schema.get("items")
|
|
101
|
+
else:
|
|
102
|
+
properties = schema.get("properties", {})
|
|
103
|
+
if key not in properties and schema.get("additionalProperties") is False:
|
|
104
|
+
raise ValueError("missing_binding")
|
|
105
|
+
schema = properties.get(key)
|
|
106
|
+
resolved_schemas[ref] = schema
|
|
107
|
+
if step.op == "generated_kernel":
|
|
108
|
+
require().validate_step(step, resolved_schemas.get(step.inputs[0]))
|
|
109
|
+
if conditional and step.predicate:
|
|
110
|
+
validate_predicate_schema(step.predicate, resolved_schemas)
|
|
111
|
+
if conditional and step.op == "merge":
|
|
112
|
+
from .components import reject_incompatible_schema
|
|
113
|
+
|
|
114
|
+
for ref in step.incoming.values():
|
|
115
|
+
reject_incompatible_schema(resolved_schemas.get(ref), step.output_schema)
|
|
116
|
+
if step.op in OPERATORS:
|
|
117
|
+
from .components import reject_incompatible_schema, semantic_contract
|
|
118
|
+
|
|
119
|
+
required_inputs = semantic_contract(step.op)["input_schema"]["prefixItems"]
|
|
120
|
+
for ref, required in zip(step.inputs, required_inputs, strict=True):
|
|
121
|
+
reject_incompatible_schema(resolved_schemas.get(ref), required)
|
|
122
|
+
produced = step.output_schema or (
|
|
123
|
+
semantic_contract(step.op)["output_schema"]
|
|
124
|
+
if step.op in OPERATORS
|
|
125
|
+
else request_schema(calls[step.call].model_dump(exclude_none=True))
|
|
126
|
+
if step.call in calls
|
|
127
|
+
else None
|
|
128
|
+
)
|
|
129
|
+
if conditional and step.op == "branch":
|
|
130
|
+
produced = {"type": "boolean"}
|
|
131
|
+
if conditional and step.op in {"copy", "return"} and not produced:
|
|
132
|
+
produced = resolved_schemas.get(step.inputs[0])
|
|
133
|
+
# A fan-out step returns one row per chunk. Per-item schema stays on the step.
|
|
134
|
+
if step.over:
|
|
135
|
+
produced = {"type": "array", "maxItems": 32, "items": {"type": "object"}}
|
|
136
|
+
schemas[step.id] = produced
|
|
137
|
+
return plan
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Client-safe upstream provider failure shared by the router and the interpreter."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ProviderError(Exception):
|
|
7
|
+
"""An upstream failure mapped to a client-safe code/message.
|
|
8
|
+
|
|
9
|
+
Never carries the raw upstream body, URL, headers, or keys (invariant I6).
|
|
10
|
+
``status_code`` is the HTTP status the route should return.
|
|
11
|
+
``category`` is an optional typed failure class used by the executor for
|
|
12
|
+
throttle/fallback decisions (Bedrock Phase 2+): throttled | timeout |
|
|
13
|
+
access | invalid_request | unavailable | internal.
|
|
14
|
+
``provider_dispatched`` distinguishes wrapper admission failures from an
|
|
15
|
+
upstream call so terminal client denials and attempt evidence remain exact.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
status_code: int,
|
|
21
|
+
code: str,
|
|
22
|
+
message: str,
|
|
23
|
+
*,
|
|
24
|
+
category: str | None = None,
|
|
25
|
+
retry_after_seconds: int | None = None,
|
|
26
|
+
upstream_status: int | None = None,
|
|
27
|
+
upstream_code: str | None = None,
|
|
28
|
+
provider_dispatched: bool | None = None,
|
|
29
|
+
transport_evidence: dict[str, Any] | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status_code = status_code
|
|
33
|
+
self.code = code
|
|
34
|
+
self.message = message
|
|
35
|
+
self.category = category
|
|
36
|
+
self.retry_after_seconds = retry_after_seconds
|
|
37
|
+
self.upstream_status = upstream_status
|
|
38
|
+
self.upstream_code = upstream_code
|
|
39
|
+
self.provider_dispatched = provider_dispatched
|
|
40
|
+
# Sanitized physical-attempt evidence (stage, transmission state, status);
|
|
41
|
+
# never upstream bodies, URLs, headers or credentials.
|
|
42
|
+
self.transport_evidence = transport_evidence
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Explicit process-local research seam; normal compilation/serving cannot execute code.
|
|
2
|
+
|
|
3
|
+
Only the isolated study worker installs a context. Artifact identity remains in
|
|
4
|
+
serialized steps, while executable source stays in its run-scoped artifact store.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from contextvars import ContextVar
|
|
11
|
+
from decimal import Decimal
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
VERSION = "generated-kernel-v1"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ResearchRuntime(Protocol):
|
|
18
|
+
synthesis_enabled: bool
|
|
19
|
+
|
|
20
|
+
def validate_step(self, step, input_schema=None) -> None: ...
|
|
21
|
+
|
|
22
|
+
def compute_bound(self, plan, inputs: int) -> tuple[Decimal, float]: ...
|
|
23
|
+
|
|
24
|
+
async def invoke(self, step, value: Any, *, provider) -> Any:
|
|
25
|
+
"""Await isolated execution, including admission and settled resource receipt."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
async def run_agent(self, legacy, **kwargs): ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_CURRENT: ContextVar[ResearchRuntime | None] = ContextVar("kernel_research_runtime", default=None)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def active():
|
|
35
|
+
return _CURRENT.get()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@contextmanager
|
|
39
|
+
def installed(runtime):
|
|
40
|
+
token = _CURRENT.set(runtime)
|
|
41
|
+
try:
|
|
42
|
+
yield runtime
|
|
43
|
+
finally:
|
|
44
|
+
_CURRENT.reset(token)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def generated(plan):
|
|
48
|
+
return any(step.op == "generated_kernel" for step in plan.steps)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def require():
|
|
52
|
+
runtime = active()
|
|
53
|
+
if runtime is None or not runtime.synthesis_enabled:
|
|
54
|
+
raise ValueError("generated_kernel_research_only")
|
|
55
|
+
return runtime
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def bound(plan, inputs=1):
|
|
59
|
+
if not generated(plan):
|
|
60
|
+
return Decimal(0), 0.0
|
|
61
|
+
return require().compute_bound(plan, inputs)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def validate_config(step):
|
|
65
|
+
if (
|
|
66
|
+
step.config.get("version") != VERSION
|
|
67
|
+
or set(step.config) != {"version", "revision_id"}
|
|
68
|
+
or not isinstance(step.config.get("revision_id"), str)
|
|
69
|
+
or len(step.config["revision_id"]) != 64
|
|
70
|
+
or any(c not in "0123456789abcdef" for c in step.config["revision_id"])
|
|
71
|
+
or len(step.inputs) != 1
|
|
72
|
+
or step.model is not None
|
|
73
|
+
or step.call is not None
|
|
74
|
+
or step.over is not None
|
|
75
|
+
or step.output_schema is None
|
|
76
|
+
):
|
|
77
|
+
raise ValueError("invalid_generated_kernel_contract")
|