# Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for `DecisionCascadeRouter` and cascade routing types.""" from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any import warnings import pytest from a2ui.core import Catalog, CatalogApi from a2ui.core.basic_catalog import BasicCatalog from a2ui.core.schema import ProtocolVersion from a2ui.experimental.decision import ( CatalogDecisionGraph, ConversationTurn, DecisionAnswer, DecisionBatch, DecisionDistribution, DecisionModelError, DecisionQuestion, ExpressSurfaceSpec, InputPart, MockDecisionModel, QuestionKind, TextInputPart, ) from a2ui.experimental.decision.cascade import ( CascadeConfig, CascadeTier, DecisionCascadeRouter, RouteDecision, SurfaceTemplateSpec, ) from a2ui.transformers.macros import MacroExpander, macro SUPPRESS_ENV_VAR = "A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS" def _basic_v1() -> CatalogApi: return BasicCatalog("v1.0") def _custom_catalog( components: dict[str, dict[str, Any]], *, catalog_id: str = "urn:test:cascade", defs: dict[str, Any] | None = None, ) -> CatalogApi: payload: dict[str, Any] = { "catalogId": catalog_id, "components": { name: { "type": "object", "properties": { "component": {"const": name}, **spec.get("properties", {}), }, **{k: v for k, v in spec.items() if k != "properties"}, } for name, spec in components.items() }, } if defs is not None: payload["$defs"] = defs return Catalog.from_json(payload, protocol_version=ProtocolVersion.V1_0) def _templates() -> tuple[ExpressSurfaceSpec, ...]: return ( ExpressSurfaceSpec( id="weather_card", description="Show weather forecast card", dsl='surface "s1" { root = Text("Sunny") }', ), ExpressSurfaceSpec( id="flight_status", description="Show flight status summary", dsl='surface "s1" { root = Text("On time") }', ), ) @dataclass(frozen=True) class _CustomTemplate: """Format-agnostic template satisfying `SurfaceTemplateSpec` without Express DSL.""" id: str description: str catalog_id: str | None = None payload: dict[str, Any] | None = None class _FailingModel(MockDecisionModel): async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: del batch raise DecisionModelError("decision model timed out") class _OmittingModel(MockDecisionModel): async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: answers = await super().__call__(batch) return answers[1:] @pytest.mark.asyncio async def test_gate_below_threshold_returns_text_only() -> None: model = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.49, "route:tier": "full_catalog", } ) router = DecisionCascadeRouter(model, templates=_templates()) decision = await router.route( "What is the capital of France?", [_basic_v1()], latency_budget_ms=1200.0, ) assert isinstance(decision, RouteDecision) assert decision.tier is CascadeTier.TEXT_ONLY assert decision.catalogs == () assert decision.template is None assert decision.template_id is None assert decision.needs_ui_probability == pytest.approx(0.49) assert len(model.batches) == 1 assert model.batches[0].state is not None assert model.batches[0].shared_context == {} @pytest.mark.asyncio async def test_tight_latency_budget_selects_confident_template_or_text_only() -> None: templates = _templates() model_hit = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:template": ("flight_status", 0.72), } ) router_hit = DecisionCascadeRouter(model_hit, templates=templates) hit = await router_hit.route( "Check flight UA 100", [_basic_v1()], latency_budget_ms=300.0 ) assert hit.tier is CascadeTier.TEMPLATE assert hit.template_id == "flight_status" assert hit.template == templates[1] assert hit.template_confidence == pytest.approx(0.72) explicit = await router_hit.route( "Check flight UA 100", [_basic_v1()], latency_budget_ms=300.0, timeout_seconds=2.5, ) assert explicit.tier is CascadeTier.TEMPLATE q_ids = [q.id for q in model_hit.batches[0].questions] assert "route:tier" not in q_ids assert not any(qid.startswith("prune:") for qid in q_ids) model_miss = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:template": ("weather_card", 0.69), } ) router_miss = DecisionCascadeRouter(model_miss, templates=templates) miss = await router_miss.route( "Show complex analytics", [_basic_v1()], latency_budget_ms=499.0 ) assert miss.tier is CascadeTier.TEXT_ONLY assert miss.catalogs == () # At exactly 500.0 ms, normal routing applies rather than tight-budget restriction. backend_boundary = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "full_catalog", "route:template": ("weather_card", 0.69), } ) router_boundary = DecisionCascadeRouter(backend_boundary, templates=templates) boundary = await router_boundary.route( "Show complex analytics", [_basic_v1()], latency_budget_ms=500.0 ) assert boundary.tier is CascadeTier.FULL_CATALOG @pytest.mark.asyncio async def test_tight_budget_with_no_templates_returns_text_only() -> None: backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, } ) router = DecisionCascadeRouter(backend) decision = await router.route("Show chart", [_basic_v1()], latency_budget_ms=200.0) assert decision.tier is CascadeTier.TEXT_ONLY q_ids = [q.id for q in backend.batches[0].questions] assert q_ids == ["gate:needs_ui"] @pytest.mark.asyncio async def test_normal_budget_template_none_falls_back_to_next_tier_and_sandbox_app() -> ( None ): backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": { "template": 0.50, "sandbox_app": 0.35, "pruned_catalog": 0.10, "full_catalog": 0.05, }, "route:template": ("none", 0.85), } ) router = DecisionCascadeRouter(backend, templates=_templates()) decision = await router.route( "Open interactive whiteboard", [_basic_v1()], allow_sandbox_app=True ) assert decision.tier is CascadeTier.SANDBOX_APP tier_q = next(q for q in backend.batches[0].questions if q.id == "route:tier") assert "sandbox_app" in tier_q.options @pytest.mark.asyncio async def test_over_max_components_routes_pruned_catalog_to_full_catalog() -> None: comps: dict[str, dict[str, Any]] = {f"Comp{i}": {} for i in range(129)} large_catalog = _custom_catalog(comps, catalog_id="urn:test:large") backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_catalog", } ) router = DecisionCascadeRouter(backend) decision = await router.route("Build a dashboard", [large_catalog]) assert decision.tier is CascadeTier.FULL_CATALOG assert decision.reason == "catalog_exceeds_max_components" assert len(decision.catalogs) == 1 assert len(decision.catalogs[0].components) == 129 q_ids = [q.id for q in backend.batches[0].questions] assert not any(qid.startswith("prune:") for qid in q_ids) @pytest.mark.asyncio async def test_exact_128_components_still_runs_pruned_catalog() -> None: comps: dict[str, dict[str, Any]] = {f"Comp{i}": {} for i in range(128)} boundary_catalog = _custom_catalog(comps, catalog_id="urn:test:boundary") backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_catalog", "prune:0:Comp0": 0.90, **{f"prune:0:Comp{i}": 0.05 for i in range(1, 128)}, } ) router = DecisionCascadeRouter(backend) decision = await router.route("Show item 0", [boundary_catalog]) assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == {"Comp0"} @pytest.mark.asyncio async def test_pruned_catalog_upward_and_downward_closure_and_explicit_floor() -> None: # Multi-hop upward closure: Leaf -> Section -> Page (Surface-eligible). # DeadEndParent has allowedParents: ["MissingRoot"] so it cannot reach Surface. # Container TabGroup has allowedChildren: ["TabItemA", "TabItemB"] both < 0.25. # Explicit layout_floor=("Column", "Text") is preserved even below 0.25, while # "Unused" and "UnusedDef" are pruned out by ComponentPruningTransformer. catalog = _custom_catalog( { "Page": {"allowedParents": ["Surface"]}, "DeadEndParent": {"allowedParents": ["MissingRoot"]}, "Section": {"allowedParents": ["Page", "DeadEndParent"]}, "Leaf": {"allowedParents": ["Section"]}, "TabGroup": { "allowedParents": ["Surface"], "allowedChildren": ["TabItemA", "TabItemB"], }, "TabItemA": {"allowedParents": ["TabGroup"]}, "TabItemB": {"allowedParents": ["TabGroup"]}, "Column": {}, "Text": {}, "Unused": { "properties": {"extra": {"$ref": "#/$defs/UnusedDef"}}, }, }, defs={"UnusedDef": {"type": "string"}}, ) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": "pruned_catalog", "prune:0:Page": 0.05, "prune:0:DeadEndParent": 0.24, "prune:0:Section": 0.10, "prune:0:Leaf": 0.80, "prune:0:TabGroup": 0.70, "prune:0:TabItemA": 0.10, "prune:0:TabItemB": 0.20, "prune:0:Column": 0.05, "prune:0:Text": 0.05, "prune:0:Unused": 0.05, } ) router = DecisionCascadeRouter( backend, config=CascadeConfig(layout_floor=("Column", "Text")), ) decision = await router.route("Show leaf and tabs", [catalog]) assert decision.tier is CascadeTier.PRUNED_CATALOG pruned = decision.catalogs[0] kept = set(pruned.components) assert kept == { "Page", "Section", "Leaf", "TabGroup", "TabItemB", "Column", "Text", } assert "UnusedDef" not in pruned.validation_schema.get("$defs", {}) # Original catalog stays untouched. assert "Unused" in catalog.components @pytest.mark.asyncio async def test_multi_catalog_pruning_uses_cid_idx_isolation() -> None: cat0 = _custom_catalog({"SharedName": {}, "Text": {}}, catalog_id="urn:test:cat0") cat1 = _custom_catalog( {"SharedName": {}, "OnlyOne": {}}, catalog_id="urn:test:cat1" ) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_catalog", "prune:0:SharedName": 0.80, "prune:0:Text": 0.05, "prune:1:SharedName": 0.05, "prune:1:OnlyOne": 0.75, } ) router = DecisionCascadeRouter( backend, config=CascadeConfig(layout_floor=("Text",)) ) decision = await router.route("Use SharedName from cat0", [cat0, cat1]) assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == {"SharedName", "Text"} assert set(decision.catalogs[1].components) == {"OnlyOne"} @pytest.mark.asyncio async def test_deterministic_tie_breaking_on_tier_template_and_children() -> None: # Ties within 1e-6 must resolve strictly by declaration index, even when # dict insertion order is reversed and probabilities differ at 1e-7. catalog = _custom_catalog({ "Holder": {"allowedChildren": ["FirstChild", "SecondChild"]}, "FirstChild": {"allowedParents": ["Holder"]}, "SecondChild": {"allowedParents": ["Holder"]}, }) templates = _templates() # 1. route:tier tie -> "template" (idx 0) beats "pruned_catalog" (idx 1) # route:template tie -> "weather_card" (idx 0) beats "flight_status" (idx 1) tier_dist = DecisionAnswer( question_id="route:tier", distribution=DecisionDistribution( probabilities={ "full_catalog": 0.10, "pruned_catalog": 0.4500002, "template": 0.4500001, } ), ) tmpl_dist = DecisionAnswer( question_id="route:template", distribution=DecisionDistribution( probabilities={ "none": 0.10, "flight_status": 0.4500002, "weather_card": 0.4500001, } ), ) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": tier_dist, "route:template": tmpl_dist, } ) router = DecisionCascadeRouter( backend, templates=templates, config=CascadeConfig(template_min_confidence=0.40), ) res_tmpl = await router.route("Tie break test", [catalog]) assert res_tmpl.tier is CascadeTier.TEMPLATE assert res_tmpl.template_id == "weather_card" # 2. Downward closure child tie -> FirstChild (decl idx 1) beats SecondChild (decl idx 2) prune_backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_catalog", "prune:0:Holder": 0.80, "prune:0:FirstChild": 0.1000001, "prune:0:SecondChild": 0.1000002, } ) prune_router = DecisionCascadeRouter(prune_backend) res_prune = await prune_router.route("Child tie test", [catalog]) assert set(res_prune.catalogs[0].components) == {"Holder", "FirstChild"} @pytest.mark.asyncio async def test_backend_errors_and_omitted_answers_propagate() -> None: router = DecisionCascadeRouter(_FailingModel()) with pytest.raises(DecisionModelError, match="decision model timed out"): await router.route("Show chart", [_basic_v1()]) omitting_router = DecisionCascadeRouter(_OmittingModel()) with pytest.raises(DecisionModelError, match="omitted answers"): await omitting_router.route("Show chart", [_basic_v1()]) @pytest.mark.asyncio async def test_validation_and_experimental_warning( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.delenv(SUPPRESS_ENV_VAR, raising=False) with pytest.warns(UserWarning, match=r"\[EXPERIMENTAL\] DecisionCascadeRouter"): router = DecisionCascadeRouter(MockDecisionModel()) # route() must not leak internal [EXPERIMENTAL] CatalogDecisionGraph warnings. with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") await router.route("hi", [_basic_v1()]) assert not any("CatalogDecisionGraph" in str(w.message) for w in caught) with pytest.raises(ValueError, match="at least one catalog"): await router.route("hi", []) with pytest.raises(ValueError, match="latency_budget_ms must be positive"): await router.route("hi", [_basic_v1()], latency_budget_ms=0.0) with pytest.raises(ValueError, match="timeout_seconds must be positive"): await router.route("hi", [_basic_v1()], timeout_seconds=0.0) with pytest.raises(TypeError, match="DecisionModel"): DecisionCascadeRouter("not-a-model") # type: ignore[call-overload] with pytest.raises(ValueError, match="Duplicate template id"): DecisionCascadeRouter( MockDecisionModel(), templates=( ExpressSurfaceSpec(id="dup", description="First", dsl="x"), ExpressSurfaceSpec(id="dup", description="Second", dsl="y"), ), ) with pytest.raises(ValueError, match="reserved"): DecisionCascadeRouter( MockDecisionModel(), templates=(_CustomTemplate(id="none", description="Invalid"),), ) with pytest.raises(ValueError, match="needs_ui_threshold"): CascadeConfig(needs_ui_threshold=1.5) with pytest.raises(ValueError, match="max_components"): CascadeConfig(max_components=0) with pytest.raises(ValueError, match="max_questions"): CascadeConfig(max_questions=0) with pytest.raises(TypeError, match="batch_formatter"): CascadeConfig(batch_formatter="not-callable") # type: ignore[arg-type] @pytest.mark.asyncio async def test_nested_downward_closure_and_kept_parent_short_circuit() -> None: catalog = _custom_catalog({ "Outer": { "allowedParents": ["Surface"], "allowedChildren": ["Inner"], }, "Inner": { "allowedParents": ["Outer"], "allowedChildren": ["DeepLeaf"], }, "DeepLeaf": {"allowedParents": ["Inner"]}, "AltParent": {"allowedParents": ["Surface"]}, "KeptParent": {"allowedParents": ["Surface"]}, "ChildWithTwoParents": { "allowedParents": ["AltParent", "KeptParent"], }, }) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": "pruned_catalog", "prune:0:Outer": 0.80, "prune:0:Inner": 0.10, "prune:0:DeepLeaf": 0.05, "prune:0:AltParent": 0.20, "prune:0:KeptParent": 0.60, "prune:0:ChildWithTwoParents": 0.70, } ) router = DecisionCascadeRouter(backend) decision = await router.route("Nested closure", [catalog]) assert decision.tier is CascadeTier.PRUNED_CATALOG assert set(decision.catalogs[0].components) == { "Outer", "Inner", "DeepLeaf", "KeptParent", "ChildWithTwoParents", } @pytest.mark.asyncio async def test_all_zero_template_distribution_does_not_pick_first_template() -> None: catalog = BasicCatalog(ProtocolVersion.V1_0) template = ExpressSurfaceSpec( id="weather", description="Weather summary", dsl='root = Text("Sunny")', ) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": ("template", 0.90), "route:template": {"weather": 0.0, "none": 0.0}, } ) router = DecisionCascadeRouter(backend, templates=(template,)) decision = await router.route("Show weather", [catalog]) assert decision.tier is not CascadeTier.TEMPLATE assert decision.template is None @pytest.mark.asyncio async def test_empty_pruned_catalog_falls_back_to_full_catalog() -> None: catalog = _custom_catalog( { "Alpha": {"properties": {"id": {"type": "string"}}}, "Beta": {"properties": {"id": {"type": "string"}}}, }, catalog_id="https://example.com/empty_prune/catalog.json", ) backend = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.90, "route:tier": ("pruned_catalog", 0.90), "prune:0:Alpha": 0.05, "prune:0:Beta": 0.05, } ) router = DecisionCascadeRouter( backend, config=CascadeConfig(layout_floor=(), prune_threshold=0.50), ) decision = await router.route("Render custom", [catalog]) assert decision.tier is CascadeTier.FULL_CATALOG assert decision.reason == "pruned_catalog_empty" assert set(decision.catalogs[0].components) == {"Alpha", "Beta"} def test_cascade_config_rejects_bare_str_layout_floor() -> None: with pytest.raises(TypeError, match="layout_floor"): CascadeConfig(layout_floor="Column") # type: ignore[arg-type] @pytest.mark.asyncio async def test_cross_catalog_macro_closure_preserves_parent_and_drops_orphans() -> None: @macro(allowed_parents=("List",)) # type: ignore[untyped-decorator] def ItemRow(label: str) -> dict[str, Any]: return {"component": "Text", "text": label} basic = _basic_v1() catalogs = MacroExpander( [ItemRow], catalog_id="urn:test:macros", base_catalogs=[basic], ).transform_catalogs([basic]) 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 async def _nan_gate_model(_batch: DecisionBatch) -> list[DecisionAnswer]: return [ DecisionAnswer( question_id="gate:needs_ui", distribution=DecisionDistribution( probabilities={"yes": float("nan"), "no": 0.0} ), ) ] nan_router = DecisionCascadeRouter(_nan_gate_model) with pytest.raises(DecisionModelError) as exc_info: await nan_router.route("NaN gate", [_basic_v1()]) assert exc_info.value.code == "DECISION_CONTRACT_ERROR" @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()], latency_budget_ms=10.0 ) assert custom_decision.tier is CascadeTier.TEXT_ONLY assert custom_backend.batches[0].state == "CUSTOM_STATE: Hola" with pytest.raises(ValueError, match="missing required question IDs"): await custom_router.route("Hola", [_basic_v1()])