Skip to content

feat(decision_gated_templates): add experimental gated template evaluator and pruner - #4342

Closed
gspencergoog wants to merge 16 commits into
feat/decision-rpc-predicatesfrom
feat/decision-gated-templates
Closed

gspencergoog wants to merge 16 commits into
feat/decision-rpc-predicatesfrom
feat/decision-gated-templates

Conversation

@gspencergoog

Copy link
Copy Markdown
Collaborator

Summary

Add an experimental gated template engine (a2ui.inference_formats.experimental.decision_gated_templates) that evaluates optional component regions (a2ui_gate) and mutually exclusive layout variants (a2ui_variant) in one decision batch and prunes excluded subtrees before emitting validated A2UI v1.0 wire messages.

Reviewer Focus

  • python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_gated_templates/pruner.py: fixed-point upward pruning for required child slots (Card.child, Button.child, Modal.trigger, Modal.content, ChildList template objects, and empty Tabs.tabs), BFS reachability from root, and @metadata.extensions stripping that preserves unrelated vendor extensions.
  • python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_gated_templates/evaluator.py: single-batch and two-call split evaluation (evaluate and select_and_evaluate), variant min_confidence / allow_none handling, and local secret redaction using is_secret_pointer from the shared decision kernel so sibling experimental tracks remain isolated.

Changes

  • Added GatedTemplateSpec (with from_messages supporting both createSurface.components and updateComponents.components), GateSpec, VariantOption, VariantGroupSpec, GateDecisionRecord, and GatedTemplateResult in models.py.
  • Added extract_gates_and_variants and prune_components in pruner.py, storing gate and variant annotations under A2UI v1.0 @metadata.extensions so unpruned templates remain schema-valid v1.0 JSON.
  • Added @experimental GatedTemplateEvaluator in evaluator.py backed by DecisionBackend, inspect_pointers, and lower_for_transport.
  • Added unit tests in python/a2ui_agent/tests/decision_gated_templates/test_gated_templates.py and updated python/a2ui_agent/CHANGELOG.md.

Impact & Risks

  • Isolated under a2ui.inference_formats.experimental.decision_gated_templates with no imports from root a2ui.inference_formats or sibling experimental tracks; test_experimental_import_isolation.py remains green.
  • If upward pruning removes a required child of root, GatedTemplateEvaluator abstains rather than emitting an invalid surface.

Testing

uv run pytest python/a2ui_agent/tests/decision_gated_templates/ python/a2ui_agent/tests/decision/ python/a2ui_agent/tests/test_experimental_import_isolation.py
uv run ruff check python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_gated_templates/ python/a2ui_agent/tests/decision_gated_templates/
uv run pyright python/a2ui_agent/src/a2ui/inference_formats/experimental/decision_gated_templates/

@gspencergoog
gspencergoog added this pull request to stack #4343 November 20, 2026 22:51

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces experimental decision-model gated templates for A2UI v1.0 surfaces, allowing the evaluation of boolean region gates and mutually exclusive variants, along with component pruning and data redaction. The review feedback highlights several important improvements: first, _format_state_text must accept and forward exclude and mutable_paths to _redact_data_model to prevent sensitive data leakage to the decision backend; second, type checking for children in _clean_parent_references should use Mapping instead of dict for better robustness; and finally, validation should be added to detect conflicting prompts within the same variant group.

…ator and pruner

Signed-off-by: Greg Spencer <gspencer@google.com>
…daction, Mapping, and prompt consistency

Signed-off-by: Greg Spencer <gspencer@google.com>
…uple sequences in pruner

Signed-off-by: Greg Spencer <gspencer@google.com>
continue
cleaned[key_str] = _redact_value(child, child_path, exclude, mutable_set)
return cleaned
if isinstance(value, list):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Secret and exclude redaction can be bypassed in two ways: _redact_value only recurses into list, so nested tuple (or other Sequence) values such as {"items": ({"apiKey": "sk_live_..."},)} leak credentials and excluded fields verbatim into both DecisionBatch.state and updateDataModel; and _is_excluded/_is_mutable diverge from payload_inspector.py, causing mutable_paths=("",) to match every path and silently disable all secret redaction while exclude=("/",) or trailing slashes ("/priv/") fail to redact anything.

