Skip to content

fix(python/builder,cli)!: fix builder ID collisions and CLI schema parity - #4564

Open
jacobsimionato wants to merge 1 commit into
mainfrom
macros/3-builder-ids-and-cli-v2
Open

jacobsimionato wants to merge 1 commit into
mainfrom
macros/3-builder-ids-and-cli-v2

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Python builders are typed component classes that dart/a2ui_cli generates from a catalog. The flattener turns a tree of builders into the flat, ID-linked component list that A2UI sends to a surface (one rendered UI on the client). This PR fixes two problems with them:

  1. Duplicate IDs. The flattener could emit two components with the same ID, so one silently replaced the other on the client. Flattening [Text(...), Text(...)] gave both roots the ID root__text_1. A macro (a Python function that expands into A2UI components on the server) could also pick an auto ID that was already used on the surface.
  2. Codegen looser than the schemas. Generated builders accepted values the catalog JSON Schemas reject, such as a FunctionCall on Icon.name, a float where the schema says integer, or an empty Tabs.tabs.

Related: #4189, #4190. Replaces #4530 (GitHub marked it merged during a stack reorder; nothing landed on main).

Stack: 1/11 (overview) · previous: none (base is main) · next: #4565

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

Summary

  1. The flattener collects every known ID first (explicit IDs, ComponentRef targets, caller reserved_ids), then allocates automatic IDs around them. In a list, each anonymous root gets the first free root_<n> (counting from its index), and its anonymous descendants get <root>__<type>_<k>, such as root_1__text_2. Real collisions raise A2uiValidationError.
  2. The macro expander passes the IDs already in the component list to the flattener, so macro output skips them.
  3. ComponentTree gains dangling_components and catalog_id, and allows root=None.
  4. dart/a2ui_cli generates builders that match the catalog schemas. The v0_9 and v1_0 basic catalogs are regenerated.

Breaking changes and migration

  1. Collisions raise. flatten_component_tree raises A2uiValidationError for duplicate explicit sibling IDs and for explicit IDs that match reserved_ids or a ComponentRef. Give sibling nodes distinct IDs.
  2. Anonymous multi-root IDs. flatten_component_tree([Text(...), Text(...)]) now emits root_0, root_1 instead of root__text_1 twice.
  3. ComponentTree.flatten() keeps explicit IDs verbatim. Card(id="hero", child=Text(id="title", ...)) now emits title, not hero__title. A ComponentTree is a whole wire tree, so its IDs must round-trip. flatten_component_tree keeps its old prefixing default for subtrees such as macro output; pass preserve_ids=True to opt out.
  4. Required nullable fields serialize as null. A required field set to None now appears as JSON null instead of being dropped by exclude_none=True.
  5. ComponentTree.root is optional (ComponentBuilderNode | None = None). Check tree.root is not None before reading it.
  6. Stricter generated basic catalog builders. Dynamic* fields (literal, data binding, or function call) use Pydantic's StrictStr/StrictInt/StrictFloat, so an int passed to Text.text is rejected instead of coerced. Icon.name drops FunctionCall. Slider.steps is int >= 1, Length min/max are int, Tabs.tabs needs at least one item, and DateTimeInput.min/max are DynamicString (previously Any).
  7. a2ui_cli Dart API. EnumType.values widens from List<String> to List<Object>, and the sealed TypeDescriptor gains FunctionCallType. Exhaustive switch expressions on TypeDescriptor must handle it.

New public API

dangling_components holds subtrees that aren't attached to root but go out in the same flattened list. catalog_id records which catalog the tree targets, next to surface_id; flatten() doesn't read it.

from a2ui.builder.core import ComponentTree, flatten_component_tree
from a2ui.builder.v1_0.catalogs.basic import CATALOG_ID, Card, Text

tree = ComponentTree(
    root=Card(id="hero", child=Text(id="title", text="Hello")),
    dangling_components=[Text(id="hint", text="Shown later")],
    catalog_id=CATALOG_ID,
)
tree.flatten()  # ids in post-order (children first): title, hero, hint

# Skip IDs that already exist on the surface.
flatten_component_tree([Text(text="a"), Text(text="b")], reserved_ids={"root_0"})
# ids: root_1, root_2

Also new: preserve_ids on flatten_component_tree and IdAllocator, external_ids on IdAllocator, CATALOG_COMPONENTS (component name to builder class) in generated catalogs, and __all__ in a2ui.builder.v0_9.models.

Where to review

Category Files Diff (+/-)
Production (Python runtime, macro expander, Dart CLI) 12 +791 / -140
Generated catalogs and CLI goldens 6 +300 / -146
Tests 4 +460 / -12
Docs and changelogs 3 +43 / -2
Total 25 +1594 / -300

Start here:

  1. python/a2ui_agent/src/a2ui/builder/core/flattener.py: how IDs are reserved across all roots before any automatic ID is picked.
  2. python/a2ui_agent/src/a2ui/builder/core/child.py and id_allocator.py: how a collision found deep in the tree reaches the caller as an error.
  3. python/a2ui_agent/src/a2ui/builder/core/base_model.py: keeping required None fields on the wire without breaking include/exclude.
  4. dart/a2ui_cli/lib/src/analyzer/catalog_analyzer.dart: how schema constraints, allOf, and nullability turn into Python types.
Implementation details
  • Flattener and allocator
    • flatten_component_tree and ComponentTree.flatten() both call the shared two-pass _flatten_root_entries. Pass 1 reserves IDs; pass 2 allocates and emits.
    • _collect_unscoped_ids runs a throwaway scan to find IDs that land on the wire unprefixed (ComponentRef IDs, plus explicit IDs when preserve_ids is set), so anonymous roots avoid them when choosing root_<n>.
    • Pass 1 shares reserved, external_ids, seen_explicit, and visited across all roots. Pass 2 uses one base IdAllocator and gives each root a scoped view through _with_scope, which shares the claimed and reserved sets.
    • IdAllocator._check_unclaimed rejects an explicit ID that resolves to an external ID or one already claimed in the tree.
    • Collision errors are stored on FlattenContext.error and re-raised by the flattener, because Pydantic's union serializer swallows exceptions raised inside the Child PlainSerializer.
  • ComponentTree.flatten() builds entries for the root and each dangling component and calls _flatten_root_entries(..., preserve_ids=True). Dangling components without an ID share the root's scope.
  • Required nullable fields: BuilderBaseModel adds a wrap model_serializer that puts required None fields back after exclude_none=True, while honoring include/exclude/exclude_unset.
  • Macro expander (transformers/macros/expander.py, processor.py): _expand_component_list collects the IDs in the incoming list plus any caller reserved_ids, passes them (minus the macro's own ID) down to flatten_component_tree, and adds each expansion's output IDs before expanding the next macro.
  • Dart CLI
    • catalog_analyzer.dart: "integer" maps to PrimitiveKind.integer (previously grouped with "number"). Reads minimum/maximum/minItems/maxItems, merges allOf (tightest bound wins), resolves FunctionCall $ref in oneOf/anyOf, and tracks nullability on PropertyDescriptor.
    • type_mapper.dart: DynamicType over string, number, boolean, any, and string list maps to DynamicString, DynamicNumber, DynamicBoolean, DynamicValue, and DynamicStringList.
    • python_emitter.dart: emits Field(ge=..., le=..., min_length=..., max_length=...), the CATALOG_ID and CATALOG_COMPONENTS registry, the extra runtime imports, and the full __all__.
  • python/a2ui_agent/src/a2ui/builder/README.md updates the Icon.name type and the note on custom serializers.
Verification

Measured at the stack tip (all 11 commits applied); these runs were not repeated on this commit alone:

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

Tests added in this PR: test_multi_root_flattening_and_collision_avoidance, test_component_tree_roundtrip_and_dag_order_independence, and test_required_nullable_serialization_and_v09_basic_catalog_parity in test_pydantic_builders.py, test_v10_basic_catalog_constraints_registry_and_strict_dynamic_types in test_pydantic_builders_v1_0.py, test_macro_expander_reserves_existing_sibling_ids in test_macros.py, and a schema-parity case in dart/a2ui_cli/test/codegen_test.dart.

@jacobsimionato jacobsimionato changed the title macros/3 builder ids and cli v2 fix(python/builder,cli): fix ID collisions and CLI schema parity Dec 3, 2026

@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 aligns the Python code generator with catalog JSON schemas by supporting integer, numeric, boolean, and nullable enums, merging allOf constraints, and resolving oneOf/anyOf nullability. It tightens validation in generated builders by emitting strict Dynamic* aliases and validation bounds (such as ge, le, min_length, and max_length). Additionally, it enforces stricter builder ID collision checks during component tree flattening, preserves explicit None values on required nullable fields, and introduces a catalog registry (CATALOG_COMPONENTS) and CATALOG_ID to generated modules. I have no feedback to provide as there are no review comments.

@jacobsimionato jacobsimionato changed the title fix(python/builder,cli): fix ID collisions and CLI schema parity fix(python/builder,cli)!: fix builder ID collisions and CLI schema parity Dec 3, 2026
…ound-trip guardrails

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/3-builder-ids-and-cli-v2 branch from 69fae65 to bf834b7 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