# 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 the framework-neutral `a2ui.experimental.decision` kernel.""" from __future__ import annotations import ast import asyncio from collections.abc import Mapping, Sequence from pathlib import Path import subprocess import sys import time from typing import Any import warnings import pytest from a2ui.core import A2uiCatalogError, A2uiValidationError, Catalog, CatalogApi from a2ui.core.basic_catalog import BasicCatalog from a2ui.core.schema import AgentToRendererMessage, ProtocolVersion from a2ui.experimental.decision import ( Calibration, CatalogDecisionGraph, ConversationTurn, DecisionAnswer, DecisionBatch, DecisionDistribution, DecisionModelError, DecisionQuestion, MediaInputPart, MockDecisionModel, PointerSummary, QuestionKind, SemanticType, SlotKind, answer_from_distribution, inspect_pointers, invoke_decision_model, redact_payload, ) from a2ui.experimental.decision.payload import ( DefaultSecretFilter, classify_scalar, humanize_key, is_secret_pointer, ) from a2ui.inference_formats.express import ExpressFormat from a2ui.parser import to_message_models from a2ui.transformers.macros import MacroExpander, macro from a2ui.utils import ( RendererState, validate_payload, ) def test_custom_callable_decision_model_and_invoke_helper() -> None: q = DecisionQuestion(id="gate", kind=QuestionKind.BOOLEAN, prompt="Needs UI?") batch = DecisionBatch( shared_context={"intent": "show weather"}, state="user asked for local forecast", instructions="Prefer UI for structured forecasts.", conversation=( ConversationTurn(role="user", content="Hi"), ConversationTurn(role="assistant", content="How can I help?"), ConversationTurn(role="user", content="What's the weather?"), ), questions=(q,), ) seen_batches: list[DecisionBatch] = [] async def custom_model(b: DecisionBatch) -> list[DecisionAnswer]: seen_batches.append(b) return [ answer_from_distribution( b.questions[0], DecisionDistribution(probabilities={"yes": 0.9, "no": 0.1}), ) ] answers = asyncio.run( invoke_decision_model(custom_model, batch, timeout_seconds=2.0) ) assert len(answers) == 1 assert answers[0].yes == pytest.approx(0.9) assert seen_batches[0].state == "user asked for local forecast" assert seen_batches[0].shared_context == {"intent": "show weather"} assert seen_batches[0].instructions == "Prefer UI for structured forecasts." assert len(seen_batches[0].conversation) == 3 def test_invoke_decision_model_enforces_timeout_and_missing_answers() -> None: q = DecisionQuestion(id="gate", kind=QuestionKind.BOOLEAN, prompt="Needs UI?") batch = DecisionBatch(questions=(q,)) async def slow_model(_: DecisionBatch) -> list[DecisionAnswer]: await asyncio.sleep(0.5) return [] async def empty_model(_: DecisionBatch) -> list[DecisionAnswer]: return [] async def _run_checks() -> None: with pytest.raises(DecisionModelError, match="timed out"): await invoke_decision_model(slow_model, batch, timeout_seconds=0.02) with pytest.raises(DecisionModelError, match="omitted answers"): await invoke_decision_model(empty_model, batch) with pytest.raises(ValueError, match="timeout_seconds"): await invoke_decision_model(empty_model, batch, timeout_seconds=0.0) asyncio.run(_run_checks()) def test_mock_decision_model_callable_scripting_and_context() -> None: q_bool = DecisionQuestion(id="gate", kind=QuestionKind.BOOLEAN, prompt="Show UI?") q_choice = DecisionQuestion( id="tpl", kind=QuestionKind.CHOICE, prompt="Pick template", options=("weather", "flight"), ) q_score = DecisionQuestion( id="fit", kind=QuestionKind.SCORE, prompt="Fit score", options=("low", "mid", "high"), ) model = MockDecisionModel( scripted_answers={"gate": 0.85, "tpl": ("weather", 0.92), "fit": 1.5} ) batch = DecisionBatch( shared_context={"topic": "weather"}, conversation=(ConversationTurn(role="user", content="Show forecast"),), questions=(q_bool, q_choice, q_score), ) answers = asyncio.run(model(batch)) assert len(model.batches) == 1 assert answers[0].yes == pytest.approx(0.85) assert answers[1].top() == ("weather", pytest.approx(0.92)) assert answers[2].expected == pytest.approx(1.5) def test_conversation_turn_validation() -> None: turn = ConversationTurn(role="user", content="hello") assert turn.role == "user" with pytest.raises(A2uiValidationError, match="role"): ConversationTurn(role=" ", content="hello") def test_calibration_scales_distribution_and_loads_profile(tmp_path: Path) -> None: probs = {"a": 0.8, "b": 0.2} sharper = Calibration(temperature=0.5).apply(probs) flatter = Calibration(temperature=2.0).apply(probs) assert sharper["a"] > probs["a"] assert flatter["a"] < probs["a"] profile_path = tmp_path / "profiles.json" profile_path.write_text('{"custom/v1": {"temperature": 0.25}}', encoding="utf-8") loaded = Calibration.load(profile_path, profile_key="custom/v1") assert loaded.temperature == pytest.approx(0.25) assert Calibration.load(profile_path, profile_key="missing").temperature == 1.0 def test_classify_scalar_and_long_camel_case_api_key_redaction() -> None: sem = classify_scalar("https://example.com/photo.png", key="avatarUrl") assert sem is SemanticType.IMAGE_URL long_secret = "sk_live_" + ("a" * 80) pointers = inspect_pointers({ "title": "Dashboard", "apiKey": long_secret, "api-key": long_secret, "userApiKey": long_secret, }) paths = {p.path for p in pointers} assert "/title" in paths assert "/apiKey" not in paths assert "/api-key" not in paths assert "/userApiKey" not in paths def test_renderer_state_commit_runs_topology_and_rolls_back() -> None: basic = BasicCatalog("v1.0") state = RendererState([basic]) invalid_messages = to_message_models([ { "version": "1.0", "createSurface": { "surfaceId": "broken", "catalogId": basic.catalog_id, }, }, { "version": "1.0", "updateComponents": { "surfaceId": "broken", "components": [{ "id": "root", "component": "Column", "children": ["missing_id"], }], }, }, ]) with pytest.raises(A2uiValidationError): state.commit(invalid_messages) assert state.get_surface("broken") is None def test_bare_str_rejected_for_macro_constraints_and_express_surface_spec() -> None: with pytest.raises(TypeError, match="allowed_parents"): @macro(allowed_parents="Column") # type: ignore[arg-type] def _BadParents(title: str) -> list[dict[str, Any]]: return [{"id": "root", "component": "Text", "text": title}] with pytest.raises(TypeError, match="allowed_children"): @macro(allowed_children="Text") # type: ignore[arg-type] def _BadChildren(title: str) -> list[dict[str, Any]]: return [{"id": "root", "component": "Text", "text": title}] def test_kernel_entry_points_emit_experimental_warning_and_suppress( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.delenv("A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS", raising=False) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") MockDecisionModel() CatalogDecisionGraph([BasicCatalog("v1.0")]) inspect_pointers({"title": "Hello"}) exp_warnings = [ w for w in caught if issubclass(w.category, UserWarning) and "[EXPERIMENTAL]" in str(w.message) ] assert len(exp_warnings) >= 3 monkeypatch.setenv("A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS", "1") with warnings.catch_warnings(record=True) as suppressed: warnings.simplefilter("always") MockDecisionModel() inspect_pointers({"title": "Hello"}) assert not [w for w in suppressed if "[EXPERIMENTAL]" in str(w.message)] def test_semantic_types_avoids_sql_backtracking_and_prose_false_positives() -> None: start = time.perf_counter() ptrs = inspect_pointers({ "bio": "select" + (" " * 2000) + "x", "message": "Let me know when you arrive", "title": "From Paris with Love", "postalCode": "94103", }) elapsed = time.perf_counter() - start assert elapsed < 0.5 by_path = {p.path: p for p in ptrs} assert by_path["/bio"].semantic_type is not SemanticType.CODE assert by_path["/message"].semantic_type is not SemanticType.CODE assert by_path["/title"].semantic_type is not SemanticType.CODE assert by_path["/postalCode"].semantic_type is not SemanticType.CODE def test_payload_inspector_redaction_precision_nesting_arrays_and_group_labels() -> ( None ): ptrs = inspect_pointers({ "businessName": "Acme Corp", "tokenCount": 512, "passwordHint": "Pet name", "secretary": "Dana", "accessToken": "tok_secret_1", "apiKeys": {"stripe": "sk_live_1"}, "secrets": {"github": "ghp_x"}, "authorization": "Bearer abc", "privateKey": "-----BEGIN PRIVATE KEY-----", "users": [{"name": "Alice", "password": "pw", "sessionId": "sid_1"}], "accounts": [{"apiKey": "sk_live_SECRET", "items": [{"x": 1}]}], }) paths = {p.path for p in ptrs} assert "/businessName" in paths assert "/tokenCount" in paths assert "/passwordHint" in paths assert "/secretary" in paths assert "/accessToken" not in paths assert "/apiKeys/stripe" not in paths assert "/secrets/github" not in paths assert "/authorization" not in paths assert "/privateKey" not in paths by_path = {p.path: p for p in ptrs} assert "password" not in by_path["/users"].element_keys assert "sessionId" not in by_path["/users"].element_keys assert "name" in by_path["/users"].element_keys assert by_path["/accounts/0/items"].label != "sk_live_SECRET" def test_catalog_decision_graph_returns_none_for_ambiguous_bare_name() -> None: shared_comp = BasicCatalog("1.0").components["Text"] comp_name = shared_comp.name cat_a = Catalog("https://a.example/v1", "1.0", components=[shared_comp]) cat_b = Catalog("https://b.example/v1", "1.0", components=[shared_comp]) graph = CatalogDecisionGraph([cat_a, cat_b]) assert graph.surface_catalog_id is None assert graph.protocol_version is ProtocolVersion.V1_0 assert graph.get_component(comp_name) is None assert graph.get_component(("https://a.example/v1", comp_name)) is not None assert graph.get_component(("https://b.example/v1", comp_name)) is not None assert graph.get_component_by_key(("https://a.example/v1", comp_name)) is not None assert len(graph.catalogs) == 2 def test_catalog_decision_graph_structured_slots_and_no_inspector_leak() -> None: basic = BasicCatalog("v1.0") graph = CatalogDecisionGraph([basic]) assert graph.surface_catalog_id == basic.catalog_id assert graph.protocol_version is ProtocolVersion.V1_0 assert not hasattr(graph, "inspectors") assert not hasattr(graph, "helpers") cp = graph.get_component("ChoicePicker") assert cp is not None opt_slot = next((s for s in cp.slots if s.name == "options"), None) assert opt_slot is not None assert opt_slot.kind is SlotKind.STRUCTURED assert opt_slot.required is True assert not hasattr(opt_slot, "schema") assert opt_slot.value_type == "array" assert f"{SlotKind.CHILD}" == "child" icon = graph.get_component("Icon") assert icon is not None icon_name = next(s for s in icon.slots if s.name == "name") assert icon_name.kind is SlotKind.DATA_VALUE assert "accountCircle" in icon_name.enum_values slider = graph.get_component("Slider") assert slider is not None steps_slot = next((s for s in slider.slots if s.name == "steps"), None) assert steps_slot is not None assert steps_slot.is_integer is True with pytest.raises(A2uiCatalogError): CatalogDecisionGraph([BasicCatalog("v0.8")]) def test_media_input_part_and_decision_question_validation() -> None: with pytest.raises(A2uiValidationError, match="base64 length"): MediaInputPart( modality="image", mime_type="image/png", data_b64="A" * 100, max_inline_bytes=8, ) with pytest.raises(A2uiValidationError, match="duplicates"): DecisionQuestion( id="q:dup", kind=QuestionKind.CHOICE, prompt="Pick", options=("a", "a"), ) with pytest.raises(A2uiValidationError, match="reserved"): DecisionQuestion( id="q:none", kind=QuestionKind.CHOICE, prompt="Pick", options=("a", "none"), allow_none=True, ) def test_payload_inspector_pluggable_classifier_secret_filter_and_single_warning( monkeypatch: pytest.MonkeyPatch, ) -> None: with pytest.raises(TypeError, match="mutable_paths"): inspect_pointers({"title": "Hi", "api_key": "sk-1"}, mutable_paths="/title") # type: ignore[arg-type] with pytest.raises(TypeError, match="exclude"): inspect_pointers({"title": "Hi"}, exclude="/title") # type: ignore[arg-type] class _CustomClassifier: def classify_scalar( self, value: Any, key: str = "", *, siblings: Mapping[str, Any] | None = None, ) -> str: del value, siblings if key == "ticker": return "ticker_symbol" return SemanticType.STRING def classify_array_field( self, values: Sequence[Any], key: str = "", *, siblings_per_item: Sequence[Mapping[str, Any]] | None = None, ) -> str: del values, siblings_per_item return "ticker_symbol" if key == "ticker" else SemanticType.STRING custom_filter = DefaultSecretFilter(extra_keys=("badge",), allowlist=("/token",)) ptrs = inspect_pointers( {"ticker": "GOOG", "badgeId": "secret-badge", "token": "public-tok"}, classifier=_CustomClassifier(), is_secret=custom_filter, detect_groups=False, ) by_path = {p.path: p for p in ptrs} assert by_path["/ticker"].semantic_type == "ticker_symbol" assert "/badgeId" not in by_path assert "/token" in by_path assert ( PointerSummary( path="/x", value_type="string", semantic_type="icd10_code" ).semantic_type == "icd10_code" ) monkeypatch.delenv("A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS", raising=False) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") inspect_pointers({"title": "Hello"}) exp_warnings = [w for w in caught if "[EXPERIMENTAL]" in str(w.message)] assert len(exp_warnings) == 1 def test_semantic_types_price_min_and_bounded_number_range() -> None: sem_min = classify_scalar(10, "priceMin") assert sem_min is SemanticType.CURRENCY sem_out = classify_scalar(80, "humidity", siblings={"min": 15, "max": 25}) assert sem_out is not SemanticType.BOUNDED sem_in = classify_scalar(20, "humidity", siblings={"min": 15, "max": 25}) assert sem_in is SemanticType.BOUNDED def _lower_and_commit( expander: MacroExpander, messages: Sequence[AgentToRendererMessage], *, catalogs: Sequence[CatalogApi], renderer_state: RendererState | None = None, ) -> list[AgentToRendererMessage]: """Lowers macros in `messages`, then commits to `renderer_state` or validates.""" surface_catalogs = ( renderer_state.surface_catalogs if renderer_state is not None else None ) lowered = expander.transform_to_transport( messages, surface_catalogs=surface_catalogs ) if renderer_state is not None: renderer_state.commit(lowered) else: validate_payload(catalogs, lowered) return list(lowered) def test_macro_dedup_and_transport_multiturn_and_qualified_shadowing() -> None: from a2ui.builder.v1_0 import Card, Column, DynamicString, Text @macro( allowed_parents=("Column", "Column", "Card"), allowed_children=("Text", "Text"), ) def ProductTile(title: DynamicString, sku: str) -> Card: """Displays a product tile.""" return Card(child=Column(children=[Text(text=title), Text(text=sku)])) with pytest.raises(ValueError, match="valid component identifiers"): @macro(allowed_parents=("",)) def _EmptyParent(title: str) -> list[dict[str, Any]]: return [{"id": "root", "component": "Text", "text": title}] basic = BasicCatalog("v1.0") expander = MacroExpander( [ProductTile], catalog_id="urn:test:macros", base_catalogs=[basic], on_error="raise", ) inf = expander.transform_catalogs([basic]) graph = CatalogDecisionGraph(inf) tile_node = graph.get_component_by_key(("urn:test:macros", "ProductTile")) assert tile_node is not None assert tile_node.allowed_parents == ("Column", "Card") assert tile_node.allowed_children == ("Text",) parser = ExpressFormat(inf).create_parser() state = RendererState([basic]) turn1 = _lower_and_commit( expander, parser.compile('root = Column(children=[ProductTile(title="A", sku="1")])'), catalogs=[basic], renderer_state=state, ) assert turn1 # The update carries no `createSurface`, so its catalog comes from `state`. turn2 = _lower_and_commit( expander, parser.compile( 'surface("main", update=true)\n' 'root = Column(children=[ProductTile(title="B", sku="2")])' ), catalogs=[basic], renderer_state=state, ) assert turn2 # Unrelated transport catalog sharing bare name ProductTile does not drop macro_catalog_id. cst_catalog = Catalog.from_json( { "catalogId": "urn:test:cst", "components": { "ProductTile": { "type": "object", "properties": { "title": {"type": "string"}, "sku": {"type": "string"}, }, } }, }, protocol_version=ProtocolVersion.V1_0, ) qualified_msgs = to_message_models([ { "version": "1.0", "createSurface": {"surfaceId": "s1", "catalogId": basic.catalog_id}, }, { "version": "1.0", "updateComponents": { "surfaceId": "s1", "components": [{ "id": "root", "component": "ProductTile", "@catalogId": "urn:test:macros", "title": {"@path": "/name"}, "sku": "1", }], }, }, ]) lowered = _lower_and_commit( MacroExpander( [ProductTile], catalog_id="urn:test:macros", base_catalogs=[basic, cst_catalog], on_error="raise", ), qualified_msgs, catalogs=[basic, cst_catalog], ) dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in lowered] comp_types = [c["component"] for c in dumped[1]["updateComponents"]["components"]] assert "Card" in comp_types assert "ProductTile" not in comp_types def _imported_modules(tree: ast.AST) -> list[str]: """Returns all top-level imported module names from an AST.""" mods: list[str] = [] for node in ast.walk(tree): if isinstance(node, ast.Import): mods.extend(alias.name for alias in node.names) elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: mods.append(node.module) return mods def test_kernel_framework_neutrality() -> None: src_dir = Path(__file__).resolve().parents[1] / "src" / "a2ui" / "experimental" assert sorted(src_dir.rglob("*.py")), f"No source files found under {src_dir}" forbidden = ("a2a", "google.adk", "google.genai", "httpx", "a2ui.a2a", "a2ui.adk") for py_file in sorted(src_dir.rglob("*.py")): tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file)) for mod in _imported_modules(tree): assert not any( mod == f or mod.startswith(f + ".") for f in forbidden ), f"{py_file} imports forbidden framework/http module {mod}" proc = subprocess.run( [ sys.executable, "-c", ( "import sys, a2ui.experimental.decision; " "bad = [m for m in ('a2a', 'google.adk', 'google.genai', 'httpx') " "if m in sys.modules]; " "assert not bad, bad" ), ], capture_output=True, text=True, check=False, ) assert proc.returncode == 0, f"Framework neutrality check failed: {proc.stderr}" def test_inspect_pointers_exclude_filters_array_sample_pointers() -> None: payload = { "items": [ {"name": "First", "photo": ""}, {"name": "Second", "photo": "https://example.com/pic.png"}, ] } ptrs = {p.path: p for p in inspect_pointers(payload, exclude={"/items/photo"})} items = ptrs["/items"] assert "photo" not in items.element_keys assert "name" in items.element_keys assert all(not sp.endswith("/photo") for sp in items.sample_pointers) def test_inspect_pointers_mutable_paths_secret_redaction() -> None: payload = { "apiKey": "sk-top", "account": { "name": "Acme", "apiKey": "sk-nested", "users": [{"name": "Alice", "apiKey": "sk-array"}], }, } slash_ptrs = {p.path: p for p in inspect_pointers(payload, mutable_paths={"/"})} assert "/apiKey" not in slash_ptrs assert "/account/apiKey" not in slash_ptrs parent_ptrs = { p.path: p for p in inspect_pointers(payload, mutable_paths={"/account"}) } assert "/account/name" in parent_ptrs assert "/account/apiKey" not in parent_ptrs assert "apiKey" not in parent_ptrs["/account/users"].element_keys assert "name" in parent_ptrs["/account/users"].element_keys explicit_ptrs = { p.path: p for p in inspect_pointers(payload, mutable_paths={"/account/apiKey"}) } assert "/account/apiKey" in explicit_ptrs with pytest.raises(TypeError, match="mutable_paths"): inspect_pointers(payload, mutable_paths="") def test_inspect_pointers_array_secret_filter_honors_allowlist_and_extra_keys() -> None: payload = { "users": [{"name": "Alice", "token": "public-id", "badge": "secret-badge"}] } secret_filter = DefaultSecretFilter(allowlist=("token",), extra_keys=("badge",)) ptrs = {p.path: p for p in inspect_pointers(payload, is_secret=secret_filter)} users = ptrs["/users"] assert "token" in users.element_keys assert "badge" not in users.element_keys assert all(not sp.endswith("/badge") for sp in users.sample_pointers) def test_inspect_pointers_skips_empty_string_keys() -> None: payload = { "": "root-empty", "ok": 1, "sections": [ {"": [{"x": 1}], "title": "A"}, ], "labeled": [ {"": "EmptyLabel", "items": [{"x": 1}]}, ], } ptrs = inspect_pointers(payload) paths = [p.path for p in ptrs] assert "/" not in paths assert "/ok" in paths assert all(not p.endswith("/") for p in paths) def test_normalize_probabilities_ignores_non_candidate_mass() -> None: model = MockDecisionModel(scripted={"q": {"a": 0.3, "b": 0.3, "x": 0.41}}) batch = DecisionBatch( questions=( DecisionQuestion( id="q", kind=QuestionKind.CHOICE, prompt="Pick one", options=("a", "b"), allow_none=False, ), ) ) answers = asyncio.run(invoke_decision_model(model, batch)) probs = answers[0].distribution.probabilities assert probs["a"] == pytest.approx(0.3) assert probs["b"] == pytest.approx(0.3) def _resolves(data: Any, pointer: str) -> bool: current = data for segment in pointer[1:].split("/"): key = segment.replace("~1", "/").replace("~0", "~") if isinstance(current, dict) and key in current: current = current[key] elif isinstance(current, list) and key.isdecimal() and int(key) < len(current): current = current[int(key)] else: return False return True def test_redact_payload_keeps_what_inspect_pointers_offers_and_drops_the_rest() -> None: payload = { "name": "Ada", "api_key": "k", "auth": {"token": "t", "scheme": "bearer"}, "secret_question": {"hint": "pet"}, "users": ( {"name": "Ada", "password": "pw", "email": "a@example.com"}, {"name": "Bob", "password": "pw", "email": "b@example.com"}, ), "rows": [{"id": 1}, {"id": 2}, {"id": 3}], "photos": [{"url": "https://example.com/1.png", "internal": "x"}], "__proto__": {"polluted": True}, "constructor": "c", } options: list[dict[str, Any]] = [ {}, {"exclude": ("/users/email", "/rows/1", "/photos/0/internal")}, {"mutable_paths": ("/",)}, {"mutable_paths": ("/api_key", "/auth")}, {"is_secret": lambda ptr: ptr.key == "email"}, ] for kwargs in options: redacted = redact_payload(payload, **kwargs) for ptr in inspect_pointers(payload, **kwargs): assert _resolves(redacted, ptr.path), (kwargs, ptr.path) for sample in ptr.sample_pointers: assert _resolves(redacted, sample), (kwargs, sample) assert "__proto__" not in redacted and "constructor" not in redacted assert redact_payload(payload) == { "name": "Ada", "auth": {"scheme": "bearer"}, "users": [ {"name": "Ada", "email": "a@example.com"}, {"name": "Bob", "email": "b@example.com"}, ], "rows": [{"id": 1}, {"id": 2}, {"id": 3}], "photos": [{"url": "https://example.com/1.png", "internal": "x"}], } excluded = redact_payload( payload, exclude=("/users/email", "/rows/1", "/photos/0/internal") ) assert excluded["users"] == [{"name": "Ada"}, {"name": "Bob"}] assert excluded["rows"] == [{"id": 1}, None, {"id": 3}] assert excluded["photos"] == [{"url": "https://example.com/1.png"}] explicit = redact_payload(payload, mutable_paths=("/api_key", "/auth")) assert explicit["api_key"] == "k" assert explicit["auth"] == {"scheme": "bearer"} assert "api_key" not in redact_payload(payload, mutable_paths=("/",)) custom = redact_payload(payload, is_secret=lambda ptr: ptr.key == "email") assert custom["api_key"] == "k" assert custom["users"][0] == {"name": "Ada", "password": "pw"} with pytest.raises(TypeError, match="exclude"): redact_payload(payload, exclude="/name") # type: ignore[arg-type] def test_inspect_pointers_skips_keys_a_renderer_cannot_address() -> None: pointers = inspect_pointers({ "constructor": {"name": "x"}, "prototype": "p", "rows": [{"__proto__": 1, "id": 2}], }) assert [p.path for p in pointers] == ["/rows"] assert pointers[0].element_keys == ("id",) def test_round2_runtime_validation_alignment_and_calibration(tmp_path: Path) -> None: q_bool = DecisionQuestion(id="b", kind=QuestionKind.BOOLEAN, prompt="Ok?") q_score = DecisionQuestion( id="s", kind=QuestionKind.SCORE, prompt="Rate", options=("low", "mid", "high") ) # Lone yes in [0, 1] is preserved, not inflated to 1.0. lone = answer_from_distribution(q_bool, DecisionDistribution({"yes": 0.3})) assert lone.yes == pytest.approx(0.3) assert lone.distribution.probabilities["no"] == pytest.approx(0.7) for bad_bool in ({}, {"yes": -1.0, "no": 2.0}, {"yes": float("nan"), "no": 0.5}): with pytest.raises(A2uiValidationError): answer_from_distribution(q_bool, DecisionDistribution(bad_bool)) for bad_score in ({}, {"low": float("nan"), "mid": 0.5, "high": 0.5}): with pytest.raises(A2uiValidationError): answer_from_distribution(q_score, DecisionDistribution(bad_score)) # invoke_decision_model aligns order, rejects duplicates/unknowns, wraps errors. q1 = DecisionQuestion(id="q1", kind=QuestionKind.BOOLEAN, prompt="One?") q2 = DecisionQuestion(id="q2", kind=QuestionKind.BOOLEAN, prompt="Two?") a1 = DecisionAnswer("q1", DecisionDistribution({"yes": 0.8, "no": 0.2})) a2 = DecisionAnswer("q2", DecisionDistribution({"yes": 0.2, "no": 0.8})) batch = DecisionBatch(questions=(q1, q2)) async def reversed_model(_b: DecisionBatch) -> list[DecisionAnswer]: return [a2, a1] aligned = asyncio.run(invoke_decision_model(reversed_model, batch)) assert [a.question_id for a in aligned] == ["q1", "q2"] async def dup_model(_b: DecisionBatch) -> list[DecisionAnswer]: return [a1, a1, a2] with pytest.raises(DecisionModelError, match="duplicate"): asyncio.run(invoke_decision_model(dup_model, batch)) async def unknown_model(_b: DecisionBatch) -> list[DecisionAnswer]: return [a1, a2, DecisionAnswer("extra", DecisionDistribution({"yes": 1.0}))] with pytest.raises(DecisionModelError, match="unexpected"): asyncio.run(invoke_decision_model(unknown_model, batch)) async def boom_model(_b: DecisionBatch) -> list[DecisionAnswer]: raise RuntimeError("boom") with pytest.raises(DecisionModelError, match="boom"): asyncio.run(invoke_decision_model(boom_model, batch)) async def internal_timeout_model(_b: DecisionBatch) -> list[DecisionAnswer]: raise asyncio.TimeoutError() with pytest.raises(DecisionModelError, match=r"^Decision model timed out\.$"): asyncio.run(invoke_decision_model(internal_timeout_model, batch)) # Calibration rejects bool and null JSON temperature; MockDecisionModel validates tuples. with pytest.raises(ValueError, match="positive"): Calibration(temperature=True) # type: ignore[arg-type] bad_cal = tmp_path / "cal.json" bad_cal.write_text('{"p": {"temperature": null}}', encoding="utf-8") with pytest.raises(ValueError, match="positive"): Calibration.load(bad_cal, profile_key="p") q_choice = DecisionQuestion( id="c", kind=QuestionKind.CHOICE, prompt="Pick", options=("a", "b") ) for bad_spec in (("a", 1.5), ("a", -0.5), ("a",)): m = MockDecisionModel(scripted_answers={"c": bad_spec}) # type: ignore[dict-item] with pytest.raises(ValueError): asyncio.run(m(DecisionBatch(questions=(q_choice,)))) # DecisionBatch guards bare strings and supports hash(). assert isinstance(hash(DecisionBatch()), int) with pytest.raises(TypeError, match="conversation"): DecisionBatch(conversation="hello") # type: ignore[arg-type] def test_round2_secret_redaction_and_semantic_types() -> None: # Separator-free secret keys redacted; benign tokens/cookieConsent/hasPassword kept. ptrs = { p.path: p for p in inspect_pointers({ "apikey": "sk1", "APIKEY": "sk2", "x_apikey": "sk3", "maxTokens": 4096, "total_tokens": 120, "nextPageToken": "cursor1", "designTokens": {"primary": "#fff"}, "cookieConsent": True, "hasPassword": True, }) } for leaked in ("/apikey", "/APIKEY", "/x_apikey"): assert leaked not in ptrs for kept in ( "/maxTokens", "/total_tokens", "/nextPageToken", "/designTokens", "/designTokens/primary", "/cookieConsent", "/hasPassword", ): assert kept in ptrs # DefaultSecretFilter multi-word extra_keys, bare string rejection, prefix allowlist, group labels. with pytest.raises(TypeError, match="extra_keys"): DefaultSecretFilter(extra_keys="badge") multi_filter = DefaultSecretFilter(extra_keys=("badge_id",)) multi_ptrs = { p.path: p for p in inspect_pointers( {"userId": "u1", "orderId": "o1", "badgeId": "b1", "name": "Alice"}, is_secret=multi_filter, ) } assert "/userId" in multi_ptrs and "/orderId" in multi_ptrs assert "/badgeId" not in multi_ptrs grp_ptrs = inspect_pointers( {"groups": [{"badge": "SECRET-999", "items": [{"x": 1}]}]}, is_secret=DefaultSecretFilter(extra_keys=("badge",)), ) for p in grp_ptrs: assert p.label != "SECRET-999" # Semantic-type array filter + index>0 sample sync + explicit mutable array column. sem_ptrs = { p.path: p for p in inspect_pointers( {"people": [{"contact": "bob@example.com", "name": "Bob"}]}, is_secret=lambda p: p.semantic_type == SemanticType.EMAIL, ) } assert "contact" not in sem_ptrs["/people"].element_keys photo_ptrs = { p.path: p for p in inspect_pointers( {"items": [{"photo": ""}, {"photo": "https://example.com/p.png"}]}, is_secret=lambda p: p.path == "/items/0/photo", ) } assert "photo" not in photo_ptrs["/items"].element_keys assert photo_ptrs["/items"].sample_pointers == () mut_arr = { p.path: p for p in inspect_pointers( {"users": [{"name": "Alice", "apiKey": "sk-1"}]}, mutable_paths={"/users/0/apiKey"}, ) } assert "apiKey" in mut_arr["/users"].element_keys # SQL / class prose false positives and durationMin. for prose in ( "Select an option from the dropdown", "Delete items from your cart", "Update your profile from settings", "Insert coin into slot", "class notes for Monday", ): sem = classify_scalar(prose) assert sem is not SemanticType.CODE, f"Misclassified as CODE: {prose!r}" assert classify_scalar("SELECT id FROM users") is SemanticType.CODE assert classify_scalar(30, "durationMin") is SemanticType.DURATION assert classify_scalar(15, "cookTimeMin") is SemanticType.DURATION assert classify_scalar(100, "priceMin") is SemanticType.CURRENCY def _email_secret(ptr: PointerSummary) -> bool: return ptr.semantic_type == SemanticType.EMAIL class _HandleIsEmailClassifier: """Classifies every `handle` scalar as an email, deferring the rest.""" def classify_scalar( self, value: Any, key: str = "", *, siblings: Mapping[str, Any] | None = None, ) -> str: if key == "handle": return SemanticType.EMAIL return classify_scalar(value, key, siblings=siblings) def classify_array_field( self, values: Sequence[Any], key: str = "", *, siblings_per_item: Sequence[Mapping[str, Any]] | None = None, ) -> str: return SemanticType.STRING def test_redact_payload_applies_semantic_secret_filters_like_inspect_pointers() -> None: data = {"contact": "bob@example.com", "name": "Bob", "": "blank"} offered = {p.path for p in inspect_pointers(data, is_secret=_email_secret)} redacted = redact_payload(data, is_secret=_email_secret) assert "/contact" not in offered assert redacted == {"name": "Bob"} custom = _HandleIsEmailClassifier() handle_data = {"handle": "bobby", "name": "Bob"} assert "/handle" not in { p.path for p in inspect_pointers( handle_data, is_secret=_email_secret, classifier=custom ) } assert redact_payload(handle_data, is_secret=_email_secret, classifier=custom) == { "name": "Bob" } assert redact_payload(handle_data, is_secret=_email_secret) == handle_data def test_mutable_array_path_does_not_expose_secret_columns() -> None: data = { "users": [ {"name": "Alice", "apiKey": "sk-1"}, {"name": "Bob", "apiKey": "sk-2"}, ] } whole_array = {p.path: p for p in inspect_pointers(data, mutable_paths={"/users"})} assert whole_array["/users"].element_keys == ("name",) assert redact_payload(data, mutable_paths={"/users"}) == { "users": [{"name": "Alice"}, {"name": "Bob"}] } for column in ("/users/apiKey", "/users/0/apiKey"): offered = {p.path: p for p in inspect_pointers(data, mutable_paths={column})} assert "apiKey" in offered["/users"].element_keys assert redact_payload(data, mutable_paths={column}) == data def test_allowlisted_ancestor_key_does_not_clear_nested_secrets() -> None: data = {"credentials": {"username": "u", "password": "p"}, "apiKey": "pub"} secret_filter = DefaultSecretFilter(allowlist=("credentials", "apiKey")) offered = {p.path for p in inspect_pointers(data, is_secret=secret_filter)} assert "/credentials/username" in offered assert "/credentials/password" not in offered assert "/apiKey" in offered assert redact_payload(data, is_secret=secret_filter) == { "credentials": {"username": "u"}, "apiKey": "pub", } def _group_sections(pointers: Sequence[PointerSummary]) -> list[PointerSummary]: return [p for p in pointers if p.path.count("/") > 1] def test_group_labels_skip_excluded_forbidden_and_semantic_secret_keys() -> None: data = { "groups": [ {"title": "Visible", "description": "Shown", "items": [{"x": 1}]}, ] } (baseline,) = _group_sections(inspect_pointers(data)) assert baseline.label == "Visible" for title_path in ("/groups/title", "/groups/0/title"): (section,) = _group_sections(inspect_pointers(data, exclude={title_path})) assert section.label != "Visible" (only_title,) = _group_sections( inspect_pointers( {"groups": [{"title": "Visible", "items": [{"x": 1}]}]}, exclude={title_path}, ) ) assert only_title.label != "Visible" (section,) = _group_sections( inspect_pointers( {"groups": [{"__proto__": "Bad", "items": [{"x": 1}]}]}, ) ) assert section.label != "Bad" (section,) = _group_sections( inspect_pointers( { "groups": [{ "owner": "bob@example.com", "description": "alice@example.com", "items": [{"x": 1}], }] }, is_secret=_email_secret, ) ) assert section.label != "bob@example.com" def test_group_detection_ignores_forbidden_inner_keys() -> None: pointers = inspect_pointers( {"rows": [{"name": "A", "__proto__": [{"x": 1}]}]}, ) assert not _group_sections(pointers) assert all("__proto__" not in p.path for p in pointers) @pytest.mark.parametrize( "key", [ "passwordConfirm", "password_confirmation", "passwordHash", "password_digest", "password_new", "passwordValue", "passwordCurrent", "totp", "totpCode", "pinCode", "pin_code", "userPin", "cardPin", "pinNumber", "verificationCode", "recoveryCode", "backupCodes", "authCode", "securityCode", "cvv", "cardCvc", ], ) def test_secret_key_names_cover_password_variants_and_card_codes(key: str) -> None: probe = PointerSummary(path=f"/{key}", value_type="string") assert is_secret_pointer(probe) def test_truncated_json_text_is_classified_quickly() -> None: truncated = "{" + '"k": 1, ' * 20_000 start = time.perf_counter() sem = classify_scalar(truncated) elapsed = time.perf_counter() - start assert sem is not SemanticType.CODE assert elapsed < 1.0 assert classify_scalar('{"k": 1, "j": "two"}') is SemanticType.CODE def test_prose_ending_in_a_file_name_is_not_a_media_url() -> None: assert classify_scalar("see the attached report.pdf") is SemanticType.STRING assert classify_scalar("report.pdf") is SemanticType.DOCUMENT_URL assert classify_scalar("/files/my report.pdf") is SemanticType.DOCUMENT_URL assert ( classify_scalar("https://example.com/report.pdf") is SemanticType.DOCUMENT_URL ) def test_decision_distribution_rejects_non_finite_and_negative_values() -> None: for bad in ( {"a": float("inf"), "b": 0.5, "c": 0.5}, {"a": float("inf"), "b": 1.0}, {"a": float("nan"), "b": 1.0}, {"a": -0.1, "b": 1.1}, ): with pytest.raises(A2uiValidationError): DecisionDistribution(probabilities=bad) def test_invoke_decision_model_wraps_generator_iteration_errors_and_media_ext_precedence() -> ( None ): q = DecisionQuestion(id="q1", kind=QuestionKind.BOOLEAN, prompt="Ok?") batch = DecisionBatch(questions=(q,)) async def failing_iter(_b: DecisionBatch) -> Any: def _gen() -> Any: raise RuntimeError("mid-stream boom") yield # pragma: no cover return _gen() with pytest.raises(DecisionModelError, match="mid-stream boom"): asyncio.run(invoke_decision_model(failing_iter, batch)) # Explicit file extension takes precedence over an earlier key hint. assert ( classify_scalar("https://example.com/report.pdf", "avatar") is SemanticType.DOCUMENT_URL ) # Dotted and colon-separated secret keys split cleanly into tokens. ptrs = { p.path: p for p in inspect_pointers({"auth.token": "s1", "x:api_key": "s2", "ok": "v"}) } assert "/auth.token" not in ptrs assert "/x:api_key" not in ptrs assert "/ok" in ptrs def test_default_secret_filter_path_allowlist_still_redacts_nested_secrets() -> None: payload = { "credentials": { "username": "alice", "password": "secret-password", "nested": {"apiKey": "sk_live_123"}, } } redacted = redact_payload( payload, is_secret=DefaultSecretFilter(allowlist=("/credentials",)), ) assert redacted == {"credentials": {"username": "alice", "nested": {}}} def test_redact_payload_bounds_deep_nesting_and_cycles() -> None: deep: dict[str, Any] = {} cur = deep for _ in range(100): nxt: dict[str, Any] = {} cur["a"] = nxt cur = nxt redacted_deep = redact_payload(deep) assert isinstance(redacted_deep, dict) cyclic: dict[str, Any] = {"name": "ok"} cyclic["self"] = cyclic redacted_cyclic = redact_payload(cyclic) assert redacted_cyclic == {"name": "ok", "self": {}} def test_decision_model_error_sets_structured_codes() -> None: q = DecisionQuestion(id="q1", kind=QuestionKind.BOOLEAN, prompt="Ok?") batch = DecisionBatch(questions=(q,)) async def slow_model(_b: DecisionBatch) -> list[DecisionAnswer]: await asyncio.sleep(5) return [] with pytest.raises(DecisionModelError) as timeout_exc: asyncio.run(invoke_decision_model(slow_model, batch, timeout_seconds=0.01)) assert timeout_exc.value.code == "DECISION_TIMEOUT" async def bad_contract(_b: DecisionBatch) -> Any: return "not-a-list" with pytest.raises(DecisionModelError) as contract_exc: asyncio.run(invoke_decision_model(bad_contract, batch)) assert contract_exc.value.code == "DECISION_CONTRACT_ERROR" def test_inspect_pointers_handles_malformed_ipv6_url() -> None: pointers = inspect_pointers({"link": "http://[invalid/photo.png"}) assert len(pointers) == 1 assert pointers[0].path == "/link" def test_inspect_pointers_handles_cycles_without_exponential_blowup() -> None: cyclic: dict[str, Any] = {} cyclic["k0"] = cyclic cyclic["k1"] = cyclic pointers = inspect_pointers(cyclic) assert [p.path for p in pointers] == ["/k0", "/k1"] @pytest.mark.parametrize( "key", [ "bearer", "jwt", "pwd", "pass", "passcode", "pin", "otp", "mfaCode", "password1", "userPassword123", "apiKey2", "token1", "socialSecurityNumber", "accessTokens", "authTokens", "sid", "signature", "webhookSignature", "hmacSignature", "hmac", "ssh_key", "accountNumber", "routingNumber", "csrf", "connectionString", "dsn", "database_url", ], ) def test_default_secret_filter_catches_common_credential_keys(key: str) -> None: payload = {key: "secret-val", "title": "safe"} assert [p.path for p in inspect_pointers(payload)] == ["/title"] assert redact_payload(payload) == {"title": "safe"} def test_benign_fields_and_alphanumeric_humanize_preserved() -> None: payload = { "emailSignature": "Best, Alice", "signatureDate": "2026-01-01", "mfaEnabled": True, "isMfaEnabled": False, "otpSent": True, "usage": {"tokens": 512}, "passwordPolicy": "min 12 chars", } offered = {p.path for p in inspect_pointers(payload)} assert offered >= { "/emailSignature", "/signatureDate", "/mfaEnabled", "/isMfaEnabled", "/otpSent", "/usage/tokens", "/passwordPolicy", } assert redact_payload(payload) == payload assert humanize_key("ipv4Address") == "Ipv4 address" assert humanize_key("s3Bucket") == "S3 bucket" assert humanize_key("base64Image") == "Base64 image" def test_secret_parent_with_allowed_descendant_keeps_inspect_and_redact_synced() -> ( None ): data = {"credentials": {"password": "pw", "username": "alice"}} assert [ p.path for p in inspect_pointers(data, mutable_paths=["/credentials/password"]) ] == ["/credentials/password"] assert redact_payload(data, mutable_paths=["/credentials/password"]) == { "credentials": {"password": "pw"} } flt = DefaultSecretFilter(allowlist=["/credentials/username"]) assert [p.path for p in inspect_pointers(data, is_secret=flt)] == [ "/credentials/username" ] assert redact_payload(data, is_secret=flt) == {"credentials": {"username": "alice"}} def test_dag_budget_depth_parity_grouped_exclusions_and_top_level_types() -> None: # Shared diamond DAG finishes quickly without exponential blowup. dag: dict[str, Any] = {"leaf": "ok"} for _ in range(31): dag = {"a": dag, "b": dag} start = time.perf_counter() redacted_dag = redact_payload(dag) assert time.perf_counter() - start < 1.0 assert isinstance(redacted_dag, dict) # Sequence nested in 31 dicts keeps its element keys in both walkers. nested: dict[str, Any] = {"arr": [{"x": 1}]} for _ in range(30): nested = {"n": nested} offered_arr = [p for p in inspect_pointers(nested) if p.path.endswith("/arr")] assert len(offered_arr) == 1 assert offered_arr[0].element_keys == ("x",) cur = redact_payload(nested) for _ in range(30): cur = cur["n"] assert cur["arr"] == [{"x": 1}] # Grouped section column exclusion stays consistent with redact_payload. grouped = { "groups": [ {"title": "G1", "items": [{"name": "a"}]}, {"title": "G2", "items": [{"name": "c"}]}, ] } for ex in ("/groups/items", "/groups/0/items"): assert [p.path for p in inspect_pointers(grouped, exclude=[ex])] == ["/groups"] assert redact_payload(grouped, exclude=[ex]) == { "groups": [{"title": "G1"}, {"title": "G2"}] } # Excluding index 0 keeps columns for items 1..N. items_payload = { "items": [ {"title": "a", "url": "https://x/a.png"}, {"title": "b", "url": "https://x/b.png"}, ] } by_path = {p.path: p for p in inspect_pointers(items_payload, exclude=["/items/0"])} assert by_path["/items"].element_keys == ("title", "url") assert redact_payload(items_payload, exclude=["/items/0"]) == { "items": [None, {"title": "b", "url": "https://x/b.png"}] } for bad in ([{"a": 1}], "raw"): with pytest.raises(TypeError, match="mapping"): inspect_pointers(bad) # type: ignore[arg-type] with pytest.raises(TypeError, match="mapping"): redact_payload(bad) # type: ignore[arg-type] def test_calibration_continuity_and_a2ui_validation_errors(tmp_path: Path) -> None: partial = {"a": 0.2, "b": 0.1} at_one = Calibration(1.0).apply(partial) near_one = Calibration(1.0 + 1e-7).apply(partial) assert at_one["a"] == pytest.approx(near_one["a"], abs=1e-6) assert at_one["b"] == pytest.approx(near_one["b"], abs=1e-6) with pytest.raises(A2uiValidationError): Calibration(temperature=0.0) bad_file = tmp_path / "bad.json" bad_file.write_text("[]", encoding="utf-8") with pytest.raises(A2uiValidationError): Calibration.load(bad_file, profile_key="default") with pytest.raises(A2uiValidationError): PointerSummary(path="/x", value_type="string", semantic_type=" ") def test_redact_payload_drops_non_json_objects() -> None: from dataclasses import dataclass @dataclass class _Creds: api_key: str payload: dict[str, Any] = { "title": "ok", "creds": _Creds(api_key="sk-123"), "raw": b"secret-bytes", "tags": {"a", "b"}, "items": ["keep", _Creds(api_key="sk-456"), b"bytes"], } redacted = redact_payload(payload) assert redacted == {"title": "ok", "items": ["keep", None, None]} def test_exclude_normalizes_trailing_slash_and_root() -> None: payload = {"internal": {"note": "x"}, "name": "n"} assert redact_payload(payload, exclude=["/internal/"]) == {"name": "n"} assert [p.path for p in inspect_pointers(payload, exclude=["/internal/"])] == [ "/name" ] assert redact_payload(payload, exclude=["/"]) == {} assert inspect_pointers(payload, exclude=["/"]) == () def test_catalog_decision_graph_v1_default_catalog_resolution() -> None: basic = BasicCatalog("1.0") cat_default = Catalog( "https://example.com/default/v1", "1.0", components=[basic.components["Text"]], ) cat_custom = Catalog( "https://example.com/custom/v1", "1.0", components=[basic.components["Text"], basic.components["Card"]], ) no_default = CatalogDecisionGraph([cat_default, cat_custom]) assert no_default.surface_catalog_id is None assert no_default.get_component("Card") is None assert no_default.get_component("Text") is None assert ( no_default.get_component(("https://example.com/custom/v1", "Card")) is not None ) with_default = CatalogDecisionGraph( [cat_default, cat_custom], default_catalog_id=cat_default.catalog_id, ) assert with_default.surface_catalog_id == cat_default.catalog_id assert with_default.get_component("Card") is None text_spec = with_default.get_component("Text") assert text_spec is not None and text_spec.catalog_id == cat_default.catalog_id assert ( with_default.get_component(("https://example.com/custom/v1", "Card")) is not None ) with pytest.raises(A2uiValidationError, match="default_catalog_id"): CatalogDecisionGraph( [cat_default, cat_custom], default_catalog_id="https://missing/v1" ) def test_readme_contents_lists_all_public_exports() -> None: import a2ui.experimental.decision as decision_pkg readme_path = Path(__file__).resolve().parents[1] / "README.md" readme_text = readme_path.read_text(encoding="utf-8") missing = [name for name in decision_pkg.__all__ if f"`{name}`" not in readme_text] assert not missing, f"README.md Contents is missing exported symbols: {missing}" @pytest.mark.asyncio async def test_r4_renormalizes_probability_sums_above_one_and_mock_scorer_weights() -> ( None ): import math q_choice = DecisionQuestion( id="route", kind=QuestionKind.CHOICE, prompt="Pick widget", options=("a", "b", "c"), ) q_bool = DecisionQuestion( id="gate", kind=QuestionKind.BOOLEAN, prompt="Show?", ) batch = DecisionBatch(state="test", questions=(q_choice, q_bool)) async def rounded_model(_batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: return ( DecisionAnswer( question_id="route", distribution=DecisionDistribution( probabilities={"a": 0.34, "b": 0.34, "c": 0.33}, calibrated=False, ), ), DecisionAnswer( question_id="gate", distribution=DecisionDistribution( probabilities={"yes": 0.6, "no": 0.6}, calibrated=False, ), ), ) answers = await invoke_decision_model(rounded_model, batch) assert math.isclose(sum(answers[0].distribution.probabilities.values()), 1.0) assert math.isclose(answers[0].distribution.probabilities["a"], 0.34 / 1.01) assert math.isclose(answers[1].distribution.probabilities["yes"], 0.5) assert math.isclose(answers[1].distribution.probabilities["no"], 0.5) # MockDecisionModel custom scorer returning unnormalized CHOICE weights succeeds. mock = MockDecisionModel( scorer=lambda q: DecisionDistribution( probabilities={opt: 1.0 for opt in q.candidates()}, calibrated=False, ) ) mock_answers = await invoke_decision_model( mock, DecisionBatch(state="test", questions=(q_choice,)) ) assert math.isclose(sum(mock_answers[0].distribution.probabilities.values()), 1.0) assert math.isclose(mock_answers[0].distribution.probabilities["a"], 0.25) def test_r4_redact_payload_preserves_large_arrays_and_trailing_sibling_keys() -> None: payload = { "items": [{"name": f"n{i}"} for i in range(5000)], "title": "Hello", } offered = {p.path for p in inspect_pointers(payload)} assert "/items" in offered assert "/title" in offered redacted = redact_payload(payload) assert len(redacted["items"]) == 5000 assert redacted["items"][0] == {"name": "n0"} assert redacted["items"][4999] == {"name": "n4999"} assert redacted["title"] == "Hello" def test_r5_access_key_pairs_redacted_and_shared_budget_signals_truncation() -> None: payload = { "title": "Hello", "access_key": "AKIA-SECRET-1", "accessKey": "AKIA-SECRET-2", "access_keys": ["AKIA-SECRET-3"], "aws_access_key_id": "AKID-SECRET", } redacted = redact_payload(payload) assert redacted == {"title": "Hello"} shared_meta = {"currency": "USD"} heavy = {"items": [{"id": i, "meta": shared_meta} for i in range(5000)]} with pytest.raises(A2uiValidationError, match="redaction budget exhausted"): redact_payload(heavy, on_budget_exhausted="raise") distinct = {"items": [{"id": i, "meta": {"currency": "USD"}} for i in range(5000)]} redacted_distinct = redact_payload(distinct, on_budget_exhausted="raise") assert len(redacted_distinct["items"]) == 5000