Additional details

Verified repros against _redact_data_model:

  • _redact_data_model({"items": ({"apiKey": "sk_live_SECRET"},)}, exclude=("/items/0/apiKey",)) returns {'items': ({'apiKey': 'sk_live_SECRET'},)} unredacted.
  • _redact_data_model({"password": "SECRET"}, mutable_paths=("",)) returns {'password': 'SECRET'} because f"{mp}/" becomes "/", matching every JSON Pointer.
  • _redact_data_model({"a": 1}, exclude=("/",)) returns {'a': 1} and exclude=("/priv/",) fails to redact "/priv/k", whereas payload_inspector._is_mutable_path handles "/" and strips trailing slashes.
  • Array-field excludes like exclude=("/items/note",) are filtered by inspect_pointers (payload_inspector.py:678-684) but left intact in _redact_value.

Because this logic is also duplicated almost verbatim in decision_binder/binder.py:114-177, consider centralizing a single redact_data_model helper in a2ui.inference_formats.experimental.decision.payload_inspector so both tracks stay in sync:

def _matches_pointer_prefix(path: str, prefixes: Collection[str]) -> bool:
    for raw in prefixes:
        if not raw:
            continue
        if raw == "/" or path == raw:
            return True
        trimmed = raw.rstrip("/")
        if trimmed and (path == trimmed or path.startswith(f"{trimmed}/")):
            return True
    return False

# Inside _redact_value:
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
    return [
        _redact_value(item, f"{prefix}/{idx}", exclude, mutable_set, depth=depth + 1)
        for idx, item in enumerate(value)
        if not _matches_pointer_prefix(f"{prefix}/{idx}", exclude)
    ]

Also consider enforcing _MAX_INSPECT_DEPTH (32) matching payload_inspector.py.

🤖 Agent-generated

f" label={ptr.label}{extra})"
)
# Include redacted scalar values so boolean gates can reason about payload content.
redacted = _redact_data_model(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forwarding mutable_paths into _format_state_text exposes plaintext secret values (such as an editable /password or /apiKey field) in DecisionBatch.state sent to external decision backends, and appending unbounded repr(redacted) can blow up request sizes on large payloads instead of only summarizing scalar values as the comment intends.

Additional details

In payload_inspector.py, mutable_paths exists so user-editable credential fields remain visible as structural pointers (e.g. - /password (string/string, label=Password)) and stay present in the client's updateDataModel. Unlike decision_binder, _format_state_text here appends Values: {redacted} directly into DecisionBatch.state — so passing mutable_paths=("/password",) produces Values: {'password': 'PLAINTEXT_PW'} in the outbound model prompt.

Additionally:

  • Line 146 says # Include redacted scalar values, but Values: {redacted} dumps the entire Python repr() of nested dicts/lists with no size cap (a 500-row payload produces >500 KB of state text, multiplied per question in StepZeroLogprobBackend).
  • _redact_data_model is also executed twice per call (here and again at line 532), constructing a full PointerSummary dataclass (with regex humanize_key) for every dict key on each pass.

Suggested fix:

  1. Always redact secrets unconditionally when building DecisionBatch.state (pass mutable_paths=() for state values, keeping mutable_paths only for inspect_pointers and updateDataModel).
  2. Serialize only a bounded JSON preview of redacted scalar values (e.g., per-value truncation + total character cap) rather than unbounded repr(redacted).
state_values = _redact_data_model(data_model, exclude=exclude, mutable_paths=())

🤖 Agent-generated

)

