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,852 @@
1
+ """Bounded interpreter used unchanged by evaluation, Try and serving.
2
+
3
+ Model transport is injected; this module has no worker or optimizer dependencies.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import re
11
+ import time
12
+ from collections.abc import Awaitable, Callable
13
+ from contextlib import contextmanager
14
+ from dataclasses import dataclass
15
+ from decimal import Decimal, InvalidOperation
16
+ from typing import Any
17
+
18
+ from jsonschema import Draft202012Validator
19
+
20
+ from .contracts import FunctionSpec, Plan, Step, canonical, digest, reference, semantic_plan
21
+ from .provider_error import ProviderError
22
+
23
+
24
+ def pointer(value: Any, path: str) -> Any:
25
+ for raw in path.split("/")[1:] if path else []:
26
+ key = raw.replace("~1", "/").replace("~0", "~")
27
+ try:
28
+ if isinstance(value, list):
29
+ if not key.isdigit() or str(int(key)) != key:
30
+ raise ValueError("invalid_array_index")
31
+ value = value[int(key)]
32
+ else:
33
+ value = value[key]
34
+ except (KeyError, IndexError, TypeError) as exc:
35
+ raise ValueError("missing_binding") from exc
36
+ return value
37
+
38
+
39
+ def resolve(ref: str, values: dict[str, Any]) -> Any:
40
+ root, path = reference(ref)
41
+ if root not in values:
42
+ raise ValueError("missing_binding")
43
+ return pointer(values[root], path)
44
+
45
+
46
+ def validate_inputs(spec: FunctionSpec, inputs: dict, plan: Plan | None = None):
47
+ """Check all external dependencies before the first paid step, including fallback."""
48
+ if not isinstance(inputs, dict) or len(canonical(inputs).encode()) > 262144:
49
+ raise ValueError("invalid_function_inputs")
50
+ if spec.input_schema and not Draft202012Validator(spec.input_schema).is_valid(inputs):
51
+ raise ValueError("invalid_function_inputs")
52
+ refs = [b.source for b in spec.bindings]
53
+ if plan:
54
+ if semantic_plan(plan.version):
55
+ from .attempt_bound import program_attempt_bound
56
+
57
+ program_attempt_bound(plan, spec)
58
+ if plan.version == "function-plan-v2" or semantic_plan(plan.version):
59
+ from .program_validation import validate_program
60
+
61
+ validate_program(plan, spec)
62
+ # Conditional nodes validate their data when the selected path visits
63
+ # them. Unvisited optional inputs must not become global requirements.
64
+ if plan.version != "function-plan-v5":
65
+ refs.extend(ref for step in plan.steps for ref in step.inputs)
66
+ for ref in refs:
67
+ if reference(ref)[0] == "input":
68
+ resolve(ref, {"input": inputs})
69
+ if (
70
+ plan
71
+ and plan.version != "function-plan-v5"
72
+ and (plan.version == "function-plan-v2" or semantic_plan(plan.version))
73
+ ):
74
+ for step in plan.steps:
75
+ for ref in step.inputs:
76
+ if reference(ref)[0] != "input":
77
+ continue
78
+ value = resolve(ref, {"input": inputs})
79
+ if (
80
+ (step.op in {"map", "filter", "decimal_sum"} and not isinstance(value, list))
81
+ or (step.op == "parse_json" and not isinstance(value, str))
82
+ or (step.op == "lookup" and not isinstance(value, dict))
83
+ ):
84
+ raise ValueError("invalid_function_inputs")
85
+ # Render external-only calls now so expanded bodies fail before paid dispatch.
86
+ for call in spec.calls:
87
+ if all(reference(b.source)[0] == "input" for b in spec.bindings if b.call == call.id):
88
+ render_request(spec, call.id, inputs, {})
89
+
90
+
91
+ def render_request(spec: FunctionSpec, call_id: str, inputs: dict, prior: dict) -> dict:
92
+ call = next((c for c in spec.calls if c.id == call_id), None)
93
+ if call is None:
94
+ raise ValueError("unknown_call")
95
+ result = call.model_dump(exclude={"id", "model"}, exclude_none=True)
96
+ if spec.template_syntax is not None:
97
+ from .templates import parse_template
98
+
99
+ for index, message in enumerate(call.messages):
100
+ template = parse_template(message.content, spec.template_syntax)
101
+ values = {name: inputs[name] for name in template.names}
102
+ if any(not isinstance(value, str) for value in values.values()):
103
+ raise ValueError("invalid_function_inputs")
104
+ result["messages"][index]["content"] = template.render(values)
105
+ if len(canonical(result).encode()) > 262144:
106
+ raise ValueError("expanded_request_too_large")
107
+ return result
108
+ # Resolve against original text once: inserted data cannot become template code.
109
+ by_message = {}
110
+ for binding in spec.bindings:
111
+ if binding.call == call_id:
112
+ value = resolve(binding.source, {**prior, "input": inputs})
113
+ by_message.setdefault(binding.message, []).append(
114
+ (binding.placeholder, value if isinstance(value, str) else canonical(value))
115
+ )
116
+ for index, replacements in by_message.items():
117
+ original = result["messages"][index]["content"]
118
+ spans = sorted((original.index(key), len(key), value) for key, value in replacements)
119
+ pieces, end = [], 0
120
+ for start, length, value in spans:
121
+ if start < end:
122
+ raise ValueError("overlapping_binding")
123
+ pieces.extend([original[end:start], value])
124
+ end = start + length
125
+ pieces.append(original[end:])
126
+ result["messages"][index]["content"] = "".join(pieces)
127
+ if len(canonical(result).encode()) > 262144:
128
+ raise ValueError("expanded_request_too_large")
129
+ return result
130
+
131
+
132
+ def decimal(value: Any) -> Decimal:
133
+ try:
134
+ result = Decimal(str(value))
135
+ except (InvalidOperation, ValueError) as exc:
136
+ raise ValueError("invalid_decimal") from exc
137
+ if not result.is_finite():
138
+ raise ValueError("invalid_decimal")
139
+ return result
140
+
141
+
142
+ def validate_kernel_config(op, config):
143
+ allowed = {
144
+ "copy": set(),
145
+ "parse_json": set(),
146
+ "object": {"fields"},
147
+ "lookup": {"key"},
148
+ "compare": {"operator"},
149
+ "filter": {"path", "equals"},
150
+ "map": {"path"},
151
+ "decimal_sum": set(),
152
+ "decimal_add": set(),
153
+ "decimal_multiply": set(),
154
+ }
155
+ if op not in allowed or set(config) - allowed[op]:
156
+ raise ValueError("unsupported_kernel_configuration")
157
+
158
+
159
+ def kernel(op: str, args: list, config: dict, max_items: int, diagnostics=None):
160
+ from .semantic import OPERATORS
161
+ from .semantic import kernel as semantic_kernel
162
+
163
+ if op in OPERATORS:
164
+ return semantic_kernel(op, args, config, diagnostics)
165
+ validate_kernel_config(op, config)
166
+ if any(isinstance(a, list) and len(a) > max_items for a in args):
167
+ raise ValueError("item_limit")
168
+ if op == "copy" and len(args) == 1:
169
+ return args[0]
170
+ if op == "parse_json" and len(args) == 1:
171
+ return json.loads(
172
+ args[0], parse_constant=lambda _: (_ for _ in ()).throw(ValueError("invalid_json"))
173
+ )
174
+ if op == "object" and len(config.get("fields", [])) == len(args):
175
+ fields = config["fields"]
176
+ if len(set(fields)) != len(fields):
177
+ raise ValueError("duplicate_field")
178
+ return dict(zip(fields, args, strict=True))
179
+ if op == "lookup" and len(args) == 1:
180
+ return args[0].get(config["key"])
181
+ if op == "compare" and len(args) == 2:
182
+ if config.get("operator", "eq") == "eq":
183
+ return args[0] == args[1]
184
+ if config.get("operator") == "lt":
185
+ return decimal(args[0]) < decimal(args[1])
186
+ if op == "map" and len(args) == 1:
187
+ return [pointer(a, config["path"]) for a in args[0]]
188
+ if op == "filter" and len(args) == 1:
189
+ return [a for a in args[0] if pointer(a, config["path"]) == config["equals"]]
190
+ if op == "decimal_sum" and len(args) == 1:
191
+ return str(sum((decimal(a) for a in args[0]), Decimal(0)))
192
+ if op == "decimal_add" and len(args) == 2:
193
+ return str(decimal(args[0]) + decimal(args[1]))
194
+ if op == "decimal_multiply" and len(args) == 2:
195
+ return str(decimal(args[0]) * decimal(args[1]))
196
+ raise ValueError("invalid_kernel_inputs")
197
+
198
+
199
+ @dataclass(frozen=True)
200
+ class Execution:
201
+ output: Any
202
+ calls: int
203
+ elapsed_ms: float
204
+ fallback_used: bool = False
205
+ fallback_reason: str | None = None
206
+ chunked: bool = False
207
+ path: tuple[str, ...] = ()
208
+ escalation_used: bool = False
209
+ timing_available: bool = True
210
+ # Counts from drop-mode ``align_spans`` steps on the answering path
211
+ # (``quoted_records``, ``dropped_quotations``, ``dropped_reasons``); ``None``
212
+ # when no such step ran. Never contains quotation text.
213
+ diagnostics: dict | None = None
214
+ # Internal durable evidence: a successful retry does not settle earlier attempts.
215
+ attempt_accounting: dict | None = None
216
+
217
+
218
+ def merge_diagnostics(total, step):
219
+ """Sum per-step drop counts; ``total`` is updated in place."""
220
+ total["quoted_records"] = total.get("quoted_records", 0) + step["quoted_records"]
221
+ total["dropped_quotations"] = total.get("dropped_quotations", 0) + step["dropped_quotations"]
222
+ if "repaired_contexts" in step:
223
+ total["repaired_contexts"] = total.get("repaired_contexts", 0) + step["repaired_contexts"]
224
+ reasons = total.setdefault("dropped_reasons", {})
225
+ for reason, count in step["dropped_reasons"].items():
226
+ reasons[reason] = reasons.get(reason, 0) + count
227
+ return total
228
+
229
+
230
+ def failure_reason(exc):
231
+ """Sanitized typed code for a failed execution step; never upstream text."""
232
+ from .deadline import ServingCapacity
233
+
234
+ if isinstance(exc, ServingCapacity):
235
+ return "provider_capacity"
236
+ if isinstance(exc, ProviderError):
237
+ return exc.code if re.fullmatch(r"[a-z_]{1,80}", exc.code or "") else "provider_error"
238
+ if isinstance(exc, json.JSONDecodeError):
239
+ return "invalid_provider_output"
240
+ if isinstance(exc, TimeoutError):
241
+ return "execution_timeout"
242
+ if isinstance(exc, ValueError) and re.fullmatch(r"[a-z_]{1,80}", str(exc)):
243
+ return str(exc)
244
+ return "execution_failed"
245
+
246
+
247
+ def evidence_value(value):
248
+ data = canonical(value)
249
+ return {
250
+ "digest": digest(value),
251
+ "bytes": len(data.encode()),
252
+ "value": value if len(data.encode()) <= 8192 else None,
253
+ "content_omitted": len(data.encode()) > 8192,
254
+ }
255
+
256
+
257
+ def bounded_trace(trace):
258
+ """Bound stored evidence without pretending omitted content was empty."""
259
+ from copy import deepcopy
260
+
261
+ result = deepcopy(trace)
262
+ if len(canonical(result).encode()) > 65536:
263
+ for step in result:
264
+ for item in [*step.get("inputs", []), step.get("output")]:
265
+ if isinstance(item, dict) and "value" in item:
266
+ item.update(value=None, content_omitted=True)
267
+ return result
268
+
269
+
270
+ @contextmanager
271
+ def step_observation(trace, plan, step, phase, inputs, values, call_count):
272
+ if trace is None:
273
+ yield {}
274
+ return
275
+ start = time.monotonic()
276
+ record = {
277
+ "version": "function-step-v1",
278
+ "id": digest([plan.digest, phase, step.id]),
279
+ "step": step.id,
280
+ "phase": phase,
281
+ "operator": step.op,
282
+ "model": step.model,
283
+ "dependencies": step.inputs,
284
+ "state": "completed",
285
+ "started_unix_ns": str(time.time_ns()),
286
+ }
287
+ initial = call_count()
288
+ if trace is not None:
289
+ record["attempt_start"] = 1 + sum(t["attempt_count"] for t in trace)
290
+ record["inputs"] = [evidence_value(resolve(r, values)) for r in step.inputs]
291
+ try:
292
+ yield record
293
+ except BaseException as exc:
294
+ record["state"] = "failed"
295
+ record["error"] = (
296
+ str(exc)
297
+ if isinstance(exc, ValueError)
298
+ and str(exc).replace("_", "").isalpha()
299
+ and len(str(exc)) < 80
300
+ else "step_failed"
301
+ )
302
+ raise
303
+ finally:
304
+ if trace is not None:
305
+ record["elapsed_ms"] = (time.monotonic() - start) * 1000
306
+ record["attempt_count"] = call_count() - initial
307
+ trace.append(record)
308
+
309
+
310
+ def _bound_messages(spec, step, values):
311
+ if step.inputs:
312
+ bound = [resolve(ref, values) for ref in step.inputs]
313
+ else:
314
+ bound = [
315
+ resolve(binding.source, values)
316
+ for binding in spec.bindings
317
+ if binding.call == step.call and binding.source.startswith("input#")
318
+ ]
319
+ return [{"role": "user", "content": canonical({"inputs": bound})}]
320
+
321
+
322
+ def _chunk_payload(step, payload, chunk):
323
+ text = chunk.get("text") if isinstance(chunk, dict) else None
324
+ if not isinstance(text, str):
325
+ raise ValueError("invalid_text")
326
+ body = {**payload, "messages": [dict(message) for message in payload["messages"]]}
327
+ if step.op == "extract" and step.config.get("mode") in {"spans", "records"}:
328
+ body["primitive"] = {**body["primitive"], "source": text}
329
+ else:
330
+ body["messages"] = [{"role": "user", "content": text}]
331
+ return body
332
+
333
+
334
+ async def _fanout(step, payload, chunks, provider):
335
+ sem = asyncio.Semaphore(4)
336
+
337
+ async def one(chunk):
338
+ async with sem:
339
+ return await provider(step.model, _chunk_payload(step, payload, chunk))
340
+
341
+ tasks = [asyncio.create_task(one(chunk)) for chunk in chunks]
342
+ pending = asyncio.gather(*tasks)
343
+ try:
344
+ # Own cancellation here so a second caller cancellation cannot interrupt
345
+ # a provider's settlement after the first failure/cancellation.
346
+ rows = await asyncio.shield(pending)
347
+ except BaseException:
348
+ for task in tasks:
349
+ if not task.done():
350
+ task.cancel()
351
+ drained = asyncio.gather(*tasks, return_exceptions=True)
352
+ while not drained.done():
353
+ try:
354
+ await asyncio.shield(drained)
355
+ except asyncio.CancelledError:
356
+ # Settlement must finish before callers snapshot accounting or
357
+ # begin fallback. Re-raise the original typed failure below.
358
+ continue
359
+ if pending.done() and not pending.cancelled():
360
+ pending.exception()
361
+ raise
362
+ return [
363
+ {
364
+ "chunk_id": chunk.get("id"),
365
+ "start": chunk.get("start"),
366
+ "end": chunk.get("end"),
367
+ "value": row,
368
+ }
369
+ for chunk, row in zip(chunks, rows, strict=True)
370
+ ]
371
+
372
+
373
+ def step_payload(spec, step, inputs, prior, values, *, instruction_envelope=None):
374
+ """Build the same immutable provider request for execution and preflight pricing.
375
+
376
+ ``instruction_envelope`` is the run's or revision's frozen rendering contract
377
+ (``optimizer.instruction_envelope``). ``None`` keeps the legacy bytes.
378
+ """
379
+ if instruction_envelope is not None:
380
+ from .contract_versions import INSTRUCTION_ENVELOPE_CONTRACT
381
+
382
+ if instruction_envelope != INSTRUCTION_ENVELOPE_CONTRACT:
383
+ raise ValueError("instruction_envelope_unsupported")
384
+ payload = render_request(spec, step.call, inputs, prior)
385
+ if "max_tokens" not in payload:
386
+ # Explicit null freezes provider omission even when a run normally sizes
387
+ # output itself; the request marker also reserves the endpoint ceiling.
388
+ payload["seldon_output_token_policy"] = "request"
389
+ elif spec.output_token_policy != "request":
390
+ payload["seldon_output_token_policy"] = spec.output_token_policy
391
+ if instruction_envelope is not None:
392
+ from .instruction_envelope import render
393
+
394
+ notice = render(step)
395
+ if notice is not None:
396
+ payload["messages"].append(notice)
397
+ elif step.instruction_mode == "append_instruction":
398
+ # Steps whose messages are replaced below keep their legacy bytes.
399
+ payload["messages"].append({"role": "developer", "content": step.prompt})
400
+ elif step.instruction_mode == "append_instruction":
401
+ payload["messages"].append({"role": "developer", "content": step.prompt})
402
+ if step.instruction_mode == "replacement_messages":
403
+ # Replacement text is an immutable complete template. Bindings still
404
+ # resolve through the reviewed original messages, supplied as context.
405
+ payload["messages"] = [m.model_dump() for m in step.messages] + [
406
+ {
407
+ "role": "user",
408
+ "content": canonical({"original_request": payload["messages"]}),
409
+ }
410
+ ]
411
+ if step.output_schema:
412
+ for key in ("tools", "tool_choice", "parallel_tool_calls"):
413
+ payload.pop(key, None)
414
+ payload["response_format"] = {
415
+ "type": "json_schema",
416
+ "json_schema": {
417
+ "name": "stage_output",
418
+ "schema": step.output_schema,
419
+ "strict": True,
420
+ },
421
+ }
422
+ if step.inputs:
423
+ payload["messages"].append(
424
+ {
425
+ "role": "user",
426
+ "content": canonical({"stage_inputs": [resolve(r, values) for r in step.inputs]}),
427
+ }
428
+ )
429
+ if step.op != "llm":
430
+ for key in ("tools", "tool_choice", "parallel_tool_calls"):
431
+ payload.pop(key, None)
432
+ payload["primitive"] = {"kind": step.op, "config": step.config}
433
+ if step.op == "extract" and step.config.get("mode") in {"spans", "records"}:
434
+ if len(step.inputs) != 1:
435
+ raise ValueError("invalid_primitive_source")
436
+ payload["primitive"]["source"] = resolve(step.inputs[0], values)
437
+ if step.config.get("view") == "bindings":
438
+ payload["messages"] = _bound_messages(spec, step, values)
439
+ return payload
440
+
441
+
442
+ async def _execute(
443
+ plan: Plan,
444
+ spec: FunctionSpec,
445
+ inputs: dict,
446
+ provider: Callable[[str, dict], Awaitable[Any]],
447
+ *,
448
+ timeout: float = 55,
449
+ trace=None,
450
+ phase="primary",
451
+ probe=False,
452
+ path_state=None,
453
+ instruction_envelope=None,
454
+ ) -> Execution:
455
+ start = time.monotonic()
456
+ values, prior, calls = {"input": inputs}, {}, 0
457
+ chunked = False
458
+ conditional = plan.version == "function-plan-v5"
459
+ by_id = {step.id: step for step in plan.steps}
460
+ index, predecessor = 0, None
461
+ path_state = path_state if path_state is not None else {}
462
+ path_state.update(path=[], escalation_used=False)
463
+ learned_seen, after_learned_branch = False, False
464
+ diagnostics = {}
465
+ async with asyncio.timeout(timeout):
466
+ while index < len(plan.steps):
467
+ step = plan.steps[index]
468
+ successor = step.next if conditional else None
469
+ if conditional:
470
+ path_state["path"].append(step.id)
471
+ if step.op == "branch" and learned_seen:
472
+ after_learned_branch = True
473
+ if step.op in {"llm", "choice", "extract"}:
474
+ path_state["escalation_used"] |= after_learned_branch
475
+ learned_seen = True
476
+ with step_observation(
477
+ trace, plan, step, phase, inputs, values, lambda: calls
478
+ ) as record:
479
+ if conditional and step.op == "branch":
480
+ from .conditional import evaluate_predicate
481
+
482
+ value = evaluate_predicate(step.predicate, values)
483
+ successor = step.true_next if value else step.false_next
484
+ record["successor"] = successor
485
+ record["predicate"] = step.predicate.model_dump(mode="json")
486
+ elif conditional and step.op == "merge":
487
+ value = resolve(step.incoming[predecessor], values)
488
+ if step.bind_call:
489
+ prior[step.bind_call] = value
490
+ record["predecessor"] = predecessor
491
+ elif conditional and step.op == "return":
492
+ value = resolve(step.inputs[0], values)
493
+ elif step.op in {"llm", "choice", "extract"}:
494
+ payload = step_payload(
495
+ spec,
496
+ step,
497
+ inputs,
498
+ prior,
499
+ values,
500
+ instruction_envelope=instruction_envelope,
501
+ )
502
+ if step.over:
503
+ chunks = resolve(step.over, values)
504
+ cap = step.max_chunks or 16
505
+ if not isinstance(chunks, list) or len(chunks) > cap:
506
+ raise ValueError("chunk_limit")
507
+ if len(chunks) > 1:
508
+ chunked = True
509
+ value = await _fanout(step, payload, chunks, provider)
510
+ calls += len(chunks)
511
+ elif step.op == "choice" and step.config.get("mode") == "pairs":
512
+ from .semantic import bounded_rows
513
+
514
+ retrieval = resolve(step.inputs[0], values)
515
+ pairs = retrieval["pairs"]
516
+ bounded_rows(pairs, 160, "pair_limit")
517
+ value = []
518
+ for offset in range(0, len(pairs), 64):
519
+ batch = pairs[offset : offset + 64]
520
+ batch_payload = {
521
+ **payload,
522
+ "primitive": {
523
+ "kind": "choice",
524
+ "config": {
525
+ "questions": {p["id"]: {"type": "boolean"} for p in batch},
526
+ "mode": "pairs",
527
+ "pairs": batch,
528
+ },
529
+ },
530
+ }
531
+ calls += 1
532
+ decisions = await provider(step.model, batch_payload)
533
+ if (
534
+ not isinstance(decisions, dict)
535
+ or set(decisions) != {p["id"] for p in batch}
536
+ or any(type(v) is not bool for v in decisions.values())
537
+ ):
538
+ raise ValueError("invalid_provider_output")
539
+ value.extend(
540
+ {"id": p["id"], "match": decisions[p["id"]]} for p in batch
541
+ )
542
+ else:
543
+ calls += 1
544
+ value = await provider(step.model, payload)
545
+ call = next(c for c in spec.calls if c.id == step.call)
546
+ from .tool_wire import request_schema
547
+
548
+ schema = step.output_schema or request_schema(
549
+ call.model_dump(exclude_none=True)
550
+ )
551
+ if not probe and schema:
552
+ checked = [row["value"] for row in value] if step.over else [value]
553
+ if any(not Draft202012Validator(schema).is_valid(item) for item in checked):
554
+ raise ValueError("output_schema")
555
+ # V3 intermediates are stage data, not outputs of the original
556
+ # workflow. Only its final implementation can satisfy a call binding.
557
+ if step.output_binding == "call":
558
+ prior[step.call] = value
559
+ elif step.op == "generated_kernel":
560
+ from .research_kernels import require
561
+
562
+ runtime = require()
563
+ runtime.validate_step(step)
564
+ value = await runtime.invoke(
565
+ step, resolve(step.inputs[0], values), provider=provider
566
+ )
567
+ else:
568
+ step_diagnostics = {}
569
+ try:
570
+ value = kernel(
571
+ step.op,
572
+ [resolve(r, values) for r in step.inputs],
573
+ step.config,
574
+ plan.max_items,
575
+ step_diagnostics,
576
+ )
577
+ if step_diagnostics:
578
+ # Counts only: quotations can be PII (D-3).
579
+ record["diagnostics"] = step_diagnostics
580
+ merge_diagnostics(diagnostics, step_diagnostics)
581
+ except (ValueError, TypeError, AttributeError) as exc:
582
+ if plan.version != "function-plan-v2" and not semantic_plan(plan.version):
583
+ raise
584
+ if isinstance(exc, ValueError) and str(exc) in {
585
+ "merge_conflict",
586
+ "chunk_limit",
587
+ "span_limit",
588
+ "invalid_span",
589
+ "invalid_chunk_configuration",
590
+ "invalid_text",
591
+ "invalid_kernel_configuration",
592
+ }:
593
+ raise
594
+ raise ValueError("deterministic_step_failed") from exc
595
+ if not probe and step.output_schema and not step.over:
596
+ if not Draft202012Validator(step.output_schema).is_valid(value):
597
+ raise ValueError("output_schema")
598
+ if not probe and len(canonical(value).encode()) > 262144:
599
+ raise ValueError("intermediate_size_limit")
600
+ values[step.id] = value
601
+ if trace is not None:
602
+ record["output"] = evidence_value(value)
603
+ predecessor = step.id
604
+ if conditional:
605
+ if step.op == "return":
606
+ break
607
+ index = plan.steps.index(by_id[successor])
608
+ else:
609
+ index += 1
610
+ output = values[plan.steps[-1].id]
611
+ if not probe and not Draft202012Validator(spec.output_schema).is_valid(output):
612
+ if trace:
613
+ trace[-1].update(state="failed", error="output_schema")
614
+ raise ValueError("output_schema")
615
+ return Execution(
616
+ output,
617
+ calls,
618
+ (time.monotonic() - start) * 1000,
619
+ chunked=chunked,
620
+ path=tuple(path_state["path"]),
621
+ escalation_used=path_state["escalation_used"],
622
+ diagnostics=diagnostics or None,
623
+ )
624
+
625
+
626
+ # Refusals raised by transport before any reservation or HTTP request (P0-F).
627
+ # Serving may answer with the original call because nothing was sent. Compiler
628
+ # evaluation does not widen its set: a model disabled mid-run must fail the
629
+ # candidate, not produce measurements that are really fallback measurements.
630
+ SERVING_PRE_DISPATCH_FALLBACK = frozenset(
631
+ {
632
+ "primitive_adapter_unavailable",
633
+ "primitive_mode_unqualified",
634
+ "pin_version_unsupported",
635
+ "model_capability_contract_unsupported",
636
+ "tool_output_unsupported",
637
+ "wire_profile_unsupported",
638
+ "offering_circuit_open",
639
+ }
640
+ )
641
+
642
+
643
+ def execution_call_limits(plan, spec):
644
+ """Shared serving bounds for enforcement and the management presentation."""
645
+ if plan.version == "function-plan-v4":
646
+ return 40 + (len(spec.calls) if plan.fallback else 0), 40
647
+ limit = 8 if plan.version in {"function-plan-v3", "function-plan-v5"} else 6
648
+ return limit, min(5, limit - len(spec.calls)) if plan.fallback else 5
649
+
650
+
651
+ async def execute(
652
+ plan,
653
+ spec,
654
+ inputs,
655
+ provider,
656
+ *,
657
+ timeout=55,
658
+ trace=None,
659
+ contract=None,
660
+ probe=False,
661
+ conditional=None,
662
+ serving=False,
663
+ instruction_envelope=None,
664
+ ):
665
+ """Run ``plan``. ``serving=True`` is the customer request path (runtime.py);
666
+ only it may fall back on :data:`SERVING_PRE_DISPATCH_FALLBACK` refusals.
667
+
668
+ ``instruction_envelope`` is the frozen request rendering of the run or
669
+ revision (``optimizer.instruction_envelope``); ``None`` is the legacy bytes.
670
+ """
671
+ from .contract_versions import (
672
+ CONDITIONAL_CONTRACT,
673
+ CONTEXT_CHUNKING_CONTRACT,
674
+ EVALUATION_FIDELITY_CONTRACT,
675
+ SPAN_GROUNDING_CONTRACT,
676
+ )
677
+
678
+ # v6 freezes the conditional capability separately; ``conditional=False``
679
+ # (a v6 run created with conditional workflows off) rejects v5 plans.
680
+ v5_allowed = contract == CONDITIONAL_CONTRACT or (
681
+ contract in {EVALUATION_FIDELITY_CONTRACT, SPAN_GROUNDING_CONTRACT}
682
+ and conditional is not False
683
+ )
684
+ if plan.version == "function-plan-v5" and not v5_allowed:
685
+ raise ValueError("plan_version_unsupported")
686
+ chunking = {
687
+ CONTEXT_CHUNKING_CONTRACT,
688
+ "optimizer-correctness-v4",
689
+ CONDITIONAL_CONTRACT,
690
+ EVALUATION_FIDELITY_CONTRACT,
691
+ SPAN_GROUNDING_CONTRACT,
692
+ }
693
+ if plan.version == "function-plan-v4" and contract not in chunking:
694
+ raise ValueError("plan_version_unsupported")
695
+ if any(step.config.get("view") == "bindings" for step in plan.steps) and (
696
+ contract not in chunking
697
+ ):
698
+ raise ValueError("view_requires_v3")
699
+ from .deadline import admission_deadline
700
+
701
+ with admission_deadline(time.monotonic() + timeout):
702
+ return await _execute_with_fallback(
703
+ plan,
704
+ spec,
705
+ inputs,
706
+ provider,
707
+ timeout=timeout,
708
+ trace=trace,
709
+ probe=probe,
710
+ serving=serving,
711
+ instruction_envelope=instruction_envelope,
712
+ )
713
+
714
+
715
+ async def _execute_with_fallback(
716
+ plan,
717
+ spec,
718
+ inputs,
719
+ provider,
720
+ *,
721
+ timeout=55,
722
+ trace=None,
723
+ contract=None,
724
+ probe=False,
725
+ serving=False,
726
+ instruction_envelope=None,
727
+ ):
728
+ """One deadline covers candidate and observable original-workflow fallback."""
729
+ start = time.monotonic()
730
+ calls = 0
731
+ validate_inputs(spec, inputs, plan)
732
+ fallback_phase = False
733
+ primary_path = {}
734
+ call_lock = asyncio.Lock()
735
+
736
+ async def counted(model, payload):
737
+ nonlocal calls
738
+ async with call_lock:
739
+ limit, primary_limit = execution_call_limits(plan, spec)
740
+ if calls + 1 > limit or (
741
+ semantic_plan(plan.version) and not fallback_phase and calls + 1 > primary_limit
742
+ ):
743
+ raise ValueError("call_limit")
744
+ calls += 1
745
+ return await provider(model, payload)
746
+
747
+ # Preserve the isolated study's accounting sink through the call-limit wrapper.
748
+ for attribute in ("research_receipts", "research_operation"):
749
+ if hasattr(provider, attribute):
750
+ setattr(counted, attribute, getattr(provider, attribute))
751
+
752
+ async with asyncio.timeout(timeout):
753
+ try:
754
+ return await _execute(
755
+ plan,
756
+ spec,
757
+ inputs,
758
+ counted,
759
+ timeout=timeout,
760
+ trace=trace,
761
+ probe=probe,
762
+ path_state=primary_path,
763
+ instruction_envelope=instruction_envelope,
764
+ )
765
+ except (ValueError, ProviderError) as exc:
766
+ eligible = {
767
+ "output_schema",
768
+ "invalid_provider_output",
769
+ # Typed native contract failures keep the fallback eligibility they
770
+ # had when they were reported as invalid_provider_output.
771
+ "native_output_schema_mismatch",
772
+ "invalid_grounded_span",
773
+ "ungrounded_quotation",
774
+ "intermediate_size_limit",
775
+ "provider_unavailable",
776
+ "model_identity_changed",
777
+ "token_limit",
778
+ "context_unverified",
779
+ }
780
+ from .deadline import ServingCapacity
781
+
782
+ if serving:
783
+ eligible |= SERVING_PRE_DISPATCH_FALLBACK
784
+ allowed = isinstance(exc, ValueError) and str(exc) in eligible
785
+ # Serving admission refused before dispatch: nothing was sent, so the
786
+ # original workflow may run. Compiler capacity (plain/AdmissionFailure
787
+ # "provider_capacity") stays a retry signal and is never a fallback.
788
+ allowed = allowed or isinstance(exc, ServingCapacity)
789
+ if semantic_plan(plan.version) and isinstance(exc, ValueError):
790
+ allowed = allowed or str(exc) in {
791
+ "span_limit",
792
+ "pair_limit",
793
+ "catalog_limit",
794
+ "mention_limit",
795
+ "chunk_limit",
796
+ "record_limit",
797
+ "invalid_span",
798
+ "invalid_primitive_source",
799
+ "merge_conflict",
800
+ }
801
+ if plan.version == "function-plan-v2" or semantic_plan(plan.version):
802
+ allowed = (
803
+ allowed
804
+ or isinstance(exc, json.JSONDecodeError)
805
+ or str(exc) == "deterministic_step_failed"
806
+ )
807
+ if isinstance(exc, ProviderError) and exc.code == "upstream_context_refused":
808
+ allowed = exc.provider_dispatched is False
809
+ elif isinstance(exc, ProviderError):
810
+ refused = (exc.upstream_code or exc.code) in {
811
+ "content_filter",
812
+ "provider_refusal",
813
+ "content_policy_violation",
814
+ }
815
+ # A network failure after dispatch may have completed paid work.
816
+ # Only known non-dispatch or explicit throttle rejection permits
817
+ # an automatic fallback; uncertainty retains the original hold.
818
+ unambiguous = exc.provider_dispatched is False or exc.upstream_status == 429
819
+ allowed = (
820
+ not refused
821
+ and unambiguous
822
+ and (
823
+ exc.category == "unavailable"
824
+ or exc.code in {"upstream_unavailable", "rate_limited"}
825
+ )
826
+ )
827
+ if not plan.fallback or not allowed:
828
+ raise
829
+ original = Plan(
830
+ steps=[Step(id=c.id, op="llm", model=c.model, call=c.id) for c in spec.calls]
831
+ )
832
+ fallback_phase = True
833
+ remaining = timeout - (time.monotonic() - start)
834
+ result = await _execute(
835
+ original,
836
+ spec,
837
+ inputs,
838
+ counted,
839
+ timeout=max(0, remaining),
840
+ trace=trace,
841
+ phase="fallback",
842
+ instruction_envelope=instruction_envelope,
843
+ )
844
+ return Execution(
845
+ result.output,
846
+ calls,
847
+ (time.monotonic() - start) * 1000,
848
+ True,
849
+ failure_reason(exc),
850
+ path=tuple(primary_path.get("path", [])),
851
+ escalation_used=primary_path.get("escalation_used", False),
852
+ )