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,3 @@
1
+ """Standalone Seldon Functions interpreter and local execution client."""
2
+
3
+ __version__ = "0.1.1.dev0"
@@ -0,0 +1,35 @@
1
+ """Per-step and whole-program provider-attempt bounds for a plan."""
2
+
3
+
4
+ def _step_attempts(step, version):
5
+ paid = (
6
+ 3
7
+ if step.op == "choice" and step.config.get("mode") == "pairs"
8
+ else int(step.op in {"llm", "choice", "extract"})
9
+ )
10
+ if version == "function-plan-v4" and step.over:
11
+ chunks = step.max_chunks or 16
12
+ if not 1 <= chunks <= 16:
13
+ raise ValueError("chunk_limit")
14
+ return paid * chunks
15
+ return paid
16
+
17
+
18
+ def program_attempt_bound(plan, spec):
19
+ if plan.version == "function-plan-v5":
20
+ from .conditional import max_path
21
+
22
+ primary = max_path(plan, lambda step: _step_attempts(step, plan.version))
23
+ else:
24
+ primary = sum(_step_attempts(step, plan.version) for step in plan.steps)
25
+ fallback = len(spec.calls) if plan.fallback else 0
26
+ bound = primary + fallback
27
+ if plan.version == "function-plan-v4":
28
+ if primary > 40:
29
+ raise ValueError("call_limit")
30
+ return bound
31
+ if bound > (8 if plan.version in {"function-plan-v3", "function-plan-v5"} else 6):
32
+ raise ValueError("call_limit")
33
+ if plan.version in {"function-plan-v3", "function-plan-v5"} and primary > 5:
34
+ raise ValueError("call_limit")
35
+ return bound
@@ -0,0 +1,316 @@
1
+ """Execution schema and native-step validation; planner registries stay server-side."""
2
+
3
+ from .semantic import OPERATORS
4
+
5
+
6
+ def reject_incompatible_schema(actual, required):
7
+ """Reject provable mismatches in the supported structural schema fragment.
8
+
9
+ Unknown/conditional schemas remain guarded by runtime validation. This is
10
+ not a claim of arbitrary JSON Schema subsumption or semantic equivalence.
11
+ """
12
+ if actual is False:
13
+ raise ValueError("incompatible_component_inputs")
14
+ if not isinstance(actual, dict) or not isinstance(required, dict):
15
+ return
16
+
17
+ def types(schema):
18
+ value = schema.get("type")
19
+ result = set(value if isinstance(value, list) else [value]) if value else set()
20
+ if "integer" in result:
21
+ result.add("number")
22
+ return result
23
+
24
+ if types(actual) and types(required) and not types(actual) & types(required):
25
+ raise ValueError("incompatible_component_inputs")
26
+ if "enum" in actual and "enum" in required:
27
+ if not any(v in required["enum"] for v in actual["enum"]):
28
+ raise ValueError("incompatible_component_inputs")
29
+ if required.get("type") == "array":
30
+ reject_incompatible_schema(actual.get("items"), required.get("items"))
31
+ if required.get("type") == "object":
32
+ properties = actual.get("properties", {})
33
+ for key in required.get("required", []):
34
+ if key not in properties and actual.get("additionalProperties") is False:
35
+ raise ValueError("incompatible_component_inputs")
36
+ for key, target in required.get("properties", {}).items():
37
+ if key in properties:
38
+ reject_incompatible_schema(properties[key], target)
39
+
40
+
41
+ def collection(properties, maximum, required=None):
42
+ return {
43
+ "type": "array",
44
+ "maxItems": maximum,
45
+ "items": {
46
+ "type": "object",
47
+ "properties": properties,
48
+ "required": required or list(properties),
49
+ },
50
+ }
51
+
52
+
53
+ STRING = {"type": "string"}
54
+
55
+ MENTIONS = collection({"id": STRING, "text": STRING}, 32)
56
+
57
+ CATALOG = collection(
58
+ {"id": STRING, "name": STRING, "aliases": {"type": "array", "maxItems": 32, "items": STRING}},
59
+ 500,
60
+ ["id", "name"],
61
+ )
62
+
63
+ PAIRS = collection({"id": STRING, "mention_id": STRING, "candidate_id": STRING}, 160)
64
+
65
+ DECISIONS = collection({"id": STRING, "match": {"type": "boolean"}}, 160)
66
+
67
+ RETRIEVAL = {
68
+ "type": "object",
69
+ "properties": {
70
+ "pairs": PAIRS,
71
+ "catalog_id": STRING,
72
+ "omitted_pairs": {"type": "integer", "minimum": 0},
73
+ "mention_ids": {"type": "array", "maxItems": 32, "items": STRING},
74
+ },
75
+ "required": ["pairs", "mention_ids"],
76
+ }
77
+
78
+ LINKS = collection(
79
+ {
80
+ "mention_id": STRING,
81
+ "candidate_id": {"type": ["string", "null"]},
82
+ "status": {"enum": ["matched", "no_match", "ambiguous"]},
83
+ },
84
+ 32,
85
+ )
86
+
87
+ SEMANTIC_IO = {
88
+ "align_spans": (
89
+ [STRING, collection({"text": STRING, "label": STRING}, 32)],
90
+ collection(
91
+ {
92
+ "id": STRING,
93
+ "text": STRING,
94
+ "label": STRING,
95
+ "start": {"type": "integer"},
96
+ "end": {"type": "integer"},
97
+ },
98
+ 32,
99
+ ),
100
+ ),
101
+ "project_records": (
102
+ [{"type": "array", "maxItems": 32, "items": {"type": "object"}}],
103
+ {"type": "array", "maxItems": 32, "items": {"type": "object"}},
104
+ ),
105
+ "merge_spans": (
106
+ [STRING, {"type": "array", "maxItems": 32}],
107
+ {"type": "array", "maxItems": 32},
108
+ ),
109
+ "merge_records": ([{"type": "array", "maxItems": 32}], {"type": "object"}),
110
+ "merge_labels": ([{"type": "array", "maxItems": 32}], {"type": "object"}),
111
+ "normalize_text": (
112
+ [STRING],
113
+ {"type": "object", "required": ["text", "source_map", "document_id"]},
114
+ ),
115
+ "chunk_text": (
116
+ [STRING],
117
+ collection(
118
+ {
119
+ "id": STRING,
120
+ "start": {"type": "integer"},
121
+ "end": {"type": "integer"},
122
+ "text": STRING,
123
+ },
124
+ 32,
125
+ ),
126
+ ),
127
+ "retrieve_candidates": ([MENTIONS, CATALOG], RETRIEVAL),
128
+ "exact_links": ([MENTIONS, CATALOG], LINKS),
129
+ "resolve_links": ([RETRIEVAL, DECISIONS], LINKS),
130
+ "assemble_records": (
131
+ [MENTIONS, collection({"id": STRING}, 32)],
132
+ {"type": "array", "maxItems": 32},
133
+ ),
134
+ }
135
+
136
+ CONFIG_FIELDS = {
137
+ "casefold": {"type": "boolean"},
138
+ "unique": {"type": "boolean"},
139
+ "size": {"type": "integer", "minimum": 1, "maximum": 16384},
140
+ "overlap": {"type": "integer", "minimum": 0, "maximum": 16383},
141
+ "top_k": {"enum": [1, 3, 5]},
142
+ "unit": {"enum": ["chars", "tokens"]},
143
+ "rule": {"enum": ["all_agree", "any_true", "max_ordinal", "union"]},
144
+ "order": {"type": "array", "minItems": 2, "maxItems": 128, "items": {"type": "string"}},
145
+ "sums": {"type": "object", "maxProperties": 32},
146
+ "fields": {
147
+ "type": "array",
148
+ "minItems": 1,
149
+ "maxItems": 32,
150
+ "uniqueItems": True,
151
+ "items": {"type": "string", "minLength": 1},
152
+ },
153
+ }
154
+
155
+
156
+ def semantic_contract(op):
157
+ arity, keys = OPERATORS[op]
158
+ inputs, output = SEMANTIC_IO[op]
159
+ return {
160
+ "input_schema": {
161
+ "type": "array",
162
+ "prefixItems": inputs,
163
+ "minItems": arity,
164
+ "maxItems": arity,
165
+ },
166
+ "output_schema": output,
167
+ "config_schema": {
168
+ "type": "object",
169
+ "properties": {
170
+ k: (
171
+ {
172
+ "type": "object",
173
+ "minProperties": 1,
174
+ "maxProperties": 32,
175
+ "propertyNames": {"minLength": 1},
176
+ "additionalProperties": {"enum": ["array", "scalar", "ignore"]},
177
+ }
178
+ if op == "merge_records" and k == "fields"
179
+ else {
180
+ "type": "object",
181
+ "minProperties": 1,
182
+ "maxProperties": 32,
183
+ "propertyNames": {"minLength": 1},
184
+ "additionalProperties": {"type": "string", "pattern": "^/"},
185
+ }
186
+ if op == "project_records" and k == "fields"
187
+ else CONFIG_FIELDS[k]
188
+ )
189
+ for k in keys
190
+ },
191
+ "additionalProperties": False,
192
+ "required": ["fields"]
193
+ if op in {"assemble_records", "project_records", "merge_records"}
194
+ else [],
195
+ },
196
+ "source_identity": "original_codepoint_offsets_and_explicit_ids",
197
+ "failure_classes": [
198
+ "invalid_kernel_configuration",
199
+ "invalid_identity",
200
+ "input_limit",
201
+ "invalid_input_shape",
202
+ ],
203
+ "max_input_bytes": 262144,
204
+ "max_output_bytes": 262144,
205
+ }
206
+
207
+
208
+ NULL_POLICIES = frozenset({"empty_string:v1"})
209
+
210
+
211
+ def validate_label_descriptions(descriptions, schema):
212
+ """One bounded description for exactly each enum label of each field."""
213
+ properties = schema.get("properties") or {}
214
+ if not isinstance(descriptions, dict) or set(descriptions) - set(properties):
215
+ raise ValueError("invalid_primitive_configuration")
216
+ for field, labels in descriptions.items():
217
+ if (
218
+ not isinstance(labels, dict)
219
+ or set(labels) != set(properties[field].get("enum") or [])
220
+ or any(not isinstance(v, str) or not v or len(v) > 1024 for v in labels.values())
221
+ ):
222
+ raise ValueError("invalid_primitive_configuration")
223
+
224
+
225
+ def validate_native(step, capability):
226
+ if step.op != capability["kind"]:
227
+ raise ValueError("unsupported_component")
228
+ if step.op == "extract":
229
+ mode = step.config.get("mode", "legacy")
230
+ if mode != "legacy" and mode not in capability.get("modes", []):
231
+ raise ValueError("primitive_mode_unqualified")
232
+ if mode not in {"legacy", "spans", "records"}:
233
+ raise ValueError("unsupported_component")
234
+ if mode == "spans":
235
+ labels = step.config.get("labels")
236
+ if (
237
+ not isinstance(labels, dict)
238
+ or not 1 <= len(labels) <= 32
239
+ or any(
240
+ not isinstance(k, str) or not k or not isinstance(v, str) or len(v) > 1024
241
+ for k, v in labels.items()
242
+ )
243
+ or set(step.config) - {"mode", "labels"}
244
+ ):
245
+ raise ValueError("invalid_primitive_configuration")
246
+ else:
247
+ from .contracts import bounded_schema
248
+
249
+ bounded_schema(step.config.get("schema", {}))
250
+ allowed = {"mode", "schema", "null_policy"}
251
+ if mode == "legacy":
252
+ allowed |= {"view", "label_descriptions"}
253
+ if set(step.config) - allowed:
254
+ raise ValueError("invalid_primitive_configuration")
255
+ if "label_descriptions" in step.config:
256
+ validate_label_descriptions(
257
+ step.config["label_descriptions"], step.config.get("schema", {})
258
+ )
259
+ # A declared, typed normalization; only where the task permits it (W6).
260
+ if "null_policy" in step.config and (
261
+ mode != "records" or step.config["null_policy"] not in NULL_POLICIES
262
+ ):
263
+ raise ValueError("invalid_primitive_configuration")
264
+ if mode in {"spans", "records"} and (len(step.inputs) != 1 or step.prompt or step.messages):
265
+ raise ValueError("unsupported_native_prompt")
266
+ if mode == "records":
267
+ from .native_schema import structured_schema
268
+
269
+ structured_schema(step.config["schema"])
270
+ if "view" in step.config and (
271
+ step.config["view"] not in {"full", "bindings"} or mode in {"spans", "records"}
272
+ ):
273
+ raise ValueError("invalid_primitive_configuration")
274
+ elif step.op == "choice":
275
+ if step.config.get("mode") == "pairs":
276
+ if "pairs" not in capability.get("modes", []):
277
+ raise ValueError("primitive_mode_unqualified")
278
+ if set(step.config) != {"mode"} or len(step.inputs) < 1:
279
+ raise ValueError("invalid_primitive_configuration")
280
+ return
281
+ questions = step.config.get("questions")
282
+ if (
283
+ not isinstance(questions, dict)
284
+ or not 1 <= len(questions) <= 128
285
+ or set(step.config) - {"questions", "view"}
286
+ or step.config.get("view", "full") not in {"full", "bindings"}
287
+ ):
288
+ raise ValueError("invalid_primitive_configuration")
289
+ for field, question in questions.items():
290
+ if not isinstance(field, str) or not isinstance(question, dict):
291
+ raise ValueError("invalid_primitive_configuration")
292
+ options = question.get("options", [])
293
+ if question.get("type") in {"noul", "score"}:
294
+ # Only capability runs pass card ``answers``; legacy primitives
295
+ # (and Jev without a card) never accept these answer types.
296
+ from .contracts import check_question
297
+
298
+ if question["type"] not in capability.get("answers", ()):
299
+ raise ValueError("invalid_primitive_configuration")
300
+ check_question(question)
301
+ if question["type"] == "score" and len(question["levels"]) > capability.get(
302
+ "max_levels", 10
303
+ ):
304
+ raise ValueError("invalid_primitive_configuration")
305
+ elif question.get("type") == "boolean":
306
+ if set(question) != {"type"}:
307
+ raise ValueError("invalid_primitive_configuration")
308
+ elif (
309
+ question.get("type") != "choice"
310
+ or not isinstance(options, list)
311
+ or not 1 <= len(options) <= 128
312
+ or any(not isinstance(v, str) for v in options)
313
+ or len(set(options)) != len(options)
314
+ or set(question) != {"type", "options"}
315
+ ):
316
+ raise ValueError("invalid_primitive_configuration")
@@ -0,0 +1,277 @@
1
+ """Typed forward-only control flow, shared by validation, execution and budgeting.
2
+
3
+ This module deliberately imports contracts lazily: Predicate is embedded in Step.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from typing import Any, Literal
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
12
+
13
+ from .contract_versions import CONDITIONAL_CONTRACT # noqa: F401 (re-export)
14
+
15
+ CONTROL_OPS = frozenset({"branch", "merge", "return"})
16
+
17
+ LEARNED_OPS = frozenset({"llm", "choice", "extract"})
18
+
19
+ CONDITIONAL_VERSION = "function-plan-v5"
20
+
21
+
22
+ class Predicate(BaseModel):
23
+ model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
24
+ operator: Literal["eq", "in", "lt", "le", "gt", "ge", "all", "any"]
25
+ source: str | None = None
26
+ value: Any = None
27
+ clauses: list[Predicate] = Field(default_factory=list, max_length=4)
28
+
29
+ @model_validator(mode="after")
30
+ def bounded(self):
31
+ from .contracts import canonical, reference
32
+
33
+ def visit(predicate, depth=0):
34
+ if predicate.operator in {"all", "any"}:
35
+ if (
36
+ depth >= 2
37
+ or not predicate.clauses
38
+ or predicate.source
39
+ or predicate.value is not None
40
+ ):
41
+ raise ValueError("invalid_predicate")
42
+ return sum(visit(child, depth + 1) for child in predicate.clauses)
43
+ if (
44
+ predicate.clauses
45
+ or predicate.source is None
46
+ or "value" not in predicate.model_fields_set
47
+ ):
48
+ raise ValueError("invalid_predicate")
49
+ reference(predicate.source)
50
+ if predicate.operator == "in":
51
+ if not isinstance(predicate.value, list) or not 1 <= len(predicate.value) <= 64:
52
+ raise ValueError("invalid_predicate")
53
+ values = predicate.value
54
+ else:
55
+ values = [predicate.value]
56
+ if any(type(value) not in {str, int, float, bool, type(None)} for value in values):
57
+ raise ValueError("predicate_type")
58
+ if any(isinstance(value, float) and not math.isfinite(value) for value in values):
59
+ raise ValueError("predicate_type")
60
+ if len({_kind(value) for value in values}) > 1:
61
+ raise ValueError("predicate_type")
62
+ if (
63
+ predicate.operator in {"lt", "le", "gt", "ge"}
64
+ and _kind(predicate.value) != "number"
65
+ ):
66
+ raise ValueError("predicate_type")
67
+ return 1
68
+
69
+ if visit(self) > 4 or len(canonical(self.model_dump()).encode()) > 8192:
70
+ raise ValueError("predicate_complexity_limit")
71
+ return self
72
+
73
+
74
+ def _kind(value):
75
+ if type(value) in {int, float}:
76
+ return "number"
77
+ return {str: "string", bool: "boolean", type(None): "null"}.get(type(value), "invalid")
78
+
79
+
80
+ def predicate_refs(predicate):
81
+ if predicate.source is not None:
82
+ return [predicate.source]
83
+ return [ref for child in predicate.clauses for ref in predicate_refs(child)]
84
+
85
+
86
+ def evaluate_predicate(predicate, values):
87
+ from .executor import resolve
88
+
89
+ if predicate.operator in {"all", "any"}:
90
+ # Validate every operand; short circuiting must not hide missing data.
91
+ results = [evaluate_predicate(child, values) for child in predicate.clauses]
92
+ return all(results) if predicate.operator == "all" else any(results)
93
+ actual = resolve(predicate.source, values)
94
+ expected = predicate.value[0] if predicate.operator == "in" else predicate.value
95
+ if _kind(actual) != _kind(expected) or _kind(actual) == "invalid":
96
+ raise ValueError("predicate_type")
97
+ if isinstance(actual, float) and not math.isfinite(actual):
98
+ raise ValueError("predicate_type")
99
+ if predicate.operator == "eq":
100
+ return actual == predicate.value
101
+ if predicate.operator == "in":
102
+ return actual in predicate.value
103
+ if predicate.operator == "lt":
104
+ return actual < predicate.value
105
+ if predicate.operator == "le":
106
+ return actual <= predicate.value
107
+ if predicate.operator == "gt":
108
+ return actual > predicate.value
109
+ return actual >= predicate.value
110
+
111
+
112
+ def successors(step):
113
+ if step.op == "return":
114
+ return ()
115
+ if step.op == "branch":
116
+ return tuple(dict.fromkeys((step.true_next, step.false_next)))
117
+ return (step.next,)
118
+
119
+
120
+ def predecessors(plan):
121
+ incoming = {step.id: [] for step in plan.steps}
122
+ for step in plan.steps:
123
+ for target in successors(step):
124
+ incoming[target].append(step.id)
125
+ return incoming
126
+
127
+
128
+ def max_path(plan, weight):
129
+ """Maximum additive resource along a reachable path; preserves Decimal types."""
130
+ totals = {}
131
+ for step in reversed(plan.steps):
132
+ totals[step.id] = weight(step) + max(
133
+ (totals[target] for target in successors(step)), default=0
134
+ )
135
+ return totals[plan.steps[0].id]
136
+
137
+
138
+ def validate_graph(plan):
139
+ from .contracts import reference
140
+
141
+ positions = {step.id: index for index, step in enumerate(plan.steps)}
142
+ returns = [step for step in plan.steps if step.op == "return"]
143
+ if len(returns) != 1 or plan.steps[-1].op != "return":
144
+ raise ValueError("single_return_required")
145
+ for step in plan.steps:
146
+ if step.op == "branch":
147
+ if (
148
+ not step.predicate
149
+ or not step.true_next
150
+ or not step.false_next
151
+ or step.next
152
+ or step.inputs
153
+ ):
154
+ raise ValueError("invalid_branch")
155
+ elif step.predicate or step.true_next or step.false_next:
156
+ raise ValueError("unexpected_control_fields")
157
+ if step.op == "merge":
158
+ if not step.incoming or not step.output_schema or step.inputs:
159
+ raise ValueError("invalid_merge")
160
+ elif step.incoming is not None or step.bind_call is not None:
161
+ raise ValueError("unexpected_control_fields")
162
+ if step.op in CONTROL_OPS and (step.config or step.call or step.model):
163
+ raise ValueError("invalid_control_configuration")
164
+ if step.op == "return" and (step.next or len(step.inputs) != 1):
165
+ raise ValueError("invalid_return")
166
+ for target in successors(step):
167
+ if target not in positions:
168
+ raise ValueError("missing_control_target")
169
+ if positions[target] <= positions[step.id]:
170
+ raise ValueError("forward_control_edge")
171
+ incoming = predecessors(plan)
172
+ available = {}
173
+ for index, step in enumerate(plan.steps):
174
+ parents = incoming[step.id]
175
+ if index and not parents:
176
+ raise ValueError("unreachable_step")
177
+ before = (
178
+ set.intersection(*(available[parent] for parent in parents)) if parents else {"input"}
179
+ )
180
+ refs = list(step.inputs)
181
+ if step.op == "branch":
182
+ refs.extend(predicate_refs(step.predicate))
183
+ if any(reference(ref)[0] not in before for ref in refs):
184
+ raise ValueError("non_dominating_reference")
185
+ if step.op == "merge":
186
+ if set(step.incoming) != set(parents):
187
+ raise ValueError("merge_predecessors")
188
+ for parent, ref in step.incoming.items():
189
+ if reference(ref)[0] not in available[parent]:
190
+ raise ValueError("non_dominating_reference")
191
+ available[step.id] = before | {step.id}
192
+ if max_path(plan, lambda step: int(step.op in LEARNED_OPS)) > 3:
193
+ raise ValueError("model_call_limit")
194
+ from .attempt_bound import _step_attempts
195
+
196
+ if max_path(plan, lambda step: _step_attempts(step, plan.version)) > 5:
197
+ raise ValueError("call_limit")
198
+
199
+
200
+ def binding_states(plan, spec):
201
+ """Only identical call bindings survive joins; merges explicitly rebind them."""
202
+ from .contracts import reference
203
+
204
+ incoming, after, before = predecessors(plan), {}, {}
205
+ calls = {call.id for call in spec.calls}
206
+ for step in plan.steps:
207
+ parents = incoming[step.id]
208
+ shared = dict(after[parents[0]]) if parents else {}
209
+ for parent in parents[1:]:
210
+ shared = {
211
+ key: value for key, value in shared.items() if after[parent].get(key) == value
212
+ }
213
+ before[step.id] = dict(shared)
214
+ if step.op in LEARNED_OPS:
215
+ if step.call not in calls:
216
+ raise ValueError("unknown_call")
217
+ for binding in spec.bindings:
218
+ if binding.call == step.call:
219
+ root, _ = reference(binding.source)
220
+ if root != "input" and root not in shared:
221
+ raise ValueError("missing_intermediate_call")
222
+ if step.output_binding == "call":
223
+ shared[step.call] = step.id
224
+ if step.bind_call:
225
+ if step.bind_call not in calls:
226
+ raise ValueError("unknown_call")
227
+ shared[step.bind_call] = step.id
228
+ after[step.id] = shared
229
+ return before
230
+
231
+
232
+ def validate_predicate_schema(predicate, schemas):
233
+ if predicate.operator in {"all", "any"}:
234
+ for child in predicate.clauses:
235
+ validate_predicate_schema(child, schemas)
236
+ return
237
+ schema = schemas.get(predicate.source)
238
+ if not schema or not schema.get("type"):
239
+ return
240
+ expected = predicate.value[0] if predicate.operator == "in" else predicate.value
241
+ types = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]
242
+ if not any(
243
+ value == _kind(expected) or value == "integer" and _kind(expected) == "number"
244
+ for value in types
245
+ ):
246
+ raise ValueError("predicate_schema_type")
247
+
248
+
249
+ def canonical_graph(plan):
250
+ """Rename node identities and every typed edge/ref; never rewrite user text."""
251
+ from .contracts import reference
252
+
253
+ names = {step.id: f"s{index}" for index, step in enumerate(plan.steps)}
254
+
255
+ def ref(value):
256
+ root, path = reference(value)
257
+ return names.get(root, root) + "#" + path
258
+
259
+ def predicate(value):
260
+ result = dict(value)
261
+ if result.get("source"):
262
+ result["source"] = ref(result["source"])
263
+ result["clauses"] = [predicate(child) for child in result.get("clauses", [])]
264
+ return result
265
+
266
+ value = plan.model_dump(mode="json")
267
+ for step in value["steps"]:
268
+ step["id"] = names[step["id"]]
269
+ step["inputs"] = [ref(item) for item in step["inputs"]]
270
+ for key in ("next", "true_next", "false_next"):
271
+ if key in step:
272
+ step[key] = names[step[key]]
273
+ if "incoming" in step:
274
+ step["incoming"] = {names[key]: ref(item) for key, item in step["incoming"].items()}
275
+ if "predicate" in step:
276
+ step["predicate"] = predicate(step["predicate"])
277
+ return value
@@ -0,0 +1,15 @@
1
+ """Optimizer-correctness contract identifiers shared by the optimizer and the interpreter."""
2
+
3
+ # v3 adds context measurement v2, bound-field native views and chunked plans.
4
+ # Created only while the context-chunking flag is on. It keeps v2 measurement.
5
+ CONTEXT_CHUNKING_CONTRACT = "optimizer-correctness-v3"
6
+ CONDITIONAL_CONTRACT = "optimizer-correctness-v5"
7
+ # v6 adds evaluation-semantics-v2 (value equality, the metric registry and
8
+ # direction-aware objectives). It freezes the task-metric and conditional
9
+ # capability booleans instead of implying conditional creation.
10
+ EVALUATION_FIDELITY_CONTRACT = "optimizer-correctness-v6"
11
+ SPAN_GROUNDING_CONTRACT = "optimizer-correctness-v7"
12
+ # Learned-step requests delimit the compiler-added instruction and stage inputs
13
+ # in one developer message (``instruction_envelope.py``). Frozen per run and per
14
+ # revision; ``None`` keeps the legacy request bytes. No setting creates it yet.
15
+ INSTRUCTION_ENVELOPE_CONTRACT = "instruction-envelope-v1"