_ROOT_ID = "root"
_REQUIRED_SINGLE_CHILD_KEYS: tuple[str, ...] = ("child", "trigger", "content")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hardcoding Basic Catalog child property names (child, trigger, content, children, tabs) breaks custom v1.0 catalogs: any container using another Child/ChildList property name (such as SplitPane.leftPane or Panel.header) has its children silently dropped as unreachable by BFS and crashes lower_for_transport with A2uiIntegrityError: Dangling reference even when no gate fires. In the reverse direction, components with optional Child slots wrongly prune their parent, and components with plain string properties named content or trigger get falsely pruned whenever a pruned component happens to share that string as its ID.

Additional details

Per AGENTS.md (Keep Inference Formats Catalog-Agnostic) and specification/v1_0/docs/a2ui_protocol.md, structural child relationships are declared in each catalog's JSON Schema via $ref to ComponentId / Child / ChildList (and minItems on array slots), not by a fixed list of property names.

The shared a2ui.inference_formats.experimental.decision kernel already provides CatalogDecisionGraph, which classifies every component's slots into SlotKind.CHILD, SlotKind.CHILD_LIST, and SlotKind.NAMED_CHILD_ARRAY along with slot.required and slot.child_id_key.

Suggested approach:

  1. Build self._graph = CatalogDecisionGraph(self._transport_catalogs) in GatedTemplateEvaluator.__init__ and pass graph: CatalogDecisionGraph | None = None (and default_catalog_id: str | None = None) into prune_components.
  2. Resolve each component via (comp.get("@catalogId") or default_catalog_id, comp.get("component")):
    • SlotKind.CHILD: if the child ID is pruned, return True when slot.required else remove the optional property (comp.pop(slot.name, None)).
    • SlotKind.CHILD_LIST: filter pruned IDs from static sequences or cascade upward if a template object's componentId is pruned (and respect schema minItems).
    • SlotKind.NAMED_CHILD_ARRAY: filter items where isinstance(tab.get(slot.child_id_key), str) and tab[slot.child_id_key] in pruned (which also guards against unhashable values at line 299), and cascade upward when remaining items fall below schema minItems (e.g., 1 for Tabs.tabs).
  3. Keep the Basic Catalog heuristic only as a fallback when graph is None.
# Repro: a valid custom v1.0 catalog template with no gates crashes evaluate():
# SplitPane { leftPane: {$ref: "common_types.json#/$defs/Child"} }
# -> prune_components drops 'l' as unreachable -> A2uiIntegrityError: Dangling reference

🤖 Agent-generated

)


def _basic() -> BasicCatalog:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR fails repository CI formatting (uv run pyink --check . wants to reformat models.py and test_gated_templates.py), and annotating _basic() -> BasicCatalog fails both pyright and mypy because BasicCatalog is a factory function returning CatalogApi, not a class.

Additional details

Because this PR currently targets feat/decision-rpc-predicates rather than main, python_ci.yml did not run on GitHub, but two gates fail locally:

  1. Formatting (python_ci.yml:119): uv run pyink --check . fails on models.py (line 105) and test_gated_templates.py (lines 217, 236, 274, 322, 391, 553, 625). Running ./scripts/fix_format.sh or uv run pyink fixes both.
  2. Type checking: BasicCatalog in a2ui.core.basic_catalog is a function returning CatalogApi, causing pyright (reportGeneralTypeIssues) and 15 mypy errors across test_gated_templates.py (including unannotated components at line 323 and answers at line 516). Sibling tests (e.g. tests/decision_binder/test_tool_pointer_binder.py:54) import CatalogApi from a2ui.core:
from a2ui.core import A2uiCatalogError, CatalogApi

def _basic() -> CatalogApi:
    return BasicCatalog(ProtocolVersion.V1_0)

Also annotate components: list[dict[str, Any]] = [...] at line 323 and answers: dict[str, tuple[str, float] | float] = {...} at line 516 so mypy passes cleanly.

🤖 Agent-generated

raise ValueError(f"max_pairs must be >= 1, got {max_pairs}.")

