diff --git a/python/a2ui_agent/CHANGELOG.md b/python/a2ui_agent/CHANGELOG.md index 48172b5ebe..7ac8a4a551 100644 --- a/python/a2ui_agent/CHANGELOG.md +++ b/python/a2ui_agent/CHANGELOG.md @@ -1,14 +1,5 @@ ## Unreleased -- `resolve_catalogs` reads the capabilities of v0.9 and v0.9.1 catalogs from - the `v0.9.1` entry, falling back to `v0.9` when `v0.9.1` is absent or - activates no catalog. When a renderer sends both entries, both are validated, - and each inline catalog targets the protocol version of its declaring entry. - `read_renderer_capabilities` returns each of the two entries present. - [#3135](https://github.com/a2ui-project/a2ui/pull/3135) -- `DirectJsonFormat`, `DirectJsonParser` and `schema_to_prompt` accept v0.9 and - v0.9.1 catalogs together, as `RendererState` does. - [#3135](https://github.com/a2ui-project/a2ui/pull/3135) - **BREAKING CHANGE**: (v1_0) `validate_payload`, `RendererState.apply`, and inference format parsers check function calls nested in `callRendererFunction.callFunction.args` under the agent's caller boundary instead of the renderer's, rejecting `rendererOnly` functions while accepting `agentOnly` and `rendererOrAgent` functions. Recommended migration: set `allowedCallers` to `"rendererOrAgent"` or `"agentOnly"` on functions nested inside `callRendererFunction` arguments ([#3774](https://github.com/a2ui-project/a2ui/issues/3774), [#4336](https://github.com/a2ui-project/a2ui/pull/4336)). - **BREAKING CHANGE**: `resolve_catalogs` and `read_renderer_capabilities` reject inline catalogs whose local `#...` `$ref` pointers do not resolve @@ -21,6 +12,15 @@ target protocol version's `common_types.json` ([#3165](https://github.com/a2ui-project/a2ui/issues/3165), [#4367](https://github.com/a2ui-project/a2ui/pull/4367)). +- `resolve_catalogs` reads the capabilities of v0.9 and v0.9.1 catalogs from + the `v0.9.1` entry, falling back to `v0.9` when `v0.9.1` is absent or + activates no catalog. When a renderer sends both entries, both are validated, + and each inline catalog targets the protocol version of its declaring entry. + `read_renderer_capabilities` returns each of the two entries present. + [#3135](https://github.com/a2ui-project/a2ui/pull/3135) +- `DirectJsonFormat`, `DirectJsonParser` and `schema_to_prompt` accept v0.9 and + v0.9.1 catalogs together, as `RendererState` does. + [#3135](https://github.com/a2ui-project/a2ui/pull/3135) - `ExpressPromptGenerator` now traverses `oneOf`, `anyOf`, `allOf`, and locally flattened wire envelopes when extracting structured map-key instructions and enum constraints, and `ExpressCompiler` now coerces literal string arrays into @@ -56,6 +56,11 @@ `ComponentSlot`, `ComponentKey`, `SlotKind`, `ActionSpec`, `ExpressSurfaceSpec`, `build_inference_catalogs`, and `lower_for_transport` ([#4320](https://github.com/a2ui-project/a2ui/pull/4320)). +- Add `DecisionCascadeRouter`, `CascadeConfig`, `CascadeTier`, `RouteDecision`, + `SurfaceTemplateSpec`, and `CascadeBatchFormatter` in + `a2ui.inference_formats.experimental.decision_cascade` for single-batch UI + gating, template selection, and catalog pruning + ([#4321](https://github.com/a2ui-project/a2ui/pull/4321)). ## 0.12.1 (2026-11-23) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/__init__.py b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/__init__.py new file mode 100644 index 0000000000..1ce0f9c91d --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Experimental single-batch decision cascade router for A2UI surfaces.""" + +from __future__ import annotations + +from .router import ( + CascadeBatchFormatter, + CascadeConfig, + CascadeTier, + DecisionCascadeRouter, + RouteDecision, + SurfaceTemplateSpec, +) + +__all__ = [ + "CascadeBatchFormatter", + "CascadeConfig", + "CascadeTier", + "DecisionCascadeRouter", + "RouteDecision", + "SurfaceTemplateSpec", +] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/router.py b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/router.py new file mode 100644 index 0000000000..a320962821 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/router.py @@ -0,0 +1,1155 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Single-batch UI gate, routing tier selector, and catalog pruning router.""" + +from __future__ import annotations + +from collections import deque +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from enum import Enum +import math +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload +import warnings + +from a2ui.catalog_transformers import ComponentPruningTransformer +from a2ui.core import CatalogApi +from a2ui.inference_formats._shared.catalogs import check_mixed_catalogs +from a2ui.inference_formats.experimental.decision import ( + CatalogDecisionGraph, + ComponentNodeSpec, + ConversationTurn, + DecisionAnswer, + DecisionBatch, + DecisionModel, + DecisionModelError, + DecisionQuestion, + InputPart, + QuestionKind, + SlotKind, + invoke_decision_model, +) +from a2ui.utils._experimental import experimental + +_NodeKey: TypeAlias = tuple[int, str] + + +class SurfaceTemplateSpec(Protocol): + """Minimal structural protocol for templates registered with `DecisionCascadeRouter`.""" + + @property + def id(self) -> str: + """Stable unique identifier used as the decision candidate label.""" + + @property + def description(self) -> str: + """Short natural-language description shown to the decision model.""" + + @property + def catalog_id(self) -> str | None: + """Optional target catalog identifier required to render this template.""" + + +TemplateT = TypeVar("TemplateT", bound=SurfaceTemplateSpec) + + +class CascadeTier(str, Enum): + """Execution tier selected by `DecisionCascadeRouter`.""" + + TEXT_ONLY = "text_only" + TEMPLATE = "template" + PRUNED_CATALOG = "pruned_catalog" + FULL_CATALOG = "full_catalog" + SANDBOX_APP = "sandbox_app" + + def __str__(self) -> str: + return str.__str__(self) + + def __format__(self, format_spec: str) -> str: + return str.__format__(str(self), format_spec) + + def __hash__(self) -> int: + return str.__hash__(self) + + +class CascadeBatchFormatter(Protocol): + """Hook for customizing the `DecisionBatch` constructed by `DecisionCascadeRouter`.""" + + def __call__( + self, + *, + prompt: str, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph | None, + templates: Sequence[SurfaceTemplateSpec], + config: CascadeConfig, + latency_budget_ms: float | None, + allow_sandbox_app: bool, + include_tier: bool, + include_prune: bool, + context: Mapping[str, Any] | None, + conversation: Sequence[ConversationTurn], + input_parts: Sequence[InputPart], + ) -> DecisionBatch: + """Builds the `DecisionBatch` evaluated for a single `route()` call.""" + + +def _validate_unit_interval(name: str, value: float) -> None: + """Validates that `value` is finite and lies in `[0.0, 1.0]`.""" + if not math.isfinite(value) or not (0.0 <= value <= 1.0): + raise ValueError(f"{name} must be in [0.0, 1.0], got {value}.") + + +@dataclass(frozen=True) +class CascadeConfig: + """Thresholds and bounds controlling `DecisionCascadeRouter.route`. + + Attributes: + needs_ui_threshold: Minimum `gate:needs_ui` probability to render a UI. + tight_budget_ms: Latency budget below which only `TEMPLATE` or + `TEXT_ONLY` routes are allowed. + template_min_confidence: Minimum `route:template` probability required + to select `TEMPLATE` (applies to both tight-budget and normal-budget + routing). + prune_threshold: Minimum `prune::` probability to + keep a component before closure and floor inclusion. + max_components: Maximum total components across catalogs eligible for + per-component pruning questions. + max_questions: Optional cap on total questions in the routing batch. + When adding `prune:*` questions would exceed this cap, pruning + questions are omitted and `PRUNED_CATALOG` falls back to + `FULL_CATALOG`. + layout_floor: Optional explicit sequence of component names always + preserved when present in a catalog during pruning. Defaults to + `None`, which derives a catalog-agnostic structural floor from + `ComponentNodeSpec` metadata (highest-scored Surface-eligible + `CHILD_LIST` container, `CHILD` wrapper, string-bearing leaf, and + action-capable component). Pass `()` to disable the floor. + batch_formatter: Optional callable overriding the default English + `DecisionBatch` state and question builder. + """ + + needs_ui_threshold: float = 0.50 + tight_budget_ms: float = 500.0 + template_min_confidence: float = 0.70 + prune_threshold: float = 0.25 + max_components: int = 128 + max_questions: int | None = None + layout_floor: tuple[str, ...] | None = None + batch_formatter: CascadeBatchFormatter | None = None + + def __post_init__(self) -> None: + _validate_unit_interval("needs_ui_threshold", self.needs_ui_threshold) + _validate_unit_interval("template_min_confidence", self.template_min_confidence) + _validate_unit_interval("prune_threshold", self.prune_threshold) + if not math.isfinite(self.tight_budget_ms) or self.tight_budget_ms < 0.0: + raise ValueError( + f"tight_budget_ms must be non-negative, got {self.tight_budget_ms}." + ) + if self.max_components < 1: + raise ValueError(f"max_components must be >= 1, got {self.max_components}.") + if self.max_questions is not None and self.max_questions < 1: + raise ValueError( + f"max_questions must be >= 1 when set, got {self.max_questions}." + ) + if self.layout_floor is not None: + if isinstance(self.layout_floor, (str, bytes)): + raise TypeError( + "CascadeConfig.layout_floor must be a sequence of component names," + " not a string." + ) + object.__setattr__(self, "layout_floor", tuple(self.layout_floor)) + if self.batch_formatter is not None and not callable(self.batch_formatter): + raise TypeError( + "CascadeConfig.batch_formatter must be callable when provided." + ) + + +@dataclass(frozen=True) +class RouteDecision(Generic[TemplateT]): + """Routing decision returned by `DecisionCascadeRouter.route`. + + Attributes: + tier: Selected `CascadeTier`. + catalogs: Catalogs to pass downstream (pruned for `PRUNED_CATALOG`, + original for `FULL_CATALOG`/`TEMPLATE`/`SANDBOX_APP`, empty for + `TEXT_ONLY`). + template_id: Selected template `id` when `tier` is + `CascadeTier.TEMPLATE`. + template: Selected template object when `tier` is + `CascadeTier.TEMPLATE`. + needs_ui_probability: Calibrated probability of `gate:needs_ui`. + tier_confidence: Confidence score associated with the selected route. + template_confidence: Confidence score of `template` when selected. + reason: Short machine-readable explanation of the routing decision. + answers: Raw `DecisionAnswer` tuple returned by the decision model. + """ + + tier: CascadeTier + catalogs: tuple[CatalogApi, ...] = () + template_id: str | None = None + template: TemplateT | None = None + needs_ui_probability: float = 0.0 + tier_confidence: float = 0.0 + template_confidence: float = 0.0 + reason: str = "" + answers: tuple[DecisionAnswer, ...] = field(default_factory=tuple) + + def __post_init__(self) -> None: + object.__setattr__(self, "tier", CascadeTier(self.tier)) + object.__setattr__(self, "catalogs", tuple(self.catalogs)) + object.__setattr__(self, "answers", tuple(self.answers)) + + +def _rank_candidates( + candidates: Sequence[str], probabilities: Mapping[str, float] +) -> list[tuple[str, float]]: + """Ranks `candidates` by descending finite probability with deterministic tie-break.""" + indexed: list[tuple[int, str, float, float]] = [] + for idx, name in enumerate(candidates): + raw = float(probabilities.get(name, 0.0)) + sort_score = round(-raw, 6) if math.isfinite(raw) else float("inf") + indexed.append((idx, name, raw, sort_score)) + indexed.sort(key=lambda item: (item[3], item[0])) + return [(name, prob) for _, name, prob, _ in indexed] + + +def _best_scored_key( + candidates: Iterable[_NodeKey], + scores: Mapping[_NodeKey, float], + decl_index: Mapping[_NodeKey, int], + *, + preferred_cid_idx: int | None = None, + preferred_kept: set[_NodeKey] | None = None, +) -> _NodeKey | None: + """Returns the highest-scoring node key with deterministic tie-breaking.""" + items = list(candidates) + if not items: + return None + return min( + items, + key=lambda key: ( + 0 if preferred_kept is not None and key in preferred_kept else 1, + round(-scores.get(key, 0.0), 6), + 0 if preferred_cid_idx is not None and key[0] == preferred_cid_idx else 1, + decl_index[key], + ), + ) + + +def _format_cascade_state( + prompt: str, + catalogs: Sequence[CatalogApi], + templates: Sequence[SurfaceTemplateSpec], + latency_budget_ms: float | None, + allow_sandbox_app: bool, +) -> str: + """Formats the default English `DecisionBatch.state` string for cascade routing.""" + catalog_summary = ", ".join( + f"{cat.catalog_id} ({len(cat.components)} components)" for cat in catalogs + ) + parts = [ + f"User request: {prompt}", + f"Catalogs: {catalog_summary}", + f"Registered templates: {len(templates)}", + f"Sandbox app allowed: {allow_sandbox_app}", + ] + if latency_budget_ms is not None: + parts.append(f"Latency budget (ms): {latency_budget_ms:.1f}") + return "\n".join(parts) + + +def _build_tier_options( + has_templates: bool, allow_sandbox_app: bool +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Builds ordered `route:tier` options and parallel descriptions.""" + entries: list[tuple[str, str]] = [] + if has_templates: + entries.append( + ( + CascadeTier.TEMPLATE.value, + "Match a pre-registered UI surface template directly.", + ) + ) + entries.append( + ( + CascadeTier.PRUNED_CATALOG.value, + "Generate a UI surface with a pruned component subset.", + ) + ) + entries.append( + ( + CascadeTier.FULL_CATALOG.value, + "Generate a UI surface with the full component catalogs.", + ) + ) + if allow_sandbox_app: + entries.append( + ( + CascadeTier.SANDBOX_APP.value, + "Launch an interactive sandbox app beyond standard components.", + ) + ) + return tuple(k for k, _ in entries), tuple(d for _, d in entries) + + +def _build_prune_questions( + catalogs: Sequence[CatalogApi], graph: CatalogDecisionGraph +) -> list[DecisionQuestion]: + """Builds `prune::` boolean questions per component.""" + questions: list[DecisionQuestion] = [] + for cid_idx, catalog in enumerate(catalogs): + for comp_name in catalog.components: + spec = graph.get_component_by_key((catalog.catalog_id, comp_name)) + desc = spec.description if spec is not None and spec.description else "" + prompt = ( + f"Keep component '{comp_name}' ({desc}) for this UI?" + if desc + else f"Keep component '{comp_name}' for this UI?" + ) + questions.append( + DecisionQuestion( + id=f"prune:{cid_idx}:{comp_name}", + kind=QuestionKind.BOOLEAN, + prompt=prompt, + ) + ) + return questions + + +def _build_cascade_batch( + *, + prompt: str, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph | None, + templates: Sequence[SurfaceTemplateSpec], + config: CascadeConfig, + latency_budget_ms: float | None, + allow_sandbox_app: bool, + include_tier: bool, + include_prune: bool, + context: Mapping[str, Any] | None, + conversation: Sequence[ConversationTurn], + input_parts: Sequence[InputPart], +) -> DecisionBatch: + """Constructs the default single `DecisionBatch` evaluated by `route()`.""" + del config + questions: list[DecisionQuestion] = [ + DecisionQuestion( + id="gate:needs_ui", + kind=QuestionKind.BOOLEAN, + prompt=( + "Does this request benefit from a visual UI surface over plain text?" + ), + context={ + "yes": "Structured or interactive UI improves clarity or usability.", + "no": "A plain text response answers the request directly.", + }, + ) + ] + if include_tier: + tier_options, tier_texts = _build_tier_options( + bool(templates), allow_sandbox_app + ) + questions.append( + DecisionQuestion( + id="route:tier", + kind=QuestionKind.CHOICE, + prompt="Which rendering tier best fits this request?", + options=tier_options, + option_texts=tier_texts, + allow_none=False, + ) + ) + if templates: + questions.append( + DecisionQuestion( + id="route:template", + kind=QuestionKind.CHOICE, + prompt="Which registered UI surface template matches this request?", + options=tuple(t.id for t in templates), + option_texts=tuple(t.description for t in templates), + allow_none=True, + ) + ) + if include_prune and graph is not None: + questions.extend(_build_prune_questions(catalogs, graph)) + state = _format_cascade_state( + prompt, catalogs, templates, latency_budget_ms, allow_sandbox_app + ) + return DecisionBatch( + shared_context=dict(context) if context is not None else {}, + questions=tuple(questions), + state=state, + conversation=tuple(conversation), + input_parts=tuple(input_parts), + ) + + +def _index_answers( + answers: Sequence[DecisionAnswer], + expected_ids: Sequence[str], +) -> dict[str, DecisionAnswer]: + """Maps model answers by question ID and fails loudly if any are missing.""" + by_id = {ans.question_id: ans for ans in answers} + missing = [qid for qid in expected_ids if qid not in by_id] + if missing: + raise DecisionModelError( + f"Decision model omitted answers for questions: {missing}." + ) + return by_id + + +def _is_surface_eligible(spec: ComponentNodeSpec | None) -> bool: + """Returns whether a component may sit directly at the surface root.""" + if spec is None or not spec.allowed_parents: + return True + return "Surface" in spec.allowed_parents + + +def _edge_allowed( + parent_spec: ComponentNodeSpec | None, + parent_name: str, + child_spec: ComponentNodeSpec | None, + child_name: str, +) -> bool: + """Returns whether `parent_name` may contain `child_name` under catalog rules.""" + if ( + child_spec is not None + and child_spec.allowed_parents + and parent_name not in child_spec.allowed_parents + ): + return False + if ( + parent_spec is not None + and parent_spec.allowed_children + and child_name not in parent_spec.allowed_children + ): + return False + return True + + +def _build_parent_to_children_edges( + all_keys: Sequence[_NodeKey], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + keys_by_name: Mapping[str, list[_NodeKey]], +) -> dict[_NodeKey, list[_NodeKey]]: + """Builds allowed parent-to-child adjacency lists across all active catalogs.""" + children_by_parent: dict[_NodeKey, list[_NodeKey]] = {key: [] for key in all_keys} + for child_key in all_keys: + child_spec = specs.get(child_key) + if child_spec is None or not child_spec.allowed_parents: + continue + child_name = child_key[1] + for parent_name in child_spec.allowed_parents: + for parent_key in keys_by_name.get(parent_name, ()): + if _edge_allowed( + specs.get(parent_key), parent_name, child_spec, child_name + ): + children_by_parent[parent_key].append(child_key) + return children_by_parent + + +def _compute_surface_distances( + all_keys: Sequence[_NodeKey], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + keys_by_name: Mapping[str, list[_NodeKey]], +) -> dict[_NodeKey, int]: + """Computes shortest parent-chain distances to a `"Surface"`-eligible root.""" + children_by_parent = _build_parent_to_children_edges(all_keys, specs, keys_by_name) + distances: dict[_NodeKey, int] = { + key: 0 for key in all_keys if _is_surface_eligible(specs.get(key)) + } + queue: deque[_NodeKey] = deque(distances) + while queue: + parent_key = queue.popleft() + next_dist = distances[parent_key] + 1 + for child_key in children_by_parent[parent_key]: + if child_key not in distances: + distances[child_key] = next_dist + queue.append(child_key) + return distances + + +def _kept_reaching_surface( + kept: set[_NodeKey], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], +) -> set[_NodeKey]: + """Returns the subset of `kept` connected to a `"Surface"`-eligible root.""" + reaching = {key for key in kept if _is_surface_eligible(specs.get(key))} + queue: deque[_NodeKey] = deque(reaching) + while queue: + parent_key = queue.popleft() + parent_spec = specs.get(parent_key) + parent_name = parent_key[1] + for child_key in kept: + if child_key in reaching: + continue + child_spec = specs.get(child_key) + if _edge_allowed(parent_spec, parent_name, child_spec, child_key[1]): + reaching.add(child_key) + queue.append(child_key) + return reaching + + +def _valid_upward_parents( + curr_key: _NodeKey, + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + keys_by_name: Mapping[str, list[_NodeKey]], + dist_to_surface: Mapping[_NodeKey, int], +) -> list[_NodeKey]: + """Returns valid parents of `curr_key` strictly closer to `"Surface"`.""" + curr_spec = specs.get(curr_key) + if curr_spec is None: + return [] + curr_dist = dist_to_surface[curr_key] + curr_name = curr_key[1] + result: list[_NodeKey] = [] + for parent_name in curr_spec.allowed_parents: + for parent_key in keys_by_name.get(parent_name, ()): + if ( + parent_key in dist_to_surface + and dist_to_surface[parent_key] < curr_dist + and _edge_allowed( + specs.get(parent_key), parent_name, curr_spec, curr_name + ) + ): + result.append(parent_key) + return result + + +def _trace_upward_path( + start: _NodeKey, + kept: set[_NodeKey], + reaching: set[_NodeKey], + keys_by_name: Mapping[str, list[_NodeKey]], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + scores: Mapping[_NodeKey, float], + decl_index: Mapping[_NodeKey, int], + dist_to_surface: Mapping[_NodeKey, int], +) -> tuple[list[_NodeKey], bool]: + """Traces best-scored upward parents from `start` until reaching a root.""" + curr = start + path: list[_NodeKey] = [] + while curr not in reaching and not _is_surface_eligible(specs.get(curr)): + candidates = _valid_upward_parents(curr, specs, keys_by_name, dist_to_surface) + best_parent = _best_scored_key( + candidates, + scores, + decl_index, + preferred_cid_idx=curr[0], + preferred_kept=kept, + ) + if best_parent is None: + return path, False + path.append(best_parent) + curr = best_parent + return path, True + + +def _close_upward( + kept: set[_NodeKey], + all_keys: Sequence[_NodeKey], + keys_by_name: Mapping[str, list[_NodeKey]], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + scores: Mapping[_NodeKey, float], + decl_index: Mapping[_NodeKey, int], + dist_to_surface: Mapping[_NodeKey, int], +) -> bool: + """Closes `kept` upward along `allowed_parents` to a `"Surface"`-eligible root.""" + added = False + reaching = _kept_reaching_surface(kept, specs) + for key in all_keys: + if key not in kept or key in reaching or key not in dist_to_surface: + continue + path, reached = _trace_upward_path( + key, + kept, + reaching, + keys_by_name, + specs, + scores, + decl_index, + dist_to_surface, + ) + if not reached: + continue + newly_reaching = [node for node in (*path, key) if node not in reaching] + for node in path: + if node not in kept: + kept.add(node) + added = True + queue: deque[_NodeKey] = deque(newly_reaching) + reaching.update(newly_reaching) + while queue: + parent_key = queue.popleft() + parent_spec = specs.get(parent_key) + parent_name = parent_key[1] + for child_key in kept: + if child_key not in reaching and _edge_allowed( + parent_spec, parent_name, specs.get(child_key), child_key[1] + ): + reaching.add(child_key) + queue.append(child_key) + return added + + +def _valid_children_for( + parent_key: _NodeKey, + parent_spec: ComponentNodeSpec, + keys_by_name: Mapping[str, list[_NodeKey]], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], +) -> list[_NodeKey]: + """Returns mutually valid children in `parent_spec.allowed_children`.""" + parent_name = parent_key[1] + result: list[_NodeKey] = [] + for child_name in parent_spec.allowed_children: + for child_key in keys_by_name.get(child_name, ()): + if _edge_allowed( + parent_spec, parent_name, specs.get(child_key), child_name + ): + result.append(child_key) + return result + + +def _close_downward( + kept: set[_NodeKey], + all_keys: Sequence[_NodeKey], + keys_by_name: Mapping[str, list[_NodeKey]], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + scores: Mapping[_NodeKey, float], + decl_index: Mapping[_NodeKey, int], +) -> bool: + """Ensures kept containers with `allowed_children` retain their top valid child.""" + added = False + for key in all_keys: + if key not in kept: + continue + spec = specs.get(key) + if spec is None or not spec.allowed_children: + continue + valid_children = _valid_children_for(key, spec, keys_by_name, specs) + if not valid_children or any(ch in kept for ch in valid_children): + continue + top_child = _best_scored_key( + valid_children, scores, decl_index, preferred_cid_idx=key[0] + ) + if top_child is not None: + kept.add(top_child) + added = True + return added + + +def _has_string_slot(spec: ComponentNodeSpec) -> bool: + """Returns whether `spec` exposes a string-valued data or literal slot.""" + return any( + slot.kind in (SlotKind.DATA_VALUE, SlotKind.LITERAL_PRIMITIVE) + and slot.value_type == "string" + for slot in spec.slots + ) + + +def _derive_structural_floor( + all_keys: Sequence[_NodeKey], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], + scores: Mapping[_NodeKey, float], + decl_index: Mapping[_NodeKey, int], +) -> set[_NodeKey]: + """Derives a catalog-agnostic structural floor from `ComponentNodeSpec` metadata.""" + child_list_roots: list[_NodeKey] = [] + child_wrapper_roots: list[_NodeKey] = [] + string_leaves: list[_NodeKey] = [] + action_nodes: list[_NodeKey] = [] + for key in all_keys: + spec = specs.get(key) + if spec is None: + continue + if _is_surface_eligible(spec): + if any(slot.kind is SlotKind.CHILD_LIST for slot in spec.slots): + child_list_roots.append(key) + if any(slot.kind is SlotKind.CHILD for slot in spec.slots): + child_wrapper_roots.append(key) + if not spec.is_container and _has_string_slot(spec): + string_leaves.append(key) + if spec.has_action_slot: + action_nodes.append(key) + + floor: set[_NodeKey] = set() + for bucket in ( + child_list_roots, + child_wrapper_roots, + string_leaves, + action_nodes, + ): + winner = _best_scored_key(bucket, scores, decl_index) + if winner is not None: + floor.add(winner) + return floor + + +def _prune_catalogs( + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph, + answers: Mapping[str, DecisionAnswer], + config: CascadeConfig, +) -> tuple[CatalogApi, ...] | None: + """Applies joint cross-catalog pruning, closure, and orphan removal. + + Returns `None` when no `"Surface"`-eligible root survives after pruning. + """ + all_keys: list[_NodeKey] = [] + decl_index: dict[_NodeKey, int] = {} + keys_by_name: dict[str, list[_NodeKey]] = {} + scores: dict[_NodeKey, float] = {} + specs: dict[_NodeKey, ComponentNodeSpec | None] = {} + + for cid_idx, catalog in enumerate(catalogs): + for comp_name in catalog.components: + key: _NodeKey = (cid_idx, comp_name) + decl_index[key] = len(all_keys) + all_keys.append(key) + keys_by_name.setdefault(comp_name, []).append(key) + scores[key] = answers[f"prune:{cid_idx}:{comp_name}"].yes + specs[key] = graph.get_component_by_key((catalog.catalog_id, comp_name)) + + kept: set[_NodeKey] = { + key for key in all_keys if scores[key] >= config.prune_threshold + } + if config.layout_floor is None: + kept.update(_derive_structural_floor(all_keys, specs, scores, decl_index)) + else: + floor_names = set(config.layout_floor) + kept.update(key for key in all_keys if key[1] in floor_names) + + dist_to_surface = _compute_surface_distances(all_keys, specs, keys_by_name) + for _ in range(len(all_keys) + 1): + changed_up = _close_upward( + kept, all_keys, keys_by_name, specs, scores, decl_index, dist_to_surface + ) + changed_down = _close_downward( + kept, all_keys, keys_by_name, specs, scores, decl_index + ) + if not changed_up and not changed_down: + break + + kept &= _kept_reaching_surface(kept, specs) + if not any(_is_surface_eligible(specs.get(key)) for key in kept): + return None + + pruned_catalogs: list[CatalogApi] = [] + for cid_idx, catalog in enumerate(catalogs): + ordered_kept = [name for name in catalog.components if (cid_idx, name) in kept] + pruned_catalogs.append( + ComponentPruningTransformer(ordered_kept).transform(catalog) + ) + return tuple(pruned_catalogs) + + +@experimental +class DecisionCascadeRouter(Generic[TemplateT]): + """Single-batch cascade router gating UI rendering, tier selection, and pruning.""" + + @overload + def __init__( + self: DecisionCascadeRouter[SurfaceTemplateSpec], + decision_model: DecisionModel, + *, + config: CascadeConfig | None = None, + ) -> None: ... + + @overload + def __init__( + self, + decision_model: DecisionModel, + *, + templates: Sequence[TemplateT], + config: CascadeConfig | None = None, + ) -> None: ... + + def __init__( + self, + decision_model: DecisionModel, + *, + templates: Sequence[TemplateT] = (), + config: CascadeConfig | None = None, + ) -> None: + """Initializes the cascade router. + + Args: + decision_model: Async callable answering the routing batch. + templates: Registered surface templates implementing + `SurfaceTemplateSpec`. + config: Threshold and pruning configuration. Defaults to + `CascadeConfig()`. + + Raises: + TypeError: If `decision_model` is not callable. + ValueError: If `templates` contains duplicate template IDs or the + reserved `'none'` ID. + """ + if not callable(decision_model): + raise TypeError("DecisionCascadeRouter requires a callable DecisionModel.") + seen_ids: set[str] = set() + template_tuple = tuple(templates) + for tmpl in template_tuple: + if tmpl.id == "none": + raise ValueError( + "Template id 'none' is reserved for no-template selection." + ) + if tmpl.id in seen_ids: + raise ValueError(f"Duplicate template id {tmpl.id!r}.") + seen_ids.add(tmpl.id) + self._decision_model = decision_model + self._templates = template_tuple + self._templates_by_id: dict[str, TemplateT] = { + tmpl.id: tmpl for tmpl in template_tuple + } + self._config = config if config is not None else CascadeConfig() + + def _select_template( + self, + active_templates: Sequence[TemplateT], + answer: DecisionAnswer, + ) -> tuple[TemplateT | None, float]: + """Selects the winning registered template or returns `(None, none_prob)`.""" + candidates = tuple(t.id for t in active_templates) + ("none",) + ranked = _rank_candidates(candidates, answer.distribution.probabilities) + winner_id, winner_prob = ranked[0] + if winner_id == "none" or not math.isfinite(winner_prob) or winner_prob <= 0.0: + return None, winner_prob if math.isfinite(winner_prob) else 0.0 + return self._templates_by_id[winner_id], winner_prob + + def _resolve_tight_budget( + self, + catalogs: Sequence[CatalogApi], + active_templates: Sequence[TemplateT], + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + answers: tuple[DecisionAnswer, ...], + ) -> RouteDecision[TemplateT]: + """Restricts tight-budget routing to `TEMPLATE` (>= threshold) or `TEXT_ONLY`.""" + if not active_templates: + return RouteDecision( + tier=CascadeTier.TEXT_ONLY, + catalogs=(), + needs_ui_probability=needs_ui_prob, + tier_confidence=1.0, + reason="tight_budget_no_templates", + answers=answers, + ) + tmpl, tmpl_prob = self._select_template( + active_templates, answer_map["route:template"] + ) + if tmpl is not None and tmpl_prob >= self._config.template_min_confidence: + return RouteDecision( + tier=CascadeTier.TEMPLATE, + catalogs=tuple(catalogs), + template_id=tmpl.id, + template=tmpl, + needs_ui_probability=needs_ui_prob, + tier_confidence=tmpl_prob, + template_confidence=tmpl_prob, + reason="tight_budget_template", + answers=answers, + ) + return RouteDecision( + tier=CascadeTier.TEXT_ONLY, + catalogs=(), + needs_ui_probability=needs_ui_prob, + tier_confidence=1.0 - (tmpl_prob if tmpl is not None else 0.0), + reason="tight_budget_below_template_threshold", + answers=answers, + ) + + def _resolve_pruned_tier( + self, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph | None, + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + tier_prob: float, + answers: tuple[DecisionAnswer, ...], + *, + exceeds_max_components: bool, + exceeds_max_questions: bool, + ) -> RouteDecision[TemplateT]: + """Executes `PRUNED_CATALOG` or falls back to `FULL_CATALOG` above caps.""" + if exceeds_max_components: + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="catalog_exceeds_max_components", + answers=answers, + ) + if exceeds_max_questions or graph is None: + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="batch_exceeds_max_questions", + answers=answers, + ) + pruned_catalogs = _prune_catalogs(catalogs, graph, answer_map, self._config) + if pruned_catalogs is None or not any( + cat.components for cat in pruned_catalogs + ): + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="pruned_catalog_empty", + answers=answers, + ) + return RouteDecision( + tier=CascadeTier.PRUNED_CATALOG, + catalogs=pruned_catalogs, + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="selected_pruned_catalog", + answers=answers, + ) + + def _resolve_normal_budget( + self, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph | None, + active_templates: Sequence[TemplateT], + batch: DecisionBatch, + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + answers: tuple[DecisionAnswer, ...], + *, + exceeds_max_components: bool, + exceeds_max_questions: bool, + ) -> RouteDecision[TemplateT]: + """Selects the winning normal-budget tier and applies pruning if chosen.""" + tier_question = next(q for q in batch.questions if q.id == "route:tier") + ranked_tiers = _rank_candidates( + tier_question.options, answer_map["route:tier"].distribution.probabilities + ) + chosen_tier, tier_prob = ranked_tiers[0] + if not math.isfinite(tier_prob) or tier_prob <= 0.0: + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=0.0, + reason="tier_distribution_empty", + answers=answers, + ) + + if chosen_tier == CascadeTier.TEMPLATE.value: + tmpl, tmpl_prob = self._select_template( + active_templates, answer_map["route:template"] + ) + if tmpl is not None and tmpl_prob >= self._config.template_min_confidence: + return RouteDecision( + tier=CascadeTier.TEMPLATE, + catalogs=tuple(catalogs), + template_id=tmpl.id, + template=tmpl, + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + template_confidence=tmpl_prob, + reason="selected_template", + answers=answers, + ) + chosen_tier, tier_prob = next( + (t, p) for t, p in ranked_tiers if t != CascadeTier.TEMPLATE.value + ) + if not math.isfinite(tier_prob) or tier_prob <= 0.0: + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=0.0, + reason="tier_distribution_empty", + answers=answers, + ) + + if chosen_tier == CascadeTier.PRUNED_CATALOG.value: + return self._resolve_pruned_tier( + catalogs, + graph, + answer_map, + needs_ui_prob, + tier_prob, + answers, + exceeds_max_components=exceeds_max_components, + exceeds_max_questions=exceeds_max_questions, + ) + if chosen_tier == CascadeTier.SANDBOX_APP.value: + return RouteDecision( + tier=CascadeTier.SANDBOX_APP, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="selected_sandbox_app", + answers=answers, + ) + return RouteDecision( + tier=CascadeTier.FULL_CATALOG, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="selected_full_catalog", + answers=answers, + ) + + async def route( + self, + prompt: str, + catalogs: Sequence[CatalogApi], + *, + latency_budget_ms: float | None = None, + allow_sandbox_app: bool = False, + context: Mapping[str, Any] | None = None, + conversation: Sequence[ConversationTurn] = (), + input_parts: Sequence[InputPart] = (), + timeout_seconds: float | None = None, + ) -> RouteDecision[TemplateT]: + """Evaluates UI gating, tier routing, and component pruning in one batch. + + Args: + prompt: User prompt or turn intent text. + catalogs: Validated catalogs available for the turn. + latency_budget_ms: Optional turn-level latency budget in + milliseconds. Restricts tight budgets (`< tight_budget_ms`) to + `TEMPLATE` or `TEXT_ONLY` without shortening `timeout_seconds`. + allow_sandbox_app: Whether `CascadeTier.SANDBOX_APP` may be selected. + context: Optional structured context dictionary forwarded to + `DecisionBatch.shared_context` (for example active surface or + domain metadata). + conversation: Optional multi-turn conversation history forwarded to + `DecisionBatch.conversation`. + input_parts: Optional multimodal input parts forwarded to + `DecisionBatch.input_parts`. + timeout_seconds: Optional explicit timeout in seconds enforced by + `invoke_decision_model`. Defaults to `None` (no extra timeout). + + Returns: + A `RouteDecision` describing the selected tier, catalogs, and + optional template. + + Raises: + ValueError: If `catalogs` is empty, `latency_budget_ms` is + non-positive, or `timeout_seconds` is non-positive. + DecisionModelError: If the decision model fails or omits answers. + """ + if not catalogs: + raise ValueError( + "DecisionCascadeRouter.route requires at least one catalog." + ) + if latency_budget_ms is not None: + if not math.isfinite(latency_budget_ms) or latency_budget_ms <= 0.0: + raise ValueError( + f"latency_budget_ms must be positive, got {latency_budget_ms}." + ) + if timeout_seconds is not None: + if not math.isfinite(timeout_seconds) or timeout_seconds <= 0.0: + raise ValueError( + f"timeout_seconds must be positive, got {timeout_seconds}." + ) + + check_mixed_catalogs(catalogs) + + active_catalog_ids = {cat.catalog_id for cat in catalogs} + active_templates = tuple( + tmpl + for tmpl in self._templates + if tmpl.catalog_id is None or tmpl.catalog_id in active_catalog_ids + ) + + tight_budget = ( + latency_budget_ms is not None + and latency_budget_ms < self._config.tight_budget_ms + ) + include_tier = not tight_budget + base_question_count = ( + 1 + (1 if include_tier else 0) + (1 if active_templates else 0) + ) + total_components = sum(len(cat.components) for cat in catalogs) + exceeds_max_components = total_components > self._config.max_components + exceeds_max_questions = ( + self._config.max_questions is not None + and (base_question_count + total_components) > self._config.max_questions + ) + include_prune = ( + not tight_budget + and not exceeds_max_components + and not exceeds_max_questions + ) + + graph: CatalogDecisionGraph | None = None + if include_prune: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + graph = CatalogDecisionGraph(catalogs) + + formatter = self._config.batch_formatter or _build_cascade_batch + batch = formatter( + prompt=prompt, + catalogs=catalogs, + graph=graph, + templates=active_templates, + config=self._config, + latency_budget_ms=latency_budget_ms, + allow_sandbox_app=allow_sandbox_app, + include_tier=include_tier, + include_prune=include_prune, + context=context, + conversation=conversation, + input_parts=input_parts, + ) + answers = await invoke_decision_model( + self._decision_model, batch, timeout_seconds=timeout_seconds + ) + answer_map = _index_answers(answers, [q.id for q in batch.questions]) + + needs_ui_prob = answer_map["gate:needs_ui"].yes + if ( + not math.isfinite(needs_ui_prob) + or needs_ui_prob < self._config.needs_ui_threshold + ): + safe_prob = needs_ui_prob if math.isfinite(needs_ui_prob) else 0.0 + return RouteDecision( + tier=CascadeTier.TEXT_ONLY, + catalogs=(), + needs_ui_probability=safe_prob, + tier_confidence=1.0 - safe_prob, + reason="needs_ui_below_threshold", + answers=answers, + ) + + if tight_budget: + return self._resolve_tight_budget( + catalogs, active_templates, answer_map, needs_ui_prob, answers + ) + + return self._resolve_normal_budget( + catalogs, + graph, + active_templates, + batch, + answer_map, + needs_ui_prob, + answers, + exceeds_max_components=exceeds_max_components, + exceeds_max_questions=exceeds_max_questions, + ) diff --git a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py new file mode 100644 index 0000000000..725e801b30 --- /dev/null +++ b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py @@ -0,0 +1,972 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for `DecisionCascadeRouter` and cascade routing types.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any +import warnings + +import pytest + +from a2ui.core import Catalog, CatalogApi +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.core.schema import ProtocolVersion +from a2ui.inference_formats.experimental.decision import ( + CatalogDecisionGraph, + ConversationTurn, + DecisionAnswer, + DecisionBatch, + DecisionDistribution, + DecisionModelError, + DecisionQuestion, + ExpressSurfaceSpec, + InputPart, + MockDecisionModel, + QuestionKind, + TextInputPart, + build_inference_catalogs, +) +from a2ui.inference_formats.experimental.decision_cascade import ( + CascadeConfig, + CascadeTier, + DecisionCascadeRouter, + RouteDecision, + SurfaceTemplateSpec, +) +from a2ui.transformers.macros import macro +from a2ui.utils._experimental import SUPPRESS_ENV_VAR + + +def _basic_v1() -> CatalogApi: + return BasicCatalog("v1.0") + + +def _custom_catalog( + components: dict[str, dict[str, Any]], + *, + catalog_id: str = "urn:test:cascade", + defs: dict[str, Any] | None = None, +) -> CatalogApi: + payload: dict[str, Any] = { + "catalogId": catalog_id, + "components": { + name: { + "type": "object", + "properties": { + "component": {"const": name}, + **spec.get("properties", {}), + }, + **{k: v for k, v in spec.items() if k != "properties"}, + } + for name, spec in components.items() + }, + } + if defs is not None: + payload["$defs"] = defs + return Catalog.from_json(payload, protocol_version=ProtocolVersion.V1_0) + + +def _templates() -> tuple[ExpressSurfaceSpec, ...]: + return ( + ExpressSurfaceSpec( + id="weather_card", + description="Show weather forecast card", + dsl='surface "s1" { root = Text("Sunny") }', + ), + ExpressSurfaceSpec( + id="flight_status", + description="Show flight status summary", + dsl='surface "s1" { root = Text("On time") }', + ), + ) + + +@dataclass(frozen=True) +class _CustomTemplate: + """Format-agnostic template satisfying `SurfaceTemplateSpec` without Express DSL.""" + + id: str + description: str + catalog_id: str | None = None + payload: dict[str, Any] | None = None + + +class _FailingModel(MockDecisionModel): + async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: + del batch + raise DecisionModelError("decision model timed out") + + +class _OmittingModel(MockDecisionModel): + async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: + answers = await super().__call__(batch) + return answers[1:] + + +@pytest.mark.asyncio +async def test_gate_below_threshold_returns_text_only() -> None: + model = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.49, + "route:tier": "full_catalog", + } + ) + router = DecisionCascadeRouter(model, templates=_templates()) + decision = await router.route( + "What is the capital of France?", + [_basic_v1()], + latency_budget_ms=1200.0, + ) + + assert isinstance(decision, RouteDecision) + assert decision.tier is CascadeTier.TEXT_ONLY + assert decision.catalogs == () + assert decision.template is None + assert decision.template_id is None + assert decision.needs_ui_probability == pytest.approx(0.49) + assert len(model.batches) == 1 + assert model.batches[0].state is not None + assert model.batches[0].shared_context == {} + + +@pytest.mark.asyncio +async def test_tight_latency_budget_selects_confident_template_or_text_only() -> None: + templates = _templates() + model_hit = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:template": ("flight_status", 0.72), + } + ) + router_hit = DecisionCascadeRouter(model_hit, templates=templates) + hit = await router_hit.route( + "Check flight UA 100", [_basic_v1()], latency_budget_ms=300.0 + ) + + assert hit.tier is CascadeTier.TEMPLATE + assert hit.template_id == "flight_status" + assert hit.template == templates[1] + assert hit.template_confidence == pytest.approx(0.72) + + explicit = await router_hit.route( + "Check flight UA 100", + [_basic_v1()], + latency_budget_ms=300.0, + timeout_seconds=2.5, + ) + assert explicit.tier is CascadeTier.TEMPLATE + q_ids = [q.id for q in model_hit.batches[0].questions] + assert "route:tier" not in q_ids + assert not any(qid.startswith("prune:") for qid in q_ids) + + model_miss = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:template": ("weather_card", 0.69), + } + ) + router_miss = DecisionCascadeRouter(model_miss, templates=templates) + miss = await router_miss.route( + "Show complex analytics", [_basic_v1()], latency_budget_ms=499.0 + ) + assert miss.tier is CascadeTier.TEXT_ONLY + assert miss.catalogs == () + + # At exactly 500.0 ms, normal routing applies rather than tight-budget restriction. + backend_boundary = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "full_catalog", + "route:template": ("weather_card", 0.69), + } + ) + router_boundary = DecisionCascadeRouter(backend_boundary, templates=templates) + boundary = await router_boundary.route( + "Show complex analytics", [_basic_v1()], latency_budget_ms=500.0 + ) + assert boundary.tier is CascadeTier.FULL_CATALOG + + +@pytest.mark.asyncio +async def test_tight_budget_with_no_templates_returns_text_only() -> None: + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Show chart", [_basic_v1()], latency_budget_ms=200.0) + assert decision.tier is CascadeTier.TEXT_ONLY + q_ids = [q.id for q in backend.batches[0].questions] + assert q_ids == ["gate:needs_ui"] + + +@pytest.mark.asyncio +async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_app() -> ( + None +): + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": { + "template": 0.50, + "sandbox_app": 0.35, + "pruned_catalog": 0.10, + "full_catalog": 0.05, + }, + "route:template": ("none", 0.85), + } + ) + router = DecisionCascadeRouter(backend, templates=_templates()) + decision = await router.route( + "Open interactive whiteboard", [_basic_v1()], allow_sandbox_app=True + ) + assert decision.tier is CascadeTier.SANDBOX_APP + tier_q = next(q for q in backend.batches[0].questions if q.id == "route:tier") + assert "sandbox_app" in tier_q.options + + +@pytest.mark.asyncio +async def test_over_max_components_routes_pruned_catalog_to_full_catalog() -> None: + comps: dict[str, dict[str, Any]] = {f"Comp{i}": {} for i in range(129)} + large_catalog = _custom_catalog(comps, catalog_id="urn:test:large") + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Build a dashboard", [large_catalog]) + + assert decision.tier is CascadeTier.FULL_CATALOG + assert decision.reason == "catalog_exceeds_max_components" + assert len(decision.catalogs) == 1 + assert len(decision.catalogs[0].components) == 129 + q_ids = [q.id for q in backend.batches[0].questions] + assert not any(qid.startswith("prune:") for qid in q_ids) + + +@pytest.mark.asyncio +async def test_exact_128_components_still_runs_pruned_catalog() -> None: + comps: dict[str, dict[str, Any]] = {f"Comp{i}": {} for i in range(128)} + boundary_catalog = _custom_catalog(comps, catalog_id="urn:test:boundary") + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:0:Comp0": 0.90, + **{f"prune:0:Comp{i}": 0.05 for i in range(1, 128)}, + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Show item 0", [boundary_catalog]) + + assert decision.tier is CascadeTier.PRUNED_CATALOG + assert set(decision.catalogs[0].components) == {"Comp0"} + + +@pytest.mark.asyncio +async def test_pruned_catalog_upward_and_downward_closure_and_explicit_floor() -> None: + # Multi-hop upward closure: Leaf -> Section -> Page (Surface-eligible). + # DeadEndParent has allowedParents: ["MissingRoot"] so it cannot reach Surface. + # Container TabGroup has allowedChildren: ["TabItemA", "TabItemB"] both < 0.25. + # Explicit layout_floor=("Column", "Text") is preserved even below 0.25, while + # "Unused" and "UnusedDef" are pruned out by ComponentPruningTransformer. + catalog = _custom_catalog( + { + "Page": {"allowedParents": ["Surface"]}, + "DeadEndParent": {"allowedParents": ["MissingRoot"]}, + "Section": {"allowedParents": ["Page", "DeadEndParent"]}, + "Leaf": {"allowedParents": ["Section"]}, + "TabGroup": { + "allowedParents": ["Surface"], + "allowedChildren": ["TabItemA", "TabItemB"], + }, + "TabItemA": {"allowedParents": ["TabGroup"]}, + "TabItemB": {"allowedParents": ["TabGroup"]}, + "Column": {}, + "Text": {}, + "Unused": { + "properties": {"extra": {"$ref": "#/$defs/UnusedDef"}}, + }, + }, + defs={"UnusedDef": {"type": "string"}}, + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:0:Page": 0.05, + "prune:0:DeadEndParent": 0.24, + "prune:0:Section": 0.10, + "prune:0:Leaf": 0.80, + "prune:0:TabGroup": 0.70, + "prune:0:TabItemA": 0.10, + "prune:0:TabItemB": 0.20, + "prune:0:Column": 0.05, + "prune:0:Text": 0.05, + "prune:0:Unused": 0.05, + } + ) + router = DecisionCascadeRouter( + backend, + config=CascadeConfig(layout_floor=("Column", "Text")), + ) + decision = await router.route("Show leaf and tabs", [catalog]) + + assert decision.tier is CascadeTier.PRUNED_CATALOG + pruned = decision.catalogs[0] + kept = set(pruned.components) + assert kept == { + "Page", + "Section", + "Leaf", + "TabGroup", + "TabItemB", + "Column", + "Text", + } + assert "UnusedDef" not in pruned.validation_schema.get("$defs", {}) + # Original catalog stays untouched. + assert "Unused" in catalog.components + + +@pytest.mark.asyncio +async def test_multi_catalog_pruning_uses_cid_idx_isolation() -> None: + cat0 = _custom_catalog({"SharedName": {}, "Text": {}}, catalog_id="urn:test:cat0") + cat1 = _custom_catalog( + {"SharedName": {}, "OnlyOne": {}}, catalog_id="urn:test:cat1" + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_catalog", + "prune:0:SharedName": 0.80, + "prune:0:Text": 0.05, + "prune:1:SharedName": 0.05, + "prune:1:OnlyOne": 0.75, + } + ) + router = DecisionCascadeRouter( + backend, config=CascadeConfig(layout_floor=("Text",)) + ) + decision = await router.route("Use SharedName from cat0", [cat0, cat1]) + + assert decision.tier is CascadeTier.PRUNED_CATALOG + assert set(decision.catalogs[0].components) == {"SharedName", "Text"} + assert set(decision.catalogs[1].components) == {"OnlyOne"} + + +@pytest.mark.asyncio +async def test_deterministic_tie_breaking_on_tier_template_and_children() -> None: + # Ties within 1e-6 must resolve strictly by declaration index, even when + # dict insertion order is reversed and probabilities differ at 1e-7. + catalog = _custom_catalog( + { + "Holder": {"allowedChildren": ["FirstChild", "SecondChild"]}, + "FirstChild": {"allowedParents": ["Holder"]}, + "SecondChild": {"allowedParents": ["Holder"]}, + } + ) + templates = _templates() + + # 1. route:tier tie -> "template" (idx 0) beats "pruned_catalog" (idx 1) + # route:template tie -> "weather_card" (idx 0) beats "flight_status" (idx 1) + tier_dist = DecisionAnswer( + question_id="route:tier", + distribution=DecisionDistribution( + probabilities={ + "full_catalog": 0.10, + "pruned_catalog": 0.4500002, + "template": 0.4500001, + } + ), + ) + tmpl_dist = DecisionAnswer( + question_id="route:template", + distribution=DecisionDistribution( + probabilities={ + "none": 0.10, + "flight_status": 0.4500002, + "weather_card": 0.4500001, + } + ), + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": tier_dist, + "route:template": tmpl_dist, + } + ) + router = DecisionCascadeRouter( + backend, + templates=templates, + config=CascadeConfig(template_min_confidence=0.40), + ) + res_tmpl = await router.route("Tie break test", [catalog]) + assert res_tmpl.tier is CascadeTier.TEMPLATE + assert res_tmpl.template_id == "weather_card" + + # 2. Downward closure child tie -> FirstChild (decl idx 1) beats SecondChild (decl idx 2) + prune_backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_catalog", + "prune:0:Holder": 0.80, + "prune:0:FirstChild": 0.1000001, + "prune:0:SecondChild": 0.1000002, + } + ) + prune_router = DecisionCascadeRouter(prune_backend) + res_prune = await prune_router.route("Child tie test", [catalog]) + assert set(res_prune.catalogs[0].components) == {"Holder", "FirstChild"} + + +@pytest.mark.asyncio +async def test_backend_errors_and_omitted_answers_propagate() -> None: + router = DecisionCascadeRouter(_FailingModel()) + with pytest.raises(DecisionModelError, match="decision model timed out"): + await router.route("Show chart", [_basic_v1()]) + + omitting_router = DecisionCascadeRouter(_OmittingModel()) + with pytest.raises(DecisionModelError, match="omitted answers"): + await omitting_router.route("Show chart", [_basic_v1()]) + + +@pytest.mark.asyncio +async def test_validation_and_experimental_warning( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(SUPPRESS_ENV_VAR, raising=False) + with pytest.warns(UserWarning, match=r"\[EXPERIMENTAL\] DecisionCascadeRouter"): + router = DecisionCascadeRouter(MockDecisionModel()) + + # route() must not leak internal [EXPERIMENTAL] CatalogDecisionGraph warnings. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + await router.route("hi", [_basic_v1()]) + assert not any("CatalogDecisionGraph" in str(w.message) for w in caught) + + with pytest.raises(ValueError, match="at least one catalog"): + await router.route("hi", []) + with pytest.raises(ValueError, match="latency_budget_ms must be positive"): + await router.route("hi", [_basic_v1()], latency_budget_ms=0.0) + with pytest.raises(ValueError, match="timeout_seconds must be positive"): + await router.route("hi", [_basic_v1()], timeout_seconds=0.0) + with pytest.raises(TypeError, match="DecisionModel"): + DecisionCascadeRouter("not-a-model") # type: ignore[call-overload] + with pytest.raises(ValueError, match="Duplicate template id"): + DecisionCascadeRouter( + MockDecisionModel(), + templates=( + ExpressSurfaceSpec(id="dup", description="First", dsl="x"), + ExpressSurfaceSpec(id="dup", description="Second", dsl="y"), + ), + ) + with pytest.raises(ValueError, match="reserved"): + DecisionCascadeRouter( + MockDecisionModel(), + templates=(_CustomTemplate(id="none", description="Invalid"),), + ) + with pytest.raises(ValueError, match="needs_ui_threshold"): + CascadeConfig(needs_ui_threshold=1.5) + with pytest.raises(ValueError, match="max_components"): + CascadeConfig(max_components=0) + with pytest.raises(ValueError, match="max_questions"): + CascadeConfig(max_questions=0) + with pytest.raises(TypeError, match="batch_formatter"): + CascadeConfig(batch_formatter="not-callable") # type: ignore[arg-type] + + +@pytest.mark.asyncio +async def test_nested_downward_closure_and_kept_parent_short_circuit() -> None: + catalog = _custom_catalog( + { + "Outer": { + "allowedParents": ["Surface"], + "allowedChildren": ["Inner"], + }, + "Inner": { + "allowedParents": ["Outer"], + "allowedChildren": ["DeepLeaf"], + }, + "DeepLeaf": {"allowedParents": ["Inner"]}, + "AltParent": {"allowedParents": ["Surface"]}, + "KeptParent": {"allowedParents": ["Surface"]}, + "ChildWithTwoParents": { + "allowedParents": ["AltParent", "KeptParent"], + }, + } + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_catalog", + "prune:0:Outer": 0.80, + "prune:0:Inner": 0.10, + "prune:0:DeepLeaf": 0.05, + "prune:0:AltParent": 0.20, + "prune:0:KeptParent": 0.60, + "prune:0:ChildWithTwoParents": 0.70, + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Nested closure", [catalog]) + + assert decision.tier is CascadeTier.PRUNED_CATALOG + assert set(decision.catalogs[0].components) == { + "Outer", + "Inner", + "DeepLeaf", + "KeptParent", + "ChildWithTwoParents", + } + + +@pytest.mark.asyncio +async def test_all_zero_template_distribution_does_not_pick_first_template() -> None: + catalog = BasicCatalog(ProtocolVersion.V1_0) + template = ExpressSurfaceSpec( + id="weather", + description="Weather summary", + dsl='root = Text("Sunny")', + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": ("template", 0.90), + "route:template": {"weather": 0.0, "none": 0.0}, + } + ) + router = DecisionCascadeRouter(backend, templates=(template,)) + decision = await router.route("Show weather", [catalog]) + assert decision.tier is not CascadeTier.TEMPLATE + assert decision.template is None + + +@pytest.mark.asyncio +async def test_empty_pruned_catalog_falls_back_to_full_catalog() -> None: + catalog = _custom_catalog( + { + "Alpha": {"properties": {"id": {"type": "string"}}}, + "Beta": {"properties": {"id": {"type": "string"}}}, + }, + catalog_id="https://example.com/empty_prune/catalog.json", + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": ("pruned_catalog", 0.90), + "prune:0:Alpha": 0.05, + "prune:0:Beta": 0.05, + } + ) + router = DecisionCascadeRouter( + backend, + config=CascadeConfig(layout_floor=(), prune_threshold=0.50), + ) + decision = await router.route("Render custom", [catalog]) + assert decision.tier is CascadeTier.FULL_CATALOG + assert decision.reason == "pruned_catalog_empty" + assert set(decision.catalogs[0].components) == {"Alpha", "Beta"} + + +def test_cascade_config_rejects_bare_str_layout_floor() -> None: + with pytest.raises(TypeError, match="layout_floor"): + CascadeConfig(layout_floor="Column") # type: ignore[arg-type] + + +@pytest.mark.asyncio +async def test_cross_catalog_macro_closure_preserves_parent_and_drops_orphans() -> None: + @macro(allowed_parents=("List",)) # type: ignore[untyped-decorator] + def ItemRow(label: str) -> dict[str, Any]: + return {"component": "Text", "text": label} + + basic = _basic_v1() + catalogs = build_inference_catalogs( + [basic], macros=[ItemRow], macro_catalog_id="urn:test:macros" + ) + scores: dict[str, Any] = { + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:1:ItemRow": 0.95, + } + for name in basic.components: + scores[f"prune:0:{name}"] = 0.05 + + router = DecisionCascadeRouter( + MockDecisionModel(scripted_answers=scores), + config=CascadeConfig(layout_floor=()), + ) + decision = await router.route("List items", catalogs) + + assert decision.tier is CascadeTier.PRUNED_CATALOG + assert "ItemRow" in decision.catalogs[1].components + assert "List" in decision.catalogs[0].components + + # Orphan-only catalog must fall back to FULL_CATALOG when no Surface root survives. + orphan_catalog = _custom_catalog( + { + "ValidRoot": {"allowedParents": ["Surface"]}, + "OrphanOnly": {"allowedParents": ["Missing"]}, + } + ) + orphan_router = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:0:ValidRoot": 0.05, + "prune:0:OrphanOnly": 0.90, + } + ), + config=CascadeConfig(layout_floor=()), + ) + orphan_decision = await orphan_router.route("Orphan only", [orphan_catalog]) + assert orphan_decision.tier is CascadeTier.FULL_CATALOG + assert orphan_decision.reason == "pruned_catalog_empty" + + +@pytest.mark.asyncio +async def test_dynamic_structural_layout_floor_is_catalog_agnostic() -> None: + custom = _custom_catalog( + { + "VStack": { + "allowedParents": ["Surface"], + "properties": { + "children": {"$ref": "#/$defs/ChildList"}, + }, + }, + "Box": { + "allowedParents": ["Surface"], + "properties": { + "child": {"$ref": "#/$defs/ComponentId"}, + }, + }, + "Label": { + "properties": { + "text": {"$ref": "#/$defs/DynamicString"}, + }, + }, + "ActionBtn": { + "properties": { + "action": {"$ref": "#/$defs/Action"}, + }, + }, + "UnusedChart": { + "properties": { + "count": {"type": "number"}, + }, + }, + }, + defs={ + "ChildList": {"type": "array", "items": {"type": "string"}}, + "ComponentId": {"type": "string"}, + "DynamicString": {"type": "string"}, + "Action": {"type": "object"}, + }, + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_catalog", + "prune:0:VStack": 0.10, + "prune:0:Box": 0.10, + "prune:0:Label": 0.10, + "prune:0:ActionBtn": 0.10, + "prune:0:UnusedChart": 0.05, + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Custom catalog", [custom]) + assert decision.tier is CascadeTier.PRUNED_CATALOG + assert set(decision.catalogs[0].components) == { + "VStack", + "Box", + "Label", + "ActionBtn", + } + + +@pytest.mark.asyncio +async def test_templates_filtered_by_active_catalog_id() -> None: + airline_tmpl = _CustomTemplate( + id="airline_pass", + description="Boarding pass", + catalog_id="urn:airline:only", + ) + generic_tmpl = _CustomTemplate( + id="generic_card", + description="Generic summary card", + ) + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "full_catalog", + "route:template": ("generic_card", 0.85), + } + ) + router = DecisionCascadeRouter(backend, templates=(airline_tmpl, generic_tmpl)) + await router.route("boarding pass", [_basic_v1()]) + tmpl_q = next(q for q in backend.batches[0].questions if q.id == "route:template") + assert tmpl_q.options == ("generic_card",) + + # When only an inactive-catalog template is registered, route:template is omitted. + only_airline_backend = MockDecisionModel( + scripted_answers={"gate:needs_ui": 0.90, "route:tier": "full_catalog"} + ) + only_airline_router = DecisionCascadeRouter( + only_airline_backend, templates=(airline_tmpl,) + ) + decision = await only_airline_router.route("boarding pass", [_basic_v1()]) + assert decision.tier is CascadeTier.FULL_CATALOG + q_ids = [q.id for q in only_airline_backend.batches[0].questions] + assert "route:template" not in q_ids + + +@pytest.mark.asyncio +async def test_max_questions_cap_skips_pruning_and_falls_back() -> None: + catalog = _custom_catalog({f"Comp{i}": {} for i in range(10)}) + backend = MockDecisionModel( + scripted_answers={"gate:needs_ui": 0.95, "route:tier": "pruned_catalog"} + ) + router = DecisionCascadeRouter(backend, config=CascadeConfig(max_questions=5)) + decision = await router.route("Small batch model", [catalog]) + + assert decision.tier is CascadeTier.FULL_CATALOG + assert decision.reason == "batch_exceeds_max_questions" + assert not any(q.id.startswith("prune:") for q in backend.batches[0].questions) + + +@pytest.mark.asyncio +async def test_upward_closure_propagates_reachability_and_prefers_kept_parents() -> ( + None +): + # Counterexample 1: Sibling adds MidB -> Item becomes reachable via MidB + # and must not pull RootA. + cat1 = _custom_catalog( + { + "RootA": {"allowedParents": ["Surface"]}, + "RootB": {"allowedParents": ["Surface"]}, + "MidB": {"allowedParents": ["RootB"]}, + "Sibling": {"allowedParents": ["MidB"]}, + "Item": {"allowedParents": ["RootA", "MidB"]}, + } + ) + router1 = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:0:RootA": 0.01, + "prune:0:RootB": 0.90, + "prune:0:MidB": 0.20, + "prune:0:Sibling": 0.85, + "prune:0:Item": 0.85, + } + ), + config=CascadeConfig(layout_floor=()), + ) + dec1 = await router1.route("Shared ancestor", [cat1]) + assert set(dec1.catalogs[0].components) == {"RootB", "MidB", "Sibling", "Item"} + + # Counterexample 2: Leaf1 adds Mid + Root -> Leaf2 is now reachable via Mid + # and must not pull higher-scoring Alt. + cat2 = _custom_catalog( + { + "Root": {"allowedParents": ["Surface"]}, + "Mid": {"allowedParents": ["Root"]}, + "Alt": {"allowedParents": ["Root"]}, + "Leaf1": {"allowedParents": ["Mid"]}, + "Leaf2": {"allowedParents": ["Mid", "Alt"]}, + } + ) + router2 = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_catalog", + "prune:0:Root": 0.05, + "prune:0:Mid": 0.10, + "prune:0:Alt": 0.20, + "prune:0:Leaf1": 0.90, + "prune:0:Leaf2": 0.90, + } + ), + config=CascadeConfig(layout_floor=()), + ) + dec2 = await router2.route("Same distance alt", [cat2]) + assert set(dec2.catalogs[0].components) == {"Root", "Mid", "Leaf1", "Leaf2"} + + +@pytest.mark.asyncio +async def test_empty_tier_distribution_and_nan_gate_are_guarded() -> None: + empty_tier = DecisionAnswer( + question_id="route:tier", + distribution=DecisionDistribution(probabilities={}), + ) + router = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": empty_tier, + "route:template": ("weather_card", 0.95), + } + ), + templates=_templates(), + ) + dec = await router.route("Empty tier", [_basic_v1()]) + assert dec.tier is CascadeTier.FULL_CATALOG + assert dec.reason == "tier_distribution_empty" + assert dec.tier_confidence == 0.0 + + nan_gate = DecisionAnswer( + question_id="gate:needs_ui", + distribution=DecisionDistribution( + probabilities={"yes": float("nan"), "no": 0.0} + ), + ) + nan_router = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": nan_gate, + "route:tier": "full_catalog", + } + ) + ) + nan_dec = await nan_router.route("NaN gate", [_basic_v1()]) + assert nan_dec.tier is CascadeTier.TEXT_ONLY + assert nan_dec.reason == "needs_ui_below_threshold" + + +@pytest.mark.asyncio +async def test_downward_closure_ignores_mutually_disallowed_children() -> None: + catalog = _custom_catalog( + { + "Holder": {"allowedParents": ["Surface"], "allowedChildren": ["X"]}, + "X": {"allowedParents": ["Other"]}, + "Other": {"allowedParents": ["Surface"]}, + } + ) + router = DecisionCascadeRouter( + MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_catalog", + "prune:0:Holder": 0.90, + "prune:0:X": 0.05, + "prune:0:Other": 0.05, + } + ), + config=CascadeConfig(layout_floor=()), + ) + decision = await router.route("Strict children", [catalog]) + assert set(decision.catalogs[0].components) == {"Holder"} + + +@pytest.mark.asyncio +async def test_normal_budget_weak_template_falls_through_to_next_tier() -> None: + backend = MockDecisionModel( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": { + "template": 0.50, + "full_catalog": 0.30, + "pruned_catalog": 0.20, + }, + "route:template": { + "weather_card": 0.36, + "flight_status": 0.34, + "none": 0.30, + }, + } + ) + router = DecisionCascadeRouter(backend, templates=_templates()) + decision = await router.route("Ambiguous template", [_basic_v1()]) + assert decision.tier is CascadeTier.FULL_CATALOG + assert decision.template is None + + +@pytest.mark.asyncio +async def test_route_optional_flags_are_keyword_only() -> None: + router = DecisionCascadeRouter(MockDecisionModel()) + with pytest.raises(TypeError): + await router.route("hi", [_basic_v1()], 300.0) # type: ignore[misc] + + +@pytest.mark.asyncio +async def test_context_conversation_input_parts_and_custom_batch_formatter() -> None: + backend = MockDecisionModel( + scripted_answers={"gate:needs_ui": 0.20, "route:tier": "full_catalog"} + ) + router = DecisionCascadeRouter(backend) + turns = (ConversationTurn(role="user", content="Show sales"),) + parts: tuple[InputPart, ...] = (TextInputPart(text="Q4 table"),) + await router.route( + "Make it a bar chart instead", + [_basic_v1()], + context={"active_surface": "s1"}, + conversation=turns, + input_parts=parts, + ) + sent = backend.batches[0] + assert sent.shared_context == {"active_surface": "s1"} + assert sent.conversation == turns + assert sent.input_parts == parts + + def _custom_formatter( + *, + prompt: str, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph | None, + templates: Sequence[SurfaceTemplateSpec], + config: CascadeConfig, + latency_budget_ms: float | None, + allow_sandbox_app: bool, + include_tier: bool, + include_prune: bool, + context: Mapping[str, Any] | None, + conversation: Sequence[ConversationTurn], + input_parts: Sequence[InputPart], + ) -> DecisionBatch: + del catalogs, graph, templates, config, latency_budget_ms + del allow_sandbox_app, include_tier, include_prune + return DecisionBatch( + shared_context=dict(context or {}), + state=f"CUSTOM_STATE: {prompt}", + conversation=tuple(conversation), + input_parts=tuple(input_parts), + questions=( + DecisionQuestion( + id="gate:needs_ui", + kind=QuestionKind.BOOLEAN, + prompt="Custom gate?", + ), + ), + ) + + custom_backend = MockDecisionModel(scripted_answers={"gate:needs_ui": 0.10}) + custom_router = DecisionCascadeRouter( + custom_backend, + config=CascadeConfig(batch_formatter=_custom_formatter), + ) + custom_decision = await custom_router.route("Hola", [_basic_v1()]) + assert custom_decision.tier is CascadeTier.TEXT_ONLY + assert custom_backend.batches[0].state == "CUSTOM_STATE: Hola"