From 832c90c3c90d538177a61d7cfd8cd6556e55087e Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Fri, 20 Nov 2026 01:51:59 +0000 Subject: [PATCH 1/4] feat(decision_cascade): add single-batch UI gate and catalog-pruning router Signed-off-by: Greg Spencer --- python/a2ui_agent/CHANGELOG.md | 4 + .../experimental/decision_cascade/__init__.py | 34 + .../experimental/decision_cascade/router.py | 825 ++++++++++++++++++ .../decision_cascade/test_cascade_router.py | 571 ++++++++++++ 4 files changed, 1434 insertions(+) create mode 100644 python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/__init__.py create mode 100644 python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/router.py create mode 100644 python/a2ui_agent/tests/decision_cascade/test_cascade_router.py diff --git a/python/a2ui_agent/CHANGELOG.md b/python/a2ui_agent/CHANGELOG.md index df3b688067..4c60110bfa 100644 --- a/python/a2ui_agent/CHANGELOG.md +++ b/python/a2ui_agent/CHANGELOG.md @@ -1,5 +1,9 @@ ## Unreleased +- Add `DecisionCascadeRouter` in + `a2ui.inference_formats.experimental.decision_cascade` for single-batch UI + gating, template selection, and `ComponentPruningTransformer` catalog pruning. + - **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 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..1b55a93a4f --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/__init__.py @@ -0,0 +1,34 @@ +# 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 a2ui.inference_formats.experimental.decision import ExpressSurfaceSpec + +from .router import ( + CascadeConfig, + CascadeTier, + DecisionCascadeRouter, + RouteDecision, +) + +__all__ = [ + "CascadeConfig", + "CascadeTier", + "DecisionCascadeRouter", + "ExpressSurfaceSpec", + "RouteDecision", +] 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..d756a0ac16 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_cascade/router.py @@ -0,0 +1,825 @@ +# 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 a2ui.catalog_transformers import ComponentPruningTransformer +from a2ui.core import CatalogApi +from a2ui.inference_formats.experimental.decision import ( + CatalogDecisionGraph, + ComponentNodeSpec, + DecisionAnswer, + DecisionBackend, + DecisionBackendError, + DecisionBatch, + DecisionQuestion, + ExpressSurfaceSpec, + QuestionKind, +) +from a2ui.utils._experimental import experimental + +_DEFAULT_LAYOUT_FLOOR: tuple[str, ...] = ( + "Column", + "Row", + "Card", + "Text", + "Button", +) + + +class CascadeTier(str, Enum): + """Execution tier selected by `DecisionCascadeRouter`.""" + + TEXT_ONLY = "text_only" + TEMPLATE = "template" + PRUNED_EXPRESS = "pruned_express" + FULL_EXPRESS = "full_express" + 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) + + +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` under a tight latency budget. + 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. + layout_floor: Layout primitive names always preserved when present in a + catalog during pruning. + """ + + 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 + layout_floor: tuple[str, ...] = _DEFAULT_LAYOUT_FLOOR + + 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 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)) + + +@dataclass(frozen=True) +class RouteDecision: + """Routing decision returned by `DecisionCascadeRouter.route`. + + Attributes: + tier: Selected `CascadeTier`. + catalogs: Catalogs to pass downstream (pruned for `PRUNED_EXPRESS`, + original for `FULL_EXPRESS`/`TEMPLATE`/`SANDBOX_APP`, empty for + `TEXT_ONLY`). + template_id: Selected `ExpressSurfaceSpec.id` when `tier` is + `CascadeTier.TEMPLATE`. + template: Selected `ExpressSurfaceSpec` 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 backend. + """ + + tier: CascadeTier + catalogs: tuple[CatalogApi, ...] = () + template_id: str | None = None + template: ExpressSurfaceSpec | 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 probability with deterministic tie-break.""" + indexed = [ + (idx, name, float(probabilities.get(name, 0.0))) + for idx, name in enumerate(candidates) + ] + indexed.sort(key=lambda item: (round(-item[2], 6), item[0])) + return [(name, prob) for _, name, prob in indexed] + + +def _best_scored( + candidates: Iterable[str], + scores: Mapping[str, float], + decl_index: Mapping[str, int], +) -> str | None: + """Returns the highest-scoring candidate, breaking ties by declaration index.""" + items = list(candidates) + if not items: + return None + return min( + items, + key=lambda name: (round(-scores.get(name, 0.0), 6), decl_index[name]), + ) + + +def _format_cascade_state( + prompt: str, + catalogs: Sequence[CatalogApi], + templates: Sequence[ExpressSurfaceSpec], + latency_budget_ms: float | None, + allow_sandbox_app: bool, +) -> str: + """Formats the explicit `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 Express surface template directly.", + )) + entries.append(( + CascadeTier.PRUNED_EXPRESS.value, + "Generate an Express surface with a pruned component subset.", + )) + entries.append(( + CascadeTier.FULL_EXPRESS.value, + "Generate an Express 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, + templates: Sequence[ExpressSurfaceSpec], + config: CascadeConfig, + latency_budget_ms: float | None, + allow_sandbox_app: bool, +) -> DecisionBatch: + """Constructs the single `DecisionBatch` evaluated by `route()`.""" + 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.", + }, + ) + ] + 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 Express 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, + ) + ) + total_components = sum(len(cat.components) for cat in catalogs) + tight_budget = ( + latency_budget_ms is not None and latency_budget_ms < config.tight_budget_ms + ) + if not tight_budget and total_components <= config.max_components: + questions.extend(_build_prune_questions(catalogs, graph)) + state = _format_cascade_state( + prompt, catalogs, templates, latency_budget_ms, allow_sandbox_app + ) + return DecisionBatch(state=state, questions=tuple(questions)) + + +def _index_answers( + answers: Sequence[DecisionAnswer], + expected_ids: Sequence[str], + backend: DecisionBackend, +) -> dict[str, DecisionAnswer]: + """Maps backend 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 DecisionBackendError( + f"Decision backend omitted answers for questions: {missing}.", + backend_kind=backend.backend_kind, + model_id=backend.model_id, + ) + 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( + comp_names: Sequence[str], + specs: Mapping[str, ComponentNodeSpec | None], +) -> dict[str, list[str]]: + """Builds allowed parent-to-child adjacency lists across `comp_names`.""" + comp_set = set(comp_names) + children_by_parent: dict[str, list[str]] = {name: [] for name in comp_names} + for child in comp_names: + child_spec = specs.get(child) + if child_spec is None: + continue + for parent in child_spec.allowed_parents: + if parent in comp_set and _edge_allowed( + specs.get(parent), parent, child_spec, child + ): + children_by_parent[parent].append(child) + return children_by_parent + + +def _compute_surface_distances( + comp_names: Sequence[str], + specs: Mapping[str, ComponentNodeSpec | None], +) -> dict[str, int]: + """Computes shortest parent-chain distances to a `"Surface"`-eligible root.""" + children_by_parent = _build_parent_to_children_edges(comp_names, specs) + distances: dict[str, int] = { + name: 0 for name in comp_names if _is_surface_eligible(specs.get(name)) + } + queue: deque[str] = deque(distances) + while queue: + parent = queue.popleft() + next_dist = distances[parent] + 1 + for child in children_by_parent[parent]: + if child not in distances: + distances[child] = next_dist + queue.append(child) + return distances + + +def _kept_reaching_surface( + kept: set[str], + specs: Mapping[str, ComponentNodeSpec | None], +) -> set[str]: + """Returns the subset of `kept` connected to a `"Surface"`-eligible root.""" + reaching = {name for name in kept if _is_surface_eligible(specs.get(name))} + queue: deque[str] = deque(reaching) + while queue: + parent = queue.popleft() + parent_spec = specs.get(parent) + for child in kept: + if child in reaching: + continue + child_spec = specs.get(child) + if _edge_allowed(parent_spec, parent, child_spec, child): + reaching.add(child) + queue.append(child) + return reaching + + +def _valid_upward_parents( + curr: str, + specs: Mapping[str, ComponentNodeSpec | None], + comp_set: set[str], + dist_to_surface: Mapping[str, int], +) -> list[str]: + """Returns valid parents of `curr` strictly closer to `"Surface"`.""" + curr_spec = specs.get(curr) + if curr_spec is None: + return [] + curr_dist = dist_to_surface[curr] + return [ + parent + for parent in curr_spec.allowed_parents + if parent in comp_set + and parent in dist_to_surface + and dist_to_surface[parent] < curr_dist + and _edge_allowed(specs.get(parent), parent, curr_spec, curr) + ] + + +def _trace_upward_path( + start: str, + reaching: set[str], + comp_set: set[str], + specs: Mapping[str, ComponentNodeSpec | None], + scores: Mapping[str, float], + decl_index: Mapping[str, int], + dist_to_surface: Mapping[str, int], +) -> tuple[list[str], bool]: + """Traces best-scored upward parents from `start` until reaching a root.""" + curr = start + path: list[str] = [] + while curr not in reaching and not _is_surface_eligible(specs.get(curr)): + candidates = _valid_upward_parents(curr, specs, comp_set, dist_to_surface) + best_parent = _best_scored(candidates, scores, decl_index) + if best_parent is None: + return path, False + path.append(best_parent) + curr = best_parent + return path, True + + +def _close_upward( + kept: set[str], + comp_names: Sequence[str], + specs: Mapping[str, ComponentNodeSpec | None], + scores: Mapping[str, float], + decl_index: Mapping[str, int], + dist_to_surface: Mapping[str, int], +) -> bool: + """Closes `kept` upward along `allowed_parents` to a `"Surface"`-eligible root.""" + added = False + comp_set = set(comp_names) + reaching = _kept_reaching_surface(kept, specs) + for name in comp_names: + if name not in kept or name in reaching or name not in dist_to_surface: + continue + path, reached = _trace_upward_path( + name, reaching, comp_set, specs, scores, decl_index, dist_to_surface + ) + if not reached: + continue + for node in path: + if node not in kept: + kept.add(node) + added = True + reaching.add(node) + reaching.add(name) + return added + + +def _valid_children_for( + parent_name: str, + parent_spec: ComponentNodeSpec, + comp_set: set[str], + specs: Mapping[str, ComponentNodeSpec | None], +) -> list[str]: + """Returns valid children in `parent_spec.allowed_children` existing in catalog.""" + strict = [ + ch + for ch in parent_spec.allowed_children + if ch in comp_set and _edge_allowed(parent_spec, parent_name, specs.get(ch), ch) + ] + if strict: + return strict + return [ch for ch in parent_spec.allowed_children if ch in comp_set] + + +def _close_downward( + kept: set[str], + comp_names: Sequence[str], + specs: Mapping[str, ComponentNodeSpec | None], + scores: Mapping[str, float], + decl_index: Mapping[str, int], +) -> bool: + """Ensures kept containers with `allowed_children` retain their top valid child.""" + added = False + comp_set = set(comp_names) + for name in comp_names: + if name not in kept: + continue + spec = specs.get(name) + if spec is None or not spec.allowed_children: + continue + valid_children = _valid_children_for(name, spec, comp_set, specs) + if not valid_children or any(ch in kept for ch in valid_children): + continue + top_child = _best_scored(valid_children, scores, decl_index) + if top_child is not None: + kept.add(top_child) + added = True + return added + + +def _prune_single_catalog( + catalog: CatalogApi, + cid_idx: int, + graph: CatalogDecisionGraph, + answers: Mapping[str, DecisionAnswer], + config: CascadeConfig, +) -> CatalogApi: + """Applies threshold pruning, layout floor, closure, and `ComponentPruningTransformer`.""" + comp_names = list(catalog.components.keys()) + decl_index = {name: idx for idx, name in enumerate(comp_names)} + scores = {name: answers[f"prune:{cid_idx}:{name}"].yes for name in comp_names} + specs = { + name: graph.get_component_by_key((catalog.catalog_id, name)) + for name in comp_names + } + kept: set[str] = { + name for name in comp_names if scores[name] >= config.prune_threshold + } + kept.update(name for name in config.layout_floor if name in decl_index) + + dist_to_surface = _compute_surface_distances(comp_names, specs) + for _ in range(len(comp_names) + 1): + changed_up = _close_upward( + kept, comp_names, specs, scores, decl_index, dist_to_surface + ) + changed_down = _close_downward(kept, comp_names, specs, scores, decl_index) + if not changed_up and not changed_down: + break + + ordered_kept = [name for name in comp_names if name in kept] + return ComponentPruningTransformer(ordered_kept).transform(catalog) + + +@experimental +class DecisionCascadeRouter: + """Single-batch cascade router gating UI rendering, tier selection, and pruning.""" + + def __init__( + self, + backend: DecisionBackend, + *, + templates: Sequence[ExpressSurfaceSpec] = (), + config: CascadeConfig | None = None, + ) -> None: + """Initializes the cascade router. + + Args: + backend: Decision backend answering the routing batch. + templates: Registered Express `.a2ui` surface templates. + config: Threshold and pruning configuration. Defaults to + `CascadeConfig()`. + + Raises: + TypeError: If `backend` is not a `DecisionBackend`. + ValueError: If `templates` contains duplicate template IDs. + """ + if not isinstance(backend, DecisionBackend): + raise TypeError( + "DecisionCascadeRouter requires a DecisionBackend instance." + ) + seen_ids: set[str] = set() + template_tuple = tuple(templates) + for tmpl in template_tuple: + if tmpl.id in seen_ids: + raise ValueError(f"Duplicate ExpressSurfaceSpec id {tmpl.id!r}.") + seen_ids.add(tmpl.id) + self._backend = backend + self._templates = template_tuple + self._templates_by_id = {tmpl.id: tmpl for tmpl in template_tuple} + self._config = config if config is not None else CascadeConfig() + + def _select_template( + self, answer: DecisionAnswer + ) -> tuple[ExpressSurfaceSpec | None, float]: + """Selects the winning registered template or returns `(None, none_prob)`.""" + candidates = tuple(t.id for t in self._templates) + ("none",) + ranked = _rank_candidates(candidates, answer.distribution.probabilities) + winner_id, winner_prob = ranked[0] + if winner_id == "none" or winner_prob <= 0.0: + return None, winner_prob + return self._templates_by_id[winner_id], winner_prob + + def _resolve_tight_budget( + self, + catalogs: Sequence[CatalogApi], + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + answers: tuple[DecisionAnswer, ...], + ) -> RouteDecision: + """Restricts tight-budget routing to `TEMPLATE` (>= threshold) or `TEXT_ONLY`.""" + if not self._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(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, + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + tier_prob: float, + answers: tuple[DecisionAnswer, ...], + ) -> RouteDecision: + """Executes `PRUNED_EXPRESS` or falls back to `FULL_EXPRESS` above cap.""" + total_components = sum(len(cat.components) for cat in catalogs) + if total_components > self._config.max_components: + return RouteDecision( + tier=CascadeTier.FULL_EXPRESS, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="catalog_exceeds_max_components", + answers=answers, + ) + pruned_catalogs = tuple( + _prune_single_catalog(cat, cid_idx, graph, answer_map, self._config) + for cid_idx, cat in enumerate(catalogs) + ) + if not any(cat.components for cat in pruned_catalogs): + return RouteDecision( + tier=CascadeTier.FULL_EXPRESS, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="pruned_catalog_empty", + answers=answers, + ) + return RouteDecision( + tier=CascadeTier.PRUNED_EXPRESS, + catalogs=pruned_catalogs, + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="selected_pruned_express", + answers=answers, + ) + + def _resolve_normal_budget( + self, + catalogs: Sequence[CatalogApi], + graph: CatalogDecisionGraph, + batch: DecisionBatch, + answer_map: Mapping[str, DecisionAnswer], + needs_ui_prob: float, + answers: tuple[DecisionAnswer, ...], + ) -> RouteDecision: + """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 chosen_tier == CascadeTier.TEMPLATE.value: + tmpl, tmpl_prob = self._select_template(answer_map["route:template"]) + if tmpl is not None: + 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 chosen_tier == CascadeTier.PRUNED_EXPRESS.value: + return self._resolve_pruned_tier( + catalogs, graph, answer_map, needs_ui_prob, tier_prob, answers + ) + 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_EXPRESS, + catalogs=tuple(catalogs), + needs_ui_probability=needs_ui_prob, + tier_confidence=tier_prob, + reason="selected_full_express", + answers=answers, + ) + + async def route( + self, + prompt: str, + catalogs: Sequence[CatalogApi], + latency_budget_ms: float | None = None, + allow_sandbox_app: bool = False, + ) -> RouteDecision: + """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 latency budget in milliseconds. Sets + `timeout_seconds = latency_budget_ms / 1000.0` on the backend + call and restricts tight budgets (`< tight_budget_ms`) to + `TEMPLATE` or `TEXT_ONLY`. + allow_sandbox_app: Whether `CascadeTier.SANDBOX_APP` may be selected. + + Returns: + A `RouteDecision` describing the selected tier, catalogs, and + optional template. + + Raises: + ValueError: If `catalogs` is empty or `latency_budget_ms` is + non-positive. + DecisionBackendError: If the decision backend fails or omits answers. + """ + if not catalogs: + raise ValueError( + "DecisionCascadeRouter.route requires at least one catalog." + ) + timeout_seconds: float | None = None + 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}." + ) + timeout_seconds = latency_budget_ms / 1000.0 + + graph = CatalogDecisionGraph(catalogs) + batch = _build_cascade_batch( + prompt, + catalogs, + graph, + self._templates, + self._config, + latency_budget_ms, + allow_sandbox_app, + ) + answers = await self._backend.answer(batch, timeout_seconds=timeout_seconds) + answer_map = _index_answers( + answers, [q.id for q in batch.questions], self._backend + ) + + needs_ui_prob = answer_map["gate:needs_ui"].yes + if needs_ui_prob < self._config.needs_ui_threshold: + return RouteDecision( + tier=CascadeTier.TEXT_ONLY, + catalogs=(), + needs_ui_probability=needs_ui_prob, + tier_confidence=1.0 - needs_ui_prob, + reason="needs_ui_below_threshold", + answers=answers, + ) + + if ( + latency_budget_ms is not None + and latency_budget_ms < self._config.tight_budget_ms + ): + return self._resolve_tight_budget( + catalogs, answer_map, needs_ui_prob, answers + ) + + return self._resolve_normal_budget( + catalogs, graph, batch, answer_map, needs_ui_prob, answers + ) 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..93f8496486 --- /dev/null +++ b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py @@ -0,0 +1,571 @@ +# 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 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 ( + DecisionAnswer, + DecisionBackendError, + DecisionBatch, + DecisionDistribution, + DeterministicMockBackend, +) +from a2ui.inference_formats.experimental.decision_cascade import ( + CascadeConfig, + CascadeTier, + DecisionCascadeRouter, + ExpressSurfaceSpec, + RouteDecision, +) +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") }', + ), + ) + + +class _RecordingTimeoutBackend(DeterministicMockBackend): + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.timeouts: list[float | None] = [] + + async def answer( + self, + batch: DecisionBatch, + *, + timeout_seconds: float | None = None, + ) -> tuple[DecisionAnswer, ...]: + self.timeouts.append(timeout_seconds) + return await super().answer(batch, timeout_seconds=timeout_seconds) + + +class _FailingBackend(DeterministicMockBackend): + + async def answer( + self, + batch: DecisionBatch, + *, + timeout_seconds: float | None = None, + ) -> tuple[DecisionAnswer, ...]: + del batch, timeout_seconds + raise DecisionBackendError( + "backend timed out", backend_kind="jev", model_id="jev-1.14.0" + ) + + +class _OmittingBackend(DeterministicMockBackend): + + async def answer( + self, + batch: DecisionBatch, + *, + timeout_seconds: float | None = None, + ) -> tuple[DecisionAnswer, ...]: + answers = await super().answer(batch, timeout_seconds=timeout_seconds) + return answers[1:] + + +@pytest.mark.asyncio +async def test_gate_below_threshold_returns_text_only() -> None: + backend = _RecordingTimeoutBackend( + scripted_answers={ + "gate:needs_ui": 0.49, + "route:tier": "full_express", + } + ) + router = DecisionCascadeRouter(backend, 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 backend.timeouts == [1.2] + assert len(backend.batches) == 1 + assert backend.batches[0].state is not None + assert backend.batches[0].shared_context == {} + + +@pytest.mark.asyncio +async def test_tight_latency_budget_selects_confident_template_or_text_only() -> None: + templates = _templates() + backend_hit = _RecordingTimeoutBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "full_express", + "route:template": ("flight_status", 0.72), + } + ) + router_hit = DecisionCascadeRouter(backend_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) + assert backend_hit.timeouts == [0.3] + q_ids = [q.id for q in backend_hit.batches[0].questions] + assert not any(qid.startswith("prune:") for qid in q_ids) + + backend_miss = _RecordingTimeoutBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "full_express", + "route:template": ("weather_card", 0.69), + } + ) + router_miss = DecisionCascadeRouter(backend_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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "full_express", + "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_EXPRESS + + +@pytest.mark.asyncio +async def test_tight_budget_with_no_templates_returns_text_only() -> None: + backend = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "full_express", + } + ) + 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 "route:template" not in q_ids + tier_q = next(q for q in backend.batches[0].questions if q.id == "route:tier") + assert "template" not in tier_q.options + assert "sandbox_app" not in tier_q.options + + +@pytest.mark.asyncio +async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_app() -> ( + None +): + backend = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": { + "template": 0.50, + "sandbox_app": 0.35, + "pruned_express": 0.10, + "full_express": 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_express_to_full_express() -> None: + comps = {f"Comp{i}": {} for i in range(129)} + large_catalog = _custom_catalog(comps, catalog_id="urn:test:large") + backend = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_express", + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Build a dashboard", [large_catalog]) + + assert decision.tier is CascadeTier.FULL_EXPRESS + 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_express() -> None: + comps = {f"Comp{i}": {} for i in range(128)} + boundary_catalog = _custom_catalog(comps, catalog_id="urn:test:boundary") + backend = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_express", + "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_EXPRESS + assert set(decision.catalogs[0].components) == {"Comp0"} + + +@pytest.mark.asyncio +async def test_pruned_express_upward_and_downward_closure_and_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. + # 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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.95, + "route:tier": "pruned_express", + "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) + decision = await router.route("Show leaf and tabs", [catalog]) + + assert decision.tier is CascadeTier.PRUNED_EXPRESS + 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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_express", + "prune:0:SharedName": 0.80, + "prune:0:Text": 0.05, + "prune:1:SharedName": 0.05, + "prune:1:OnlyOne": 0.75, + } + ) + router = DecisionCascadeRouter(backend) + decision = await router.route("Use SharedName from cat0", [cat0, cat1]) + + assert decision.tier is CascadeTier.PRUNED_EXPRESS + 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_express" (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_express": 0.10, + "pruned_express": 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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": tier_dist, + "route:template": tmpl_dist, + } + ) + router = DecisionCascadeRouter(backend, templates=templates) + 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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_express", + "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(_FailingBackend()) + with pytest.raises(DecisionBackendError, match="backend timed out"): + await router.route("Show chart", [_basic_v1()]) + + omitting_router = DecisionCascadeRouter(_OmittingBackend()) + with pytest.raises(DecisionBackendError, 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(DeterministicMockBackend()) + + 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(TypeError, match="DecisionBackend"): + DecisionCascadeRouter("not-a-backend") # type: ignore[arg-type] + with pytest.raises(ValueError, match="Duplicate ExpressSurfaceSpec"): + DecisionCascadeRouter( + DeterministicMockBackend(), + templates=( + ExpressSurfaceSpec(id="dup", description="First", dsl="x"), + ExpressSurfaceSpec(id="dup", description="Second", dsl="y"), + ), + ) + 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) + + +@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 = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": "pruned_express", + "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_EXPRESS + 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 = DeterministicMockBackend( + 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_express() -> None: + catalog = _custom_catalog( + { + "Alpha": {"properties": {"id": {"type": "string"}}}, + "Beta": {"properties": {"id": {"type": "string"}}}, + }, + catalog_id="https://example.com/empty_prune/catalog.json", + ) + backend = DeterministicMockBackend( + scripted_answers={ + "gate:needs_ui": 0.90, + "route:tier": ("pruned_express", 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_EXPRESS + 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] From 10e439b028c9073fd8aa564a2ff8f5249c90aea2 Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Fri, 20 Nov 2026 03:52:07 +0000 Subject: [PATCH 2/4] fix(decision_cascade): decouple transport timeout_seconds from routing latency_budget_ms Signed-off-by: Greg Spencer --- .../experimental/decision_cascade/router.py | 24 ++++++++++++------- .../decision_cascade/test_cascade_router.py | 16 +++++++++++-- 2 files changed, 30 insertions(+), 10 deletions(-) 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 index d756a0ac16..f93fb369fd 100644 --- 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 @@ -753,38 +753,46 @@ async def route( catalogs: Sequence[CatalogApi], latency_budget_ms: float | None = None, allow_sandbox_app: bool = False, + *, + timeout_seconds: float | None = None, ) -> RouteDecision: """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 latency budget in milliseconds. Sets - `timeout_seconds = latency_budget_ms / 1000.0` on the backend - call and restricts tight budgets (`< tight_budget_ms`) to - `TEMPLATE` or `TEXT_ONLY`. + latency_budget_ms: Optional turn-level latency budget in + milliseconds. Restricts tight budgets (`< tight_budget_ms`) to + `TEMPLATE` or `TEXT_ONLY` without shortening the decision + backend's transport timeout. allow_sandbox_app: Whether `CascadeTier.SANDBOX_APP` may be selected. + timeout_seconds: Optional explicit transport deadline in seconds + forwarded to `DecisionBackend.answer`. Defaults to `None` (uses + the backend's configured timeout). Returns: A `RouteDecision` describing the selected tier, catalogs, and optional template. Raises: - ValueError: If `catalogs` is empty or `latency_budget_ms` is - non-positive. + ValueError: If `catalogs` is empty, `latency_budget_ms` is + non-positive, or `timeout_seconds` is non-positive. DecisionBackendError: If the decision backend fails or omits answers. """ if not catalogs: raise ValueError( "DecisionCascadeRouter.route requires at least one catalog." ) - timeout_seconds: float | None = None 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}." ) - timeout_seconds = latency_budget_ms / 1000.0 + 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}." + ) graph = CatalogDecisionGraph(catalogs) batch = _build_cascade_batch( diff --git a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py index 93f8496486..778e0ad41e 100644 --- a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py +++ b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py @@ -148,7 +148,7 @@ async def test_gate_below_threshold_returns_text_only() -> None: assert decision.template is None assert decision.template_id is None assert decision.needs_ui_probability == pytest.approx(0.49) - assert backend.timeouts == [1.2] + assert backend.timeouts == [None] assert len(backend.batches) == 1 assert backend.batches[0].state is not None assert backend.batches[0].shared_context == {} @@ -173,7 +173,17 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> assert hit.template_id == "flight_status" assert hit.template == templates[1] assert hit.template_confidence == pytest.approx(0.72) - assert backend_hit.timeouts == [0.3] + # Tight routing budget does not shorten the decision backend transport timeout. + assert backend_hit.timeouts == [None] + + 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 + assert backend_hit.timeouts == [None, 2.5] q_ids = [q.id for q in backend_hit.batches[0].questions] assert not any(qid.startswith("prune:") for qid in q_ids) @@ -459,6 +469,8 @@ async def test_validation_and_experimental_warning( 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="DecisionBackend"): DecisionCascadeRouter("not-a-backend") # type: ignore[arg-type] with pytest.raises(ValueError, match="Duplicate ExpressSurfaceSpec"): From ab224e1aa5820493b6c783bbbc6985ce1a9d86c0 Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Mon, 30 Nov 2026 19:02:53 +0000 Subject: [PATCH 3/4] refactor(decision_cascade): switch to DecisionModel callable Signed-off-by: Greg Spencer --- .../experimental/decision_cascade/router.py | 34 +++--- .../decision_cascade/test_cascade_router.py | 111 ++++++------------ 2 files changed, 54 insertions(+), 91 deletions(-) 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 index f93fb369fd..448e094e03 100644 --- 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 @@ -28,12 +28,13 @@ CatalogDecisionGraph, ComponentNodeSpec, DecisionAnswer, - DecisionBackend, - DecisionBackendError, DecisionBatch, + DecisionModel, + DecisionModelError, DecisionQuestion, ExpressSurfaceSpec, QuestionKind, + invoke_decision_model, ) from a2ui.utils._experimental import experimental @@ -311,16 +312,13 @@ def _build_cascade_batch( def _index_answers( answers: Sequence[DecisionAnswer], expected_ids: Sequence[str], - backend: DecisionBackend, ) -> dict[str, DecisionAnswer]: - """Maps backend answers by question ID and fails loudly if any are missing.""" + """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 DecisionBackendError( - f"Decision backend omitted answers for questions: {missing}.", - backend_kind=backend.backend_kind, - model_id=backend.model_id, + raise DecisionModelError( + f"Decision model omitted answers for questions: {missing}." ) return by_id @@ -567,7 +565,7 @@ class DecisionCascadeRouter: def __init__( self, - backend: DecisionBackend, + decision_model: DecisionModel, *, templates: Sequence[ExpressSurfaceSpec] = (), config: CascadeConfig | None = None, @@ -575,26 +573,24 @@ def __init__( """Initializes the cascade router. Args: - backend: Decision backend answering the routing batch. + decision_model: Async callable answering the routing batch. templates: Registered Express `.a2ui` surface templates. config: Threshold and pruning configuration. Defaults to `CascadeConfig()`. Raises: - TypeError: If `backend` is not a `DecisionBackend`. + TypeError: If `decision_model` is not callable. ValueError: If `templates` contains duplicate template IDs. """ - if not isinstance(backend, DecisionBackend): - raise TypeError( - "DecisionCascadeRouter requires a DecisionBackend instance." - ) + 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 in seen_ids: raise ValueError(f"Duplicate ExpressSurfaceSpec id {tmpl.id!r}.") seen_ids.add(tmpl.id) - self._backend = backend + self._decision_model = decision_model self._templates = template_tuple self._templates_by_id = {tmpl.id: tmpl for tmpl in template_tuple} self._config = config if config is not None else CascadeConfig() @@ -804,10 +800,10 @@ async def route( latency_budget_ms, allow_sandbox_app, ) - answers = await self._backend.answer(batch, timeout_seconds=timeout_seconds) - answer_map = _index_answers( - answers, [q.id for q in batch.questions], self._backend + 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 needs_ui_prob < self._config.needs_ui_threshold: diff --git a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py index 778e0ad41e..45bafeaca2 100644 --- a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py +++ b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -import warnings import pytest @@ -26,10 +25,10 @@ from a2ui.core.schema import ProtocolVersion from a2ui.inference_formats.experimental.decision import ( DecisionAnswer, - DecisionBackendError, + DecisionModelError, DecisionBatch, DecisionDistribution, - DeterministicMockBackend, + MockDecisionModel, ) from a2ui.inference_formats.experimental.decision_cascade import ( CascadeConfig, @@ -85,57 +84,29 @@ def _templates() -> tuple[ExpressSurfaceSpec, ...]: ) -class _RecordingTimeoutBackend(DeterministicMockBackend): +class _FailingModel(MockDecisionModel): - def __init__(self, **kwargs: Any) -> None: - super().__init__(**kwargs) - self.timeouts: list[float | None] = [] + async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: + del batch + raise DecisionModelError("decision model timed out") - async def answer( - self, - batch: DecisionBatch, - *, - timeout_seconds: float | None = None, - ) -> tuple[DecisionAnswer, ...]: - self.timeouts.append(timeout_seconds) - return await super().answer(batch, timeout_seconds=timeout_seconds) +class _OmittingModel(MockDecisionModel): -class _FailingBackend(DeterministicMockBackend): - - async def answer( - self, - batch: DecisionBatch, - *, - timeout_seconds: float | None = None, - ) -> tuple[DecisionAnswer, ...]: - del batch, timeout_seconds - raise DecisionBackendError( - "backend timed out", backend_kind="jev", model_id="jev-1.14.0" - ) - - -class _OmittingBackend(DeterministicMockBackend): - - async def answer( - self, - batch: DecisionBatch, - *, - timeout_seconds: float | None = None, - ) -> tuple[DecisionAnswer, ...]: - answers = await super().answer(batch, timeout_seconds=timeout_seconds) + 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: - backend = _RecordingTimeoutBackend( + model = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.49, "route:tier": "full_express", } ) - router = DecisionCascadeRouter(backend, templates=_templates()) + router = DecisionCascadeRouter(model, templates=_templates()) decision = await router.route( "What is the capital of France?", [_basic_v1()], @@ -148,23 +119,22 @@ async def test_gate_below_threshold_returns_text_only() -> None: assert decision.template is None assert decision.template_id is None assert decision.needs_ui_probability == pytest.approx(0.49) - assert backend.timeouts == [None] - assert len(backend.batches) == 1 - assert backend.batches[0].state is not None - assert backend.batches[0].shared_context == {} + 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() - backend_hit = _RecordingTimeoutBackend( + model_hit = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "full_express", "route:template": ("flight_status", 0.72), } ) - router_hit = DecisionCascadeRouter(backend_hit, templates=templates) + router_hit = DecisionCascadeRouter(model_hit, templates=templates) hit = await router_hit.route( "Check flight UA 100", [_basic_v1()], latency_budget_ms=300.0 ) @@ -173,8 +143,6 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> assert hit.template_id == "flight_status" assert hit.template == templates[1] assert hit.template_confidence == pytest.approx(0.72) - # Tight routing budget does not shorten the decision backend transport timeout. - assert backend_hit.timeouts == [None] explicit = await router_hit.route( "Check flight UA 100", @@ -183,18 +151,17 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> timeout_seconds=2.5, ) assert explicit.tier is CascadeTier.TEMPLATE - assert backend_hit.timeouts == [None, 2.5] - q_ids = [q.id for q in backend_hit.batches[0].questions] + q_ids = [q.id for q in model_hit.batches[0].questions] assert not any(qid.startswith("prune:") for qid in q_ids) - backend_miss = _RecordingTimeoutBackend( + model_miss = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "full_express", "route:template": ("weather_card", 0.69), } ) - router_miss = DecisionCascadeRouter(backend_miss, templates=templates) + router_miss = DecisionCascadeRouter(model_miss, templates=templates) miss = await router_miss.route( "Show complex analytics", [_basic_v1()], latency_budget_ms=499.0 ) @@ -202,7 +169,7 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> assert miss.catalogs == () # At exactly 500.0 ms, normal routing applies rather than tight-budget restriction. - backend_boundary = DeterministicMockBackend( + backend_boundary = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "full_express", @@ -218,7 +185,7 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> @pytest.mark.asyncio async def test_tight_budget_with_no_templates_returns_text_only() -> None: - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "full_express", @@ -238,7 +205,7 @@ async def test_tight_budget_with_no_templates_returns_text_only() -> None: async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_app() -> ( None ): - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": { @@ -263,7 +230,7 @@ async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_a async def test_over_max_components_routes_pruned_express_to_full_express() -> None: comps = {f"Comp{i}": {} for i in range(129)} large_catalog = _custom_catalog(comps, catalog_id="urn:test:large") - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_express", @@ -284,7 +251,7 @@ async def test_over_max_components_routes_pruned_express_to_full_express() -> No async def test_exact_128_components_still_runs_pruned_express() -> None: comps = {f"Comp{i}": {} for i in range(128)} boundary_catalog = _custom_catalog(comps, catalog_id="urn:test:boundary") - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_express", @@ -326,7 +293,7 @@ async def test_pruned_express_upward_and_downward_closure_and_floor() -> None: }, defs={"UnusedDef": {"type": "string"}}, ) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_express", @@ -368,7 +335,7 @@ async def test_multi_catalog_pruning_uses_cid_idx_isolation() -> None: cat1 = _custom_catalog( {"SharedName": {}, "OnlyOne": {}}, catalog_id="urn:test:cat1" ) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_express", @@ -419,7 +386,7 @@ async def test_deterministic_tie_breaking_on_tier_template_and_children() -> Non } ), ) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": tier_dist, @@ -432,7 +399,7 @@ async def test_deterministic_tie_breaking_on_tier_template_and_children() -> Non assert res_tmpl.template_id == "weather_card" # 2. Downward closure child tie -> FirstChild (decl idx 1) beats SecondChild (decl idx 2) - prune_backend = DeterministicMockBackend( + prune_backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_express", @@ -448,12 +415,12 @@ async def test_deterministic_tie_breaking_on_tier_template_and_children() -> Non @pytest.mark.asyncio async def test_backend_errors_and_omitted_answers_propagate() -> None: - router = DecisionCascadeRouter(_FailingBackend()) - with pytest.raises(DecisionBackendError, match="backend timed out"): + router = DecisionCascadeRouter(_FailingModel()) + with pytest.raises(DecisionModelError, match="decision model timed out"): await router.route("Show chart", [_basic_v1()]) - omitting_router = DecisionCascadeRouter(_OmittingBackend()) - with pytest.raises(DecisionBackendError, match="omitted answers"): + omitting_router = DecisionCascadeRouter(_OmittingModel()) + with pytest.raises(DecisionModelError, match="omitted answers"): await omitting_router.route("Show chart", [_basic_v1()]) @@ -463,7 +430,7 @@ async def test_validation_and_experimental_warning( ) -> None: monkeypatch.delenv(SUPPRESS_ENV_VAR, raising=False) with pytest.warns(UserWarning, match=r"\[EXPERIMENTAL\] DecisionCascadeRouter"): - router = DecisionCascadeRouter(DeterministicMockBackend()) + router = DecisionCascadeRouter(MockDecisionModel()) with pytest.raises(ValueError, match="at least one catalog"): await router.route("hi", []) @@ -471,11 +438,11 @@ async def test_validation_and_experimental_warning( 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="DecisionBackend"): - DecisionCascadeRouter("not-a-backend") # type: ignore[arg-type] + with pytest.raises(TypeError, match="DecisionModel"): + DecisionCascadeRouter("not-a-model") # type: ignore[arg-type] with pytest.raises(ValueError, match="Duplicate ExpressSurfaceSpec"): DecisionCascadeRouter( - DeterministicMockBackend(), + MockDecisionModel(), templates=( ExpressSurfaceSpec(id="dup", description="First", dsl="x"), ExpressSurfaceSpec(id="dup", description="Second", dsl="y"), @@ -505,7 +472,7 @@ async def test_nested_downward_closure_and_kept_parent_short_circuit() -> None: "allowedParents": ["AltParent", "KeptParent"], }, }) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_express", @@ -538,7 +505,7 @@ async def test_all_zero_template_distribution_does_not_pick_first_template() -> description="Weather summary", dsl='root = Text("Sunny")', ) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": ("template", 0.90), @@ -560,7 +527,7 @@ async def test_empty_pruned_catalog_falls_back_to_full_express() -> None: }, catalog_id="https://example.com/empty_prune/catalog.json", ) - backend = DeterministicMockBackend( + backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": ("pruned_express", 0.90), From 5eeea4a4d1acba2d043a67d275da782710ac9e7a Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Tue, 1 Dec 2026 00:20:04 +0000 Subject: [PATCH 4/4] fix(decision_cascade): address PR #4321 review feedback - Compute surface distances, upward/downward closure, and reachability jointly across all active catalogs keyed by (cid_idx, comp_name), dropping unreachable orphans and falling back to FULL_CATALOG if no Surface-eligible root survives. - Replace hardcoded BasicCatalog layout_floor with a catalog-agnostic structural floor derived from ComponentNodeSpec metadata when layout_floor is None. - Filter registered templates by active catalog_id, reject reserved 'none' IDs, and gate normal-budget template selection on template_min_confidence. - Add CascadeConfig.max_questions and optional batch_formatter hook, plus keyword-only context, conversation, and input_parts on route(). - Decouple CascadeTier and templates from Express (PRUNED_CATALOG, FULL_CATALOG, SurfaceTemplateSpec protocol) and drop the ExpressSurfaceSpec re-export. - Defer CatalogDecisionGraph construction, omit route:tier under tight budgets, propagate upward-closure reachability via incremental BFS, enforce strict _valid_children_for, guard non-finite/zero distributions, and update CHANGELOG. --- python/a2ui_agent/CHANGELOG.md | 6 +- .../experimental/decision_cascade/__init__.py | 7 +- .../experimental/decision_cascade/router.py | 862 ++++++++++++------ .../decision_cascade/test_cascade_router.py | 554 +++++++++-- 4 files changed, 1090 insertions(+), 339 deletions(-) diff --git a/python/a2ui_agent/CHANGELOG.md b/python/a2ui_agent/CHANGELOG.md index 74550a4cbf..6e93ea5ce8 100644 --- a/python/a2ui_agent/CHANGELOG.md +++ b/python/a2ui_agent/CHANGELOG.md @@ -39,9 +39,11 @@ `invoke_decision_model`, `CatalogDecisionGraph`, `inspect_pointers`, `ExpressSurfaceSpec`, and `lower_for_transport` ([#4320](https://github.com/a2ui-project/a2ui/pull/4320)). -- Add `DecisionCascadeRouter` in +- Add `DecisionCascadeRouter`, `CascadeConfig`, `CascadeTier`, `RouteDecision`, + `SurfaceTemplateSpec`, and `CascadeBatchFormatter` in `a2ui.inference_formats.experimental.decision_cascade` for single-batch UI - gating, template selection, and `ComponentPruningTransformer` catalog pruning. + 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 index 1b55a93a4f..1ce0f9c91d 100644 --- 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 @@ -16,19 +16,20 @@ from __future__ import annotations -from a2ui.inference_formats.experimental.decision import ExpressSurfaceSpec - from .router import ( + CascadeBatchFormatter, CascadeConfig, CascadeTier, DecisionCascadeRouter, RouteDecision, + SurfaceTemplateSpec, ) __all__ = [ + "CascadeBatchFormatter", "CascadeConfig", "CascadeTier", "DecisionCascadeRouter", - "ExpressSurfaceSpec", "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 index 448e094e03..a320962821 100644 --- 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 @@ -21,30 +21,48 @@ 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, - ExpressSurfaceSpec, + InputPart, QuestionKind, + SlotKind, invoke_decision_model, ) from a2ui.utils._experimental import experimental -_DEFAULT_LAYOUT_FLOOR: tuple[str, ...] = ( - "Column", - "Row", - "Card", - "Text", - "Button", -) +_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): @@ -52,8 +70,8 @@ class CascadeTier(str, Enum): TEXT_ONLY = "text_only" TEMPLATE = "template" - PRUNED_EXPRESS = "pruned_express" - FULL_EXPRESS = "full_express" + PRUNED_CATALOG = "pruned_catalog" + FULL_CATALOG = "full_catalog" SANDBOX_APP = "sandbox_app" def __str__(self) -> str: @@ -66,6 +84,28 @@ 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): @@ -81,13 +121,24 @@ class CascadeConfig: 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` under a tight latency budget. + 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. - layout_floor: Layout primitive names always preserved when present in a - catalog during pruning. + 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 @@ -95,7 +146,9 @@ class CascadeConfig: template_min_confidence: float = 0.70 prune_threshold: float = 0.25 max_components: int = 128 - layout_floor: tuple[str, ...] = _DEFAULT_LAYOUT_FLOOR + 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) @@ -107,38 +160,47 @@ def __post_init__(self) -> None: ) if self.max_components < 1: raise ValueError(f"max_components must be >= 1, got {self.max_components}.") - if isinstance(self.layout_floor, (str, bytes)): + 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.layout_floor must be a sequence of component names, not" - " a string." + "CascadeConfig.batch_formatter must be callable when provided." ) - object.__setattr__(self, "layout_floor", tuple(self.layout_floor)) @dataclass(frozen=True) -class RouteDecision: +class RouteDecision(Generic[TemplateT]): """Routing decision returned by `DecisionCascadeRouter.route`. Attributes: tier: Selected `CascadeTier`. - catalogs: Catalogs to pass downstream (pruned for `PRUNED_EXPRESS`, - original for `FULL_EXPRESS`/`TEMPLATE`/`SANDBOX_APP`, empty for + catalogs: Catalogs to pass downstream (pruned for `PRUNED_CATALOG`, + original for `FULL_CATALOG`/`TEMPLATE`/`SANDBOX_APP`, empty for `TEXT_ONLY`). - template_id: Selected `ExpressSurfaceSpec.id` when `tier` is + template_id: Selected template `id` when `tier` is `CascadeTier.TEMPLATE`. - template: Selected `ExpressSurfaceSpec` when `tier` is + 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 backend. + answers: Raw `DecisionAnswer` tuple returned by the decision model. """ tier: CascadeTier catalogs: tuple[CatalogApi, ...] = () template_id: str | None = None - template: ExpressSurfaceSpec | None = None + template: TemplateT | None = None needs_ui_probability: float = 0.0 tier_confidence: float = 0.0 template_confidence: float = 0.0 @@ -154,38 +216,47 @@ def __post_init__(self) -> None: def _rank_candidates( candidates: Sequence[str], probabilities: Mapping[str, float] ) -> list[tuple[str, float]]: - """Ranks `candidates` by descending probability with deterministic tie-break.""" - indexed = [ - (idx, name, float(probabilities.get(name, 0.0))) - for idx, name in enumerate(candidates) - ] - indexed.sort(key=lambda item: (round(-item[2], 6), item[0])) - return [(name, prob) for _, name, prob in indexed] - - -def _best_scored( - candidates: Iterable[str], - scores: Mapping[str, float], - decl_index: Mapping[str, int], -) -> str | None: - """Returns the highest-scoring candidate, breaking ties by declaration index.""" + """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 name: (round(-scores.get(name, 0.0), 6), decl_index[name]), + 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[ExpressSurfaceSpec], + templates: Sequence[SurfaceTemplateSpec], latency_budget_ms: float | None, allow_sandbox_app: bool, ) -> str: - """Formats the explicit `DecisionBatch.state` string for cascade routing.""" + """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 ) @@ -206,23 +277,31 @@ def _build_tier_options( """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 Express surface template directly.", - )) - entries.append(( - CascadeTier.PRUNED_EXPRESS.value, - "Generate an Express surface with a pruned component subset.", - )) - entries.append(( - CascadeTier.FULL_EXPRESS.value, - "Generate an Express surface with the full component catalogs.", - )) + 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.", - )) + 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) @@ -251,15 +330,22 @@ def _build_prune_questions( def _build_cascade_batch( + *, prompt: str, catalogs: Sequence[CatalogApi], - graph: CatalogDecisionGraph, - templates: Sequence[ExpressSurfaceSpec], + 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 single `DecisionBatch` evaluated by `route()`.""" + """Constructs the default single `DecisionBatch` evaluated by `route()`.""" + del config questions: list[DecisionQuestion] = [ DecisionQuestion( id="gate:needs_ui", @@ -273,40 +359,43 @@ def _build_cascade_batch( }, ) ] - 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 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 Express surface template matches this request?" - ), + 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, ) ) - total_components = sum(len(cat.components) for cat in catalogs) - tight_budget = ( - latency_budget_ms is not None and latency_budget_ms < config.tight_budget_ms - ) - if not tight_budget and total_components <= config.max_components: + 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(state=state, questions=tuple(questions)) + 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( @@ -353,100 +442,116 @@ def _edge_allowed( def _build_parent_to_children_edges( - comp_names: Sequence[str], - specs: Mapping[str, ComponentNodeSpec | None], -) -> dict[str, list[str]]: - """Builds allowed parent-to-child adjacency lists across `comp_names`.""" - comp_set = set(comp_names) - children_by_parent: dict[str, list[str]] = {name: [] for name in comp_names} - for child in comp_names: - child_spec = specs.get(child) - if child_spec is None: + 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 - for parent in child_spec.allowed_parents: - if parent in comp_set and _edge_allowed( - specs.get(parent), parent, child_spec, child - ): - children_by_parent[parent].append(child) + 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( - comp_names: Sequence[str], - specs: Mapping[str, ComponentNodeSpec | None], -) -> dict[str, int]: + 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(comp_names, specs) - distances: dict[str, int] = { - name: 0 for name in comp_names if _is_surface_eligible(specs.get(name)) + 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[str] = deque(distances) + queue: deque[_NodeKey] = deque(distances) while queue: - parent = queue.popleft() - next_dist = distances[parent] + 1 - for child in children_by_parent[parent]: - if child not in distances: - distances[child] = next_dist - queue.append(child) + 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[str], - specs: Mapping[str, ComponentNodeSpec | None], -) -> set[str]: + kept: set[_NodeKey], + specs: Mapping[_NodeKey, ComponentNodeSpec | None], +) -> set[_NodeKey]: """Returns the subset of `kept` connected to a `"Surface"`-eligible root.""" - reaching = {name for name in kept if _is_surface_eligible(specs.get(name))} - queue: deque[str] = deque(reaching) + reaching = {key for key in kept if _is_surface_eligible(specs.get(key))} + queue: deque[_NodeKey] = deque(reaching) while queue: - parent = queue.popleft() - parent_spec = specs.get(parent) - for child in kept: - if child in reaching: + 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) - if _edge_allowed(parent_spec, parent, child_spec, child): - reaching.add(child) - queue.append(child) + 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: str, - specs: Mapping[str, ComponentNodeSpec | None], - comp_set: set[str], - dist_to_surface: Mapping[str, int], -) -> list[str]: - """Returns valid parents of `curr` strictly closer to `"Surface"`.""" - curr_spec = specs.get(curr) + 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] - return [ - parent - for parent in curr_spec.allowed_parents - if parent in comp_set - and parent in dist_to_surface - and dist_to_surface[parent] < curr_dist - and _edge_allowed(specs.get(parent), parent, curr_spec, curr) - ] + 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: str, - reaching: set[str], - comp_set: set[str], - specs: Mapping[str, ComponentNodeSpec | None], - scores: Mapping[str, float], - decl_index: Mapping[str, int], - dist_to_surface: Mapping[str, int], -) -> tuple[list[str], bool]: + 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[str] = [] + path: list[_NodeKey] = [] while curr not in reaching and not _is_surface_eligible(specs.get(curr)): - candidates = _valid_upward_parents(curr, specs, comp_set, dist_to_surface) - best_parent = _best_scored(candidates, scores, decl_index) + 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) @@ -455,166 +560,287 @@ def _trace_upward_path( def _close_upward( - kept: set[str], - comp_names: Sequence[str], - specs: Mapping[str, ComponentNodeSpec | None], - scores: Mapping[str, float], - decl_index: Mapping[str, int], - dist_to_surface: Mapping[str, int], + 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 - comp_set = set(comp_names) reaching = _kept_reaching_surface(kept, specs) - for name in comp_names: - if name not in kept or name in reaching or name not in dist_to_surface: + 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( - name, reaching, comp_set, specs, scores, decl_index, dist_to_surface + 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 - reaching.add(node) - reaching.add(name) + 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_name: str, + parent_key: _NodeKey, parent_spec: ComponentNodeSpec, - comp_set: set[str], - specs: Mapping[str, ComponentNodeSpec | None], -) -> list[str]: - """Returns valid children in `parent_spec.allowed_children` existing in catalog.""" - strict = [ - ch - for ch in parent_spec.allowed_children - if ch in comp_set and _edge_allowed(parent_spec, parent_name, specs.get(ch), ch) - ] - if strict: - return strict - return [ch for ch in parent_spec.allowed_children if ch in comp_set] + 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[str], - comp_names: Sequence[str], - specs: Mapping[str, ComponentNodeSpec | None], - scores: Mapping[str, float], - decl_index: Mapping[str, int], + 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 - comp_set = set(comp_names) - for name in comp_names: - if name not in kept: + for key in all_keys: + if key not in kept: continue - spec = specs.get(name) + spec = specs.get(key) if spec is None or not spec.allowed_children: continue - valid_children = _valid_children_for(name, spec, comp_set, specs) + 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(valid_children, scores, decl_index) + 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 _prune_single_catalog( - catalog: CatalogApi, - cid_idx: int, +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, -) -> CatalogApi: - """Applies threshold pruning, layout floor, closure, and `ComponentPruningTransformer`.""" - comp_names = list(catalog.components.keys()) - decl_index = {name: idx for idx, name in enumerate(comp_names)} - scores = {name: answers[f"prune:{cid_idx}:{name}"].yes for name in comp_names} - specs = { - name: graph.get_component_by_key((catalog.catalog_id, name)) - for name in comp_names - } - kept: set[str] = { - name for name in comp_names if scores[name] >= config.prune_threshold - } - kept.update(name for name in config.layout_floor if name in decl_index) +) -> 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] = {} - dist_to_surface = _compute_surface_distances(comp_names, specs) - for _ in range(len(comp_names) + 1): + 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, comp_names, specs, scores, decl_index, dist_to_surface + 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 ) - changed_down = _close_downward(kept, comp_names, specs, scores, decl_index) if not changed_up and not changed_down: break - ordered_kept = [name for name in comp_names if name in kept] - return ComponentPruningTransformer(ordered_kept).transform(catalog) + 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: +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[ExpressSurfaceSpec] = (), + 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 Express `.a2ui` surface templates. + 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. + 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 ExpressSurfaceSpec id {tmpl.id!r}.") + 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 = {tmpl.id: tmpl for tmpl in 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, answer: DecisionAnswer - ) -> tuple[ExpressSurfaceSpec | None, float]: + 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 self._templates) + ("none",) + 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 winner_prob <= 0.0: - return None, winner_prob + 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: + ) -> RouteDecision[TemplateT]: """Restricts tight-budget routing to `TEMPLATE` (>= threshold) or `TEXT_ONLY`.""" - if not self._templates: + if not active_templates: return RouteDecision( tier=CascadeTier.TEXT_ONLY, catalogs=(), @@ -623,7 +849,9 @@ def _resolve_tight_budget( reason="tight_budget_no_templates", answers=answers, ) - tmpl, tmpl_prob = self._select_template(answer_map["route:template"]) + 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, @@ -648,30 +876,40 @@ def _resolve_tight_budget( def _resolve_pruned_tier( self, catalogs: Sequence[CatalogApi], - graph: CatalogDecisionGraph, + graph: CatalogDecisionGraph | None, answer_map: Mapping[str, DecisionAnswer], needs_ui_prob: float, tier_prob: float, answers: tuple[DecisionAnswer, ...], - ) -> RouteDecision: - """Executes `PRUNED_EXPRESS` or falls back to `FULL_EXPRESS` above cap.""" - total_components = sum(len(cat.components) for cat in catalogs) - if total_components > self._config.max_components: + *, + 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_EXPRESS, + tier=CascadeTier.FULL_CATALOG, catalogs=tuple(catalogs), needs_ui_probability=needs_ui_prob, tier_confidence=tier_prob, reason="catalog_exceeds_max_components", answers=answers, ) - pruned_catalogs = tuple( - _prune_single_catalog(cat, cid_idx, graph, answer_map, self._config) - for cid_idx, cat in enumerate(catalogs) - ) - if not any(cat.components for cat in pruned_catalogs): + 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_EXPRESS, + tier=CascadeTier.FULL_CATALOG, catalogs=tuple(catalogs), needs_ui_probability=needs_ui_prob, tier_confidence=tier_prob, @@ -679,33 +917,48 @@ def _resolve_pruned_tier( answers=answers, ) return RouteDecision( - tier=CascadeTier.PRUNED_EXPRESS, + tier=CascadeTier.PRUNED_CATALOG, catalogs=pruned_catalogs, needs_ui_probability=needs_ui_prob, tier_confidence=tier_prob, - reason="selected_pruned_express", + reason="selected_pruned_catalog", answers=answers, ) def _resolve_normal_budget( self, catalogs: Sequence[CatalogApi], - graph: CatalogDecisionGraph, + graph: CatalogDecisionGraph | None, + active_templates: Sequence[TemplateT], batch: DecisionBatch, answer_map: Mapping[str, DecisionAnswer], needs_ui_prob: float, answers: tuple[DecisionAnswer, ...], - ) -> RouteDecision: + *, + 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(answer_map["route:template"]) - if tmpl is not None: + 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), @@ -720,10 +973,26 @@ def _resolve_normal_budget( 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_EXPRESS.value: + if chosen_tier == CascadeTier.PRUNED_CATALOG.value: return self._resolve_pruned_tier( - catalogs, graph, answer_map, needs_ui_prob, tier_prob, answers + 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( @@ -735,11 +1004,11 @@ def _resolve_normal_budget( answers=answers, ) return RouteDecision( - tier=CascadeTier.FULL_EXPRESS, + tier=CascadeTier.FULL_CATALOG, catalogs=tuple(catalogs), needs_ui_probability=needs_ui_prob, tier_confidence=tier_prob, - reason="selected_full_express", + reason="selected_full_catalog", answers=answers, ) @@ -747,11 +1016,14 @@ 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: + ) -> RouteDecision[TemplateT]: """Evaluates UI gating, tier routing, and component pruning in one batch. Args: @@ -759,12 +1031,17 @@ async def route( 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 the decision - backend's transport timeout. + `TEMPLATE` or `TEXT_ONLY` without shortening `timeout_seconds`. allow_sandbox_app: Whether `CascadeTier.SANDBOX_APP` may be selected. - timeout_seconds: Optional explicit transport deadline in seconds - forwarded to `DecisionBackend.answer`. Defaults to `None` (uses - the backend's configured timeout). + 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 @@ -773,7 +1050,7 @@ async def route( Raises: ValueError: If `catalogs` is empty, `latency_budget_ms` is non-positive, or `timeout_seconds` is non-positive. - DecisionBackendError: If the decision backend fails or omits answers. + DecisionModelError: If the decision model fails or omits answers. """ if not catalogs: raise ValueError( @@ -790,15 +1067,55 @@ async def route( f"timeout_seconds must be positive, got {timeout_seconds}." ) - graph = CatalogDecisionGraph(catalogs) - batch = _build_cascade_batch( - prompt, - catalogs, - graph, - self._templates, - self._config, - latency_budget_ms, - allow_sandbox_app, + 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 @@ -806,24 +1123,33 @@ async def route( answer_map = _index_answers(answers, [q.id for q in batch.questions]) needs_ui_prob = answer_map["gate:needs_ui"].yes - if needs_ui_prob < self._config.needs_ui_threshold: + 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=needs_ui_prob, - tier_confidence=1.0 - needs_ui_prob, + needs_ui_probability=safe_prob, + tier_confidence=1.0 - safe_prob, reason="needs_ui_below_threshold", answers=answers, ) - if ( - latency_budget_ms is not None - and latency_budget_ms < self._config.tight_budget_ms - ): + if tight_budget: return self._resolve_tight_budget( - catalogs, answer_map, needs_ui_prob, answers + catalogs, active_templates, answer_map, needs_ui_prob, answers ) return self._resolve_normal_budget( - catalogs, graph, batch, answer_map, needs_ui_prob, answers + 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 index 45bafeaca2..725e801b30 100644 --- a/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py +++ b/python/a2ui_agent/tests/decision_cascade/test_cascade_router.py @@ -16,7 +16,10 @@ from __future__ import annotations +from collections.abc import Mapping, Sequence +from dataclasses import dataclass from typing import Any +import warnings import pytest @@ -24,19 +27,28 @@ from a2ui.core.basic_catalog import BasicCatalog from a2ui.core.schema import ProtocolVersion from a2ui.inference_formats.experimental.decision import ( + CatalogDecisionGraph, + ConversationTurn, DecisionAnswer, - DecisionModelError, DecisionBatch, DecisionDistribution, + DecisionModelError, + DecisionQuestion, + ExpressSurfaceSpec, + InputPart, MockDecisionModel, + QuestionKind, + TextInputPart, + build_inference_catalogs, ) from a2ui.inference_formats.experimental.decision_cascade import ( CascadeConfig, CascadeTier, DecisionCascadeRouter, - ExpressSurfaceSpec, RouteDecision, + SurfaceTemplateSpec, ) +from a2ui.transformers.macros import macro from a2ui.utils._experimental import SUPPRESS_ENV_VAR @@ -84,15 +96,23 @@ def _templates() -> tuple[ExpressSurfaceSpec, ...]: ) -class _FailingModel(MockDecisionModel): +@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:] @@ -103,7 +123,7 @@ async def test_gate_below_threshold_returns_text_only() -> None: model = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.49, - "route:tier": "full_express", + "route:tier": "full_catalog", } ) router = DecisionCascadeRouter(model, templates=_templates()) @@ -130,7 +150,6 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> model_hit = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, - "route:tier": "full_express", "route:template": ("flight_status", 0.72), } ) @@ -152,12 +171,12 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> ) 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:tier": "full_express", "route:template": ("weather_card", 0.69), } ) @@ -172,7 +191,7 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> backend_boundary = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, - "route:tier": "full_express", + "route:tier": "full_catalog", "route:template": ("weather_card", 0.69), } ) @@ -180,7 +199,7 @@ async def test_tight_latency_budget_selects_confident_template_or_text_only() -> boundary = await router_boundary.route( "Show complex analytics", [_basic_v1()], latency_budget_ms=500.0 ) - assert boundary.tier is CascadeTier.FULL_EXPRESS + assert boundary.tier is CascadeTier.FULL_CATALOG @pytest.mark.asyncio @@ -188,17 +207,13 @@ async def test_tight_budget_with_no_templates_returns_text_only() -> None: backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, - "route:tier": "full_express", } ) 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 "route:template" not in q_ids - tier_q = next(q for q in backend.batches[0].questions if q.id == "route:tier") - assert "template" not in tier_q.options - assert "sandbox_app" not in tier_q.options + assert q_ids == ["gate:needs_ui"] @pytest.mark.asyncio @@ -211,8 +226,8 @@ async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_a "route:tier": { "template": 0.50, "sandbox_app": 0.35, - "pruned_express": 0.10, - "full_express": 0.05, + "pruned_catalog": 0.10, + "full_catalog": 0.05, }, "route:template": ("none", 0.85), } @@ -227,19 +242,19 @@ async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_a @pytest.mark.asyncio -async def test_over_max_components_routes_pruned_express_to_full_express() -> None: - comps = {f"Comp{i}": {} for i in range(129)} +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_express", + "route:tier": "pruned_catalog", } ) router = DecisionCascadeRouter(backend) decision = await router.route("Build a dashboard", [large_catalog]) - assert decision.tier is CascadeTier.FULL_EXPRESS + 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 @@ -248,13 +263,13 @@ async def test_over_max_components_routes_pruned_express_to_full_express() -> No @pytest.mark.asyncio -async def test_exact_128_components_still_runs_pruned_express() -> None: - comps = {f"Comp{i}": {} for i in range(128)} +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_express", + "route:tier": "pruned_catalog", "prune:0:Comp0": 0.90, **{f"prune:0:Comp{i}": 0.05 for i in range(1, 128)}, } @@ -262,17 +277,17 @@ async def test_exact_128_components_still_runs_pruned_express() -> None: router = DecisionCascadeRouter(backend) decision = await router.route("Show item 0", [boundary_catalog]) - assert decision.tier is CascadeTier.PRUNED_EXPRESS + assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == {"Comp0"} @pytest.mark.asyncio -async def test_pruned_express_upward_and_downward_closure_and_floor() -> None: +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. - # Layout floor ("Column", "Text") is preserved even below 0.25, while "Unused" - # and "UnusedDef" are pruned out by ComponentPruningTransformer. + # 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"]}, @@ -296,7 +311,7 @@ async def test_pruned_express_upward_and_downward_closure_and_floor() -> None: backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, - "route:tier": "pruned_express", + "route:tier": "pruned_catalog", "prune:0:Page": 0.05, "prune:0:DeadEndParent": 0.24, "prune:0:Section": 0.10, @@ -309,10 +324,13 @@ async def test_pruned_express_upward_and_downward_closure_and_floor() -> None: "prune:0:Unused": 0.05, } ) - router = DecisionCascadeRouter(backend) + router = DecisionCascadeRouter( + backend, + config=CascadeConfig(layout_floor=("Column", "Text")), + ) decision = await router.route("Show leaf and tabs", [catalog]) - assert decision.tier is CascadeTier.PRUNED_EXPRESS + assert decision.tier is CascadeTier.PRUNED_CATALOG pruned = decision.catalogs[0] kept = set(pruned.components) assert kept == { @@ -338,17 +356,19 @@ async def test_multi_catalog_pruning_uses_cid_idx_isolation() -> None: backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, - "route:tier": "pruned_express", + "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) + router = DecisionCascadeRouter( + backend, config=CascadeConfig(layout_floor=("Text",)) + ) decision = await router.route("Use SharedName from cat0", [cat0, cat1]) - assert decision.tier is CascadeTier.PRUNED_EXPRESS + assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == {"SharedName", "Text"} assert set(decision.catalogs[1].components) == {"OnlyOne"} @@ -357,21 +377,23 @@ async def test_multi_catalog_pruning_uses_cid_idx_isolation() -> None: 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"]}, - }) + catalog = _custom_catalog( + { + "Holder": {"allowedChildren": ["FirstChild", "SecondChild"]}, + "FirstChild": {"allowedParents": ["Holder"]}, + "SecondChild": {"allowedParents": ["Holder"]}, + } + ) templates = _templates() - # 1. route:tier tie -> "template" (idx 0) beats "pruned_express" (idx 1) + # 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_express": 0.10, - "pruned_express": 0.4500002, + "full_catalog": 0.10, + "pruned_catalog": 0.4500002, "template": 0.4500001, } ), @@ -393,7 +415,11 @@ async def test_deterministic_tie_breaking_on_tier_template_and_children() -> Non "route:template": tmpl_dist, } ) - router = DecisionCascadeRouter(backend, templates=templates) + 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" @@ -402,7 +428,7 @@ async def test_deterministic_tie_breaking_on_tier_template_and_children() -> Non prune_backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, - "route:tier": "pruned_express", + "route:tier": "pruned_catalog", "prune:0:Holder": 0.80, "prune:0:FirstChild": 0.1000001, "prune:0:SecondChild": 0.1000002, @@ -432,6 +458,12 @@ async def test_validation_and_experimental_warning( 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"): @@ -439,8 +471,8 @@ async def test_validation_and_experimental_warning( 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[arg-type] - with pytest.raises(ValueError, match="Duplicate ExpressSurfaceSpec"): + DecisionCascadeRouter("not-a-model") # type: ignore[call-overload] + with pytest.raises(ValueError, match="Duplicate template id"): DecisionCascadeRouter( MockDecisionModel(), templates=( @@ -448,34 +480,45 @@ async def test_validation_and_experimental_warning( 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"], - }, - }) + 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_express", + "route:tier": "pruned_catalog", "prune:0:Outer": 0.80, "prune:0:Inner": 0.10, "prune:0:DeepLeaf": 0.05, @@ -487,7 +530,7 @@ async def test_nested_downward_closure_and_kept_parent_short_circuit() -> None: router = DecisionCascadeRouter(backend) decision = await router.route("Nested closure", [catalog]) - assert decision.tier is CascadeTier.PRUNED_EXPRESS + assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == { "Outer", "Inner", @@ -519,7 +562,7 @@ async def test_all_zero_template_distribution_does_not_pick_first_template() -> @pytest.mark.asyncio -async def test_empty_pruned_catalog_falls_back_to_full_express() -> None: +async def test_empty_pruned_catalog_falls_back_to_full_catalog() -> None: catalog = _custom_catalog( { "Alpha": {"properties": {"id": {"type": "string"}}}, @@ -530,7 +573,7 @@ async def test_empty_pruned_catalog_falls_back_to_full_express() -> None: backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, - "route:tier": ("pruned_express", 0.90), + "route:tier": ("pruned_catalog", 0.90), "prune:0:Alpha": 0.05, "prune:0:Beta": 0.05, } @@ -540,7 +583,7 @@ async def test_empty_pruned_catalog_falls_back_to_full_express() -> None: config=CascadeConfig(layout_floor=(), prune_threshold=0.50), ) decision = await router.route("Render custom", [catalog]) - assert decision.tier is CascadeTier.FULL_EXPRESS + assert decision.tier is CascadeTier.FULL_CATALOG assert decision.reason == "pruned_catalog_empty" assert set(decision.catalogs[0].components) == {"Alpha", "Beta"} @@ -548,3 +591,382 @@ async def test_empty_pruned_catalog_falls_back_to_full_express() -> None: 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"