Repository navigation
feat(decision_gated_templates): add experimental gated template evaluator and pruner - #4342
gspencergoog wants to merge 16 commits into
Conversation
There was a problem hiding this comment.
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.
bc05f7a to
4fede91
Compare
…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): |
There was a problem hiding this comment.
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'}becausef"{mp}/"becomes"/", matching every JSON Pointer._redact_data_model({"a": 1}, exclude=("/",))returns{'a': 1}andexclude=("/priv/",)fails to redact"/priv/k", whereaspayload_inspector._is_mutable_pathhandles"/"and strips trailing slashes.- Array-field excludes like
exclude=("/items/note",)are filtered byinspect_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( |
There was a problem hiding this comment.
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, butValues: {redacted}dumps the entire Pythonrepr()of nested dicts/lists with no size cap (a 500-row payload produces >500 KB of state text, multiplied per question inStepZeroLogprobBackend). _redact_data_modelis also executed twice per call (here and again at line 532), constructing a fullPointerSummarydataclass (with regexhumanize_key) for every dict key on each pass.
Suggested fix:
- Always redact secrets unconditionally when building
DecisionBatch.state(passmutable_paths=()for state values, keepingmutable_pathsonly forinspect_pointersandupdateDataModel). - 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") |
There was a problem hiding this comment.
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:
- Build
self._graph = CatalogDecisionGraph(self._transport_catalogs)inGatedTemplateEvaluator.__init__and passgraph: CatalogDecisionGraph | None = None(anddefault_catalog_id: str | None = None) intoprune_components. - Resolve each component via
(comp.get("@catalogId") or default_catalog_id, comp.get("component")):SlotKind.CHILD: if the child ID is pruned, returnTruewhenslot.requiredelse 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'scomponentIdis pruned (and respect schemaminItems).SlotKind.NAMED_CHILD_ARRAY: filter items whereisinstance(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 schemaminItems(e.g.,1forTabs.tabs).
- 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: |
There was a problem hiding this comment.
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:
- Formatting (
python_ci.yml:119):uv run pyink --check .fails onmodels.py(line 105) andtest_gated_templates.py(lines 217, 236, 274, 322, 391, 553, 625). Running./scripts/fix_format.shoruv run pyinkfixes both. - Type checking:
BasicCatalogina2ui.core.basic_catalogis a function returningCatalogApi, causingpyright(reportGeneralTypeIssues) and 15mypyerrors acrosstest_gated_templates.py(including unannotatedcomponentsat line 323 andanswersat line 516). Sibling tests (e.g.tests/decision_binder/test_tool_pointer_binder.py:54) importCatalogApifroma2ui.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) |
There was a problem hiding this comment.
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):
CatalogDecisionGraphautomatically rejects mixed catalog versions viacheck_mixed_catalogs.- Verify
self._graph.protocol_version == "v1.0", raisingA2uiCatalogErrorotherwise. - Verify every non-
Nonespec.catalog_idis in{c.catalog_id for c in self._transport_catalogs}, raisingA2uiCatalogErrorif unknown. - At line 531, use
catalog_id = prepared.spec.catalog_id or self._graph.surface_catalog_idand omit"catalogId"fromcreateSurfacewhencatalog_id is None(supporting multi-catalog templates where components carry@catalogId, per v1.0agent_to_renderer.jsonwherecreateSurface.catalogIdis 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): |
There was a problem hiding this comment.
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 adict, leaving nestedMappingobjects intact (crashing onMappingProxyType, and keepingUserDictas a non-dict). - Lines 264 and 267 check
isinstance(metadata, dict)andisinstance(extensions, dict), returning early without strippinga2ui_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: |
There was a problem hiding this comment.
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].questionscontains onlyselect:templateandbackend_two.batches[1].questionscontains only the winning template's prefixed gate/variant questions. select_and_evaluateabstentions: empty template registry,required_pathsfiltering out ineligible templates, backend choosing"none", confidence belowmin_confidence, and unknown/ineligible template choice.- Omitted answers: backend omitting
select:template, agate:*question, or avariant:*question raisesDecisionBackendError. - Payload & redaction edge cases: JSON-string and root-sequence (
{"items": ...}) payloads, nestedtuplesecret/exclude redaction, andmutable_pathskeeping a field inupdateDataModelwithout leaking its plaintext value intoDecisionBatch.state. - Extraction validation: boolean
threshold/minConfidence, out-of-range/NaN values, single-option variant group withoutallowNone, conflictingallowNone/minConfidence, and reserved"none"names.
🤖 Agent-generated
| "service": "checkout-api", | ||
| "cpu": "40%", | ||
| "errorRate": "0.1%", | ||
| "internal_secret_note": "TOP_SECRET_MARKER", |
There was a problem hiding this comment.
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`. |
There was a problem hiding this comment.
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:
| (`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: |
There was a problem hiding this comment.
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
4fede91 to
a82ea09
Compare
Signed-off-by: Greg Spencer <gspencer@google.com>
Signed-off-by: Greg Spencer <gspencer@google.com>
|
Closing this PR in favor of the modularized replacement stack. @jacobsimionato: 🤖 Agent-generated |
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,ChildListtemplate objects, and emptyTabs.tabs), BFS reachability fromroot, and@metadata.extensionsstripping 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 (evaluateandselect_and_evaluate), variantmin_confidence/allow_nonehandling, and local secret redaction usingis_secret_pointerfrom the shared decision kernel so sibling experimental tracks remain isolated.Changes
GatedTemplateSpec(withfrom_messagessupporting bothcreateSurface.componentsandupdateComponents.components),GateSpec,VariantOption,VariantGroupSpec,GateDecisionRecord, andGatedTemplateResultinmodels.py.extract_gates_and_variantsandprune_componentsinpruner.py, storing gate and variant annotations under A2UI v1.0@metadata.extensionsso unpruned templates remain schema-valid v1.0 JSON.@experimentalGatedTemplateEvaluatorinevaluator.pybacked byDecisionBackend,inspect_pointers, andlower_for_transport.python/a2ui_agent/tests/decision_gated_templates/test_gated_templates.pyand updatedpython/a2ui_agent/CHANGELOG.md.Impact & Risks
a2ui.inference_formats.experimental.decision_gated_templateswith no imports from roota2ui.inference_formatsor sibling experimental tracks;test_experimental_import_isolation.pyremains green.root,GatedTemplateEvaluatorabstains rather than emitting an invalid surface.Testing