Skip to content

feat(python/agent): add optional DefaultCatalogSimplifier stage - #4551

Open
jacobsimionato wants to merge 1 commit into
macros/6-transformer-pipelinefrom
macros/6b-default-catalog-simplifier
Open

jacobsimionato wants to merge 1 commit into
macros/6-transformer-pipelinefrom
macros/6b-default-catalog-simplifier

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

In v1.0, builders (typed Python component classes; the Dart a2ui_cli tool generates them) and MacroExpander (which expands macros, Python functions that become A2UI components server-side) write the full catalog URI onto every component and every catalog function call. That keeps expansion stateless and lets one surface mix catalogs, but a single-catalog surface repeats the same URI everywhere:

{"createSurface": {"surfaceId": "main"}}  // before
{"updateComponents": {"surfaceId": "main", "components": [
  {"id": "root", "component": "Card", "child": "t", "@catalogId": "https://a2ui.org/.../basic/catalog.json"},
  {"id": "t", "component": "Text", "@catalogId": "https://a2ui.org/.../basic/catalog.json",
   "text": {"@call": "formatString", "catalogId": "https://a2ui.org/.../basic/catalog.json", "args": {...}}}]}}
// After: {"createSurface": {"surfaceId": "main", "catalogId": "https://a2ui.org/.../basic/catalog.json"}}, no per-item copies

This PR adds an opt-in pipeline stage that compacts those IDs on the way out, without putting catalog state back into MacroExpander.

Terms used below: a component's catalog annotation is @catalogId; a function call's is catalogId. A plain catalogId key on a component is not an annotation (it may be a component property), so the stage treats it as ambiguous and leaves that component alone. System functions (names starting with @, such as @index) belong to no catalog and never carry a catalogId. A batch is the message list passed to one transform_to_transport call: one full response, or one chunk when streaming.

Stack: 9/11 (overview) · previous: #4533 · next: #4534

Reviewer guide: A2UI Python macros: reviewer guide explains how the whole stack fits together.

Summary

  1. Add DefaultCatalogSimplifier, a stateless v1.0 MessageTransformer, exported from the existing public a2ui.catalog_transformers package. Use it in a TransformerPipeline or pass it via transformers= to A2uiGenerator / A2uiRequestProcessor.
  2. For each createSurface in a batch, the stage applies one rule:
    1. Strip: if createSurface already has a non-empty catalogId, remove annotations that match it. Other catalogs' annotations stay.
    2. Hoist, then strip: if it has no catalogId and every component and non-system call for that surface in the batch carries the same URI, set createSurface.catalogId to it and strip.
    3. Leave alone: mixed catalogs, a missing annotation, v0.9 messages, an explicit catalogId="", updateComponents with no createSurface earlier in the batch, and callRendererFunction messages.
  3. Document the stage in python/a2ui_agent/README.md and python/a2ui_agent/CHANGELOG.md.

Breaking changes: None. The stage is new and only runs when added.

New public API

from a2ui.catalog_transformers import DefaultCatalogSimplifier
from a2ui.core.basic_catalog import BasicCatalog
from a2ui.processor import A2uiGenerator, CatalogConfig
from a2ui.transformers.macros import MacroExpander

# List the simplifier BEFORE MacroExpander: transform_to_transport runs
# stages in reverse, so macros expand first and the simplifier runs last.
generator = A2uiGenerator(
    catalogs=[CatalogConfig(BasicCatalog("1.0"))],
    transformers=[
        DefaultCatalogSimplifier(),
        MacroExpander([FlightsTable]),  # a user-defined @macro
    ],
)

Where to review

Category Files Diff (+/-)
Production 2 +257 / -0
Tests 1 +880 / -0
Docs and changelog 2 +8 / -0
Total 5 +1145 / -0

Start here:

  1. python/a2ui_agent/src/a2ui/catalog_transformers/simplifier.py: check which messages count as one surface's part of a batch (they stop at the next createSurface or deleteSurface for the same surfaceId), and that any doubt blocks hoisting instead of guessing.
  2. The same file, nested calls: system functions and extension metadata are never stripped, and the hoist check is deliberately stricter than the strip step.
  3. python/a2ui_agent/tests/test_default_catalog_simplifier.py: the edge cases. Three tests also feed the output through a MessageProcessor with strict validation to confirm the client still accepts it.
Implementation details
  • transform_to_transport is async (the MessageTransformer base is async-first). It converts messages with to_message_dicts, edits the dicts, and rebuilds with type(orig).model_validate(...) only for messages it changed. Unchanged messages are returned as the original objects.
  • Version check: _is_v1_0_message compares to_version_number(msg["version"]) to v1.0, so other versions pass through.
  • _find_hoistable_catalog_id returns a URI only if every component is a dict with no plain catalogId, a non-empty @catalogId, and a non-empty catalogId on every non-system @call inside it, with exactly one distinct URI overall.
  • _strip_redundant_from_components removes @catalogId only when it matches and no plain catalogId is present, then calls _strip_nested_function_catalog_ids.
  • Metadata asymmetry: stripping skips a component's @metadata and legacy metadata keys as opaque. _collect_nested_function_catalog_ids still walks legacy metadata (it may be a custom property holding a @call), so hoisting stays conservative.
  • Streaming caveat (in the class docstring): the stage sees one batch at a time. Under A2uiRequestProcessor.aopen_stream(), a createSurface chunk with no components is not hoisted. A single-catalog first chunk of a mixed surface may be hoisted while later chunks from other catalogs keep their explicit @catalogId. Both outcomes stay valid on the wire.