self._backend = backend
self._transport_catalogs = tuple(transport_catalogs)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GatedTemplateEvaluator.__init__ accepts non-v1.0 catalogs (and mixed protocol versions) as well as templates whose catalog_id isn't in transport_catalogs, deferring configuration errors until after a backend answer() call. Additionally, line 531 arbitrarily forces transport_catalogs[0].catalog_id as createSurface.catalogId when multiple catalogs are active and spec.catalog_id is omitted.

Additional details

Because _apply_answers hardcodes "version": "1.0" at line 538, passing a v0.9 catalog (or mixed v0.9/v1.0 catalogs) or an unregistered spec.catalog_id should fail fast at registration time rather than after spending a decision-model round trip (compare decision_binder's unknown catalog_id check in commit b755edd34f).

When building self._graph = CatalogDecisionGraph(self._transport_catalogs) in __init__ (which also enables catalog-agnostic pruning):

  • CatalogDecisionGraph automatically rejects mixed catalog versions via check_mixed_catalogs.
  • Verify self._graph.protocol_version == "v1.0", raising A2uiCatalogError otherwise.
  • Verify every non-None spec.catalog_id is in {c.catalog_id for c in self._transport_catalogs}, raising A2uiCatalogError if unknown.
  • At line 531, use catalog_id = prepared.spec.catalog_id or self._graph.surface_catalog_id and omit "catalogId" from createSurface when catalog_id is None (supporting multi-catalog templates where components carry @catalogId, per v1.0 agent_to_renderer.json where createSurface.catalogId is optional).

🤖 Agent-generated

def _strip_gate_metadata(comp: dict[str, Any]) -> None:
"""Removes `a2ui_gate` and `a2ui_variant` from `@metadata.extensions` in place."""
metadata = comp.get("@metadata")
if not isinstance(metadata, dict):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a template component uses a non-dict Mapping (such as UserDict or MappingProxyType) inside @metadata or @metadata.extensions, extract_gates_and_variants reads it cleanly, but prune_components either crashes in copy.deepcopy (TypeError: cannot pickle 'mappingproxy' object) or silently fails to strip a2ui_gate/a2ui_variant because _strip_gate_metadata checks isinstance(..., dict), leaking internal extension metadata onto the wire.

Additional details

GatedTemplateSpec.components and prune_components are typed Sequence[Mapping[str, Any]], and _get_extensions accepts any Mapping. However:

  • Line 323 (copy.deepcopy(dict(c))) only converts the outermost component to a dict, leaving nested Mapping objects intact (crashing on MappingProxyType, and keeping UserDict as a non-dict).
  • Lines 264 and 267 check isinstance(metadata, dict) and isinstance(extensions, dict), returning early without stripping a2ui_gate/a2ui_variant.

Replacing copy.deepcopy(dict(c)) with a small recursive JSON-plain cloner fixes both issues cleanly (and avoids deepcopy overhead on plain JSON dicts):

def _clone_json_value(value: Any) -> Any:
    if isinstance(value, Mapping):
        return {str(k): _clone_json_value(v) for k, v in value.items()}
    if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
        return [_clone_json_value(item) for item in value]
    return copy.deepcopy(value)

Then every nested @metadata and extensions mapping in copies is guaranteed to be a plain mutable dict.

🤖 Agent-generated



@pytest.mark.asyncio
async def test_select_and_evaluate_single_call_and_two_call_split() -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Several core error, abstention, and input-normalization paths have no test coverage yet — including the omitted-answer DecisionBackendError checks, all select_and_evaluate abstention branches, and the actual batch contents of the two-call split (which currently only asserts decision_calls == 2).

Additional details

Gaps worth covering in test_gated_templates.py:

  • Two-call split: verify backend_two.batches[0].questions contains only select:template and backend_two.batches[1].questions contains only the winning template's prefixed gate/variant questions.
  • select_and_evaluate abstentions: empty template registry, required_paths filtering out ineligible templates, backend choosing "none", confidence below min_confidence, and unknown/ineligible template choice.
  • Omitted answers: backend omitting select:template, a gate:* question, or a variant:* question raises DecisionBackendError.
  • Payload & redaction edge cases: JSON-string and root-sequence ({"items": ...}) payloads, nested tuple secret/exclude redaction, and mutable_paths keeping a field in updateDataModel without leaking its plaintext value into DecisionBatch.state.
  • Extraction validation: boolean threshold/minConfidence, out-of-range/NaN values, single-option variant group without allowNone, conflicting allowNone/minConfidence, and reserved "none" names.

🤖 Agent-generated

"service": "checkout-api",
"cpu": "40%",
"errorRate": "0.1%",
"internal_secret_note": "TOP_SECRET_MARKER",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This regression test passes even if exclude is completely ignored, because the key name "internal_secret_note" contains "secret" and is already stripped by is_secret_pointer. Renaming it to a non-secret key like "internal_note" ensures the test actually verifies exclude forwarding.

Additional details

In decision/payload_inspector.py:650, _SECRET_FACT_AVOID_KEYS includes "secret", so is_secret_pointer strips "internal_secret_note" regardless of exclude=. Using a benign field name (and asserting it is absent from both backend.batches[0].state and updateDataModel.value) makes the regression check effective:

    result = await evaluator.evaluate(
        "incident",
        "Show status",
        {
            "service": "checkout-api",
            "cpu": "40%",
            "errorRate": "0.1%",
            "internal_note": "TOP_SECRET_MARKER",
        },
        exclude=("/internal_note",),
    )
    assert backend.batches
    assert "TOP_SECRET_MARKER" not in (backend.batches[0].state or "")
    dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in result.messages]
    assert "internal_note" not in dumped[2]["updateDataModel"]["value"]