Verification

Measured at the stack tip (all 11 commits applied); this PR's own commit was not run separately:

  • Full Python suite passes (6027 passed).
  • mypy clean (283 source files).
  • 56 conformance goldens valid.
  • Prettier and pyink clean on every commit; every commit has a DCO sign-off.

This PR adds python/a2ui_agent/tests/test_default_catalog_simplifier.py (10 async tests, several covering more than one case). They cover hoisting with nested calls, multi-catalog and cross-catalog preservation, already-defaulted surfaces, two-turn and v0.9 passthrough, deleteSurface/recreate boundaries, system-function and metadata skipping, explicit empty and conflicting plain catalogId, interleaved surfaces with input immutability, and an aopen_stream() run with the Express inference format (ExpressFormatFactory).

@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 the DefaultCatalogSimplifier message transformer, which compacts redundant per-component and per-function catalog IDs on v1.0 surfaces to optimize wire payloads. It also includes comprehensive unit tests verifying various scenarios such as hoisting, multi-catalog preservation, and segment boundaries. A review comment suggests an improvement in the message processing loop to check lifecycle boundaries before protocol versions, ensuring segment boundaries are always respected even across different protocol versions, and recommends using a 'version at least' check for forward compatibility.

Comment on lines +175 to +202
for later_idx in range(idx + 1, len(msg_dicts)):
later = msg_dicts[later_idx]
later_ver = later.get("version")
if (
not isinstance(later_ver, str)
or to_version_number(later_ver) != _V1_0_NUMBER
):
continue
later_cs = later.get("createSurface")
if (
isinstance(later_cs, dict)
and later_cs.get("surfaceId") == surface_id
):
break
later_ds = later.get("deleteSurface")
if (
isinstance(later_ds, dict)
and later_ds.get("surfaceId") == surface_id
):
break
later_uc = later.get("updateComponents")
if (
isinstance(later_uc, dict)
and later_uc.get("surfaceId") == surface_id
):
uc_comps = later_uc.get("components")
if isinstance(uc_comps, list) and uc_comps:
segment_entries.append((later_idx, uc_comps))

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.

high

The current implementation checks the protocol version (later_ver) before checking for lifecycle boundaries (createSurface or deleteSurface). If a message in the batch deletes or recreates the same surface using a different protocol version (e.g., v0.9), the loop will skip it and fail to break. This can cause the simplifier to incorrectly group and compact updateComponents messages from a completely different lifecycle segment.

Checking the lifecycle boundaries first, regardless of the protocol version, ensures segment boundaries are always respected. Additionally, when checking the protocol version, use a 'version at least' check (e.g., < _V1_0_NUMBER to skip older versions) instead of strict inequality to ensure forward compatibility with future versions.

            for later_idx in range(idx + 1, len(msg_dicts)):
                later = msg_dicts[later_idx]
                later_cs = later.get("createSurface")
                if (
                    isinstance(later_cs, dict)
                    and later_cs.get("surfaceId") == surface_id
                ):
                    break
                later_ds = later.get("deleteSurface")
                if (
                    isinstance(later_ds, dict)
                    and later_ds.get("surfaceId") == surface_id
                ):
                    break
                later_ver = later.get("version")
                if (
                    not isinstance(later_ver, str)
                    or to_version_number(later_ver) < _V1_0_NUMBER
                ):
                    continue
                later_uc = later.get("updateComponents")
                if (
                    isinstance(later_uc, dict)
                    and later_uc.get("surfaceId") == surface_id
                ):
                    uc_comps = later_uc.get("components")
                    if isinstance(uc_comps, list) and uc_comps:
                        segment_entries.append((later_idx, uc_comps))
References
  1. When checking protocol or specification versions for feature availability, use a 'version at least' check instead of strict equality to ensure forward compatibility with future versions.

@jacobsimionato jacobsimionato changed the title macros/6b default catalog simplifier feat(python/agent): add optional DefaultCatalogSimplifier stage Dec 2, 2026
@jacobsimionato
jacobsimionato removed this pull request from stack #4552 December 3, 2026 12:03
@jacobsimionato
jacobsimionato force-pushed the macros/6b-default-catalog-simplifier branch from 6dac5c6 to 6e5d991 Compare December 3, 2026 12:04
@jacobsimionato
jacobsimionato marked this pull request as ready for review December 3, 2026 12:04
@jacobsimionato
jacobsimionato removed this pull request from stack #4563 December 3, 2026 12:06
…tion stage

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/6b-default-catalog-simplifier branch from 6e5d991 to 33726e6 Compare December 3, 2026 12:24

This branch has not been deployed

No deployments
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.

1 participant