🤖 Agent-generated

and `prune_components` in
`a2ui.inference_formats.experimental.decision_gated_templates` for evaluating
boolean region gates (`a2ui_gate`) and mutually exclusive variants
(`a2ui_variant`) stored in A2UI v1.0 `@metadata.extensions`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ## Unreleased changelog entry is missing the clickable PR link ([#4342](https://github.com/a2ui-project/a2ui/pull/4342)) expected by the repo changelog convention.

Additional details

Per .agents/skills/update-changelog/SKILL.md (Rule 6), changelog entries should conclude with a link to their PR:

Suggested change
(`a2ui_variant`) stored in A2UI v1.0 `@metadata.extensions`.
(`a2ui_variant`) stored in A2UI v1.0 `@metadata.extensions`.
[#4342](https://github.com/a2ui-project/a2ui/pull/4342)

🤖 Agent-generated

)
)

for group in prepared.variants:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a allowNone=False variant group is nested inside a component whose boolean gate already decided to prune it, evaluating all variant groups before pruning can cause the entire surface to abstain over a low-confidence choice in a region that won't render anyway.

Additional details

In _apply_answers, gates are processed first (lines 438-460) and variants second (lines 462-518), while reachability pruning doesn't run until line 520. If a gated section (e.g. a charts_section card) is pruned because the payload has no time-series data, a nested chart_type variant group with allowNone=False and minConfidence=0.75 will naturally score low confidence and trigger full-surface abstention at line 475.

If you run an initial gate-prune pass (or check reachability after gates) before enforcing allow_none=False / min_confidence on variant groups whose options are all already unreachable, nested gate + variant compositions behave much more gracefully.

🤖 Agent-generated

@gspencergoog
gspencergoog force-pushed the feat/decision-gated-templates branch from 4fede91 to a82ea09 Compare November 30, 2026 16:58
@gspencergoog

Copy link
Copy Markdown
Collaborator Author

Closing this PR in favor of the modularized replacement stack.

@jacobsimionato: a2ui.experimental.decision.gated (gated template evaluator and schema-driven pruner) has been moved into #4474, with previous review comments incorporated.

🤖 Agent-generated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants