Skip to content

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

Merged
jacobsimionato merged 0 commit into
mainfrom
macros/3-builder-ids-and-cli
Dec 3, 2026
Merged

jacobsimionato merged 0 commit into
mainfrom
macros/3-builder-ids-and-cli

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Python's typesafe component builders—generated by dart/a2ui_cli and flattened into flat A2UI wire lists in two passes at runtime—suffered from silent component-ID collisions across multi-root trees, duplicate explicit sibling IDs, explicit ID references (ComponentRef), and macro expansions. At the same time, dart/a2ui_cli's Python emitter dropped several JSON Schema constraints and catalog metadata fields, accepted invalid FunctionCall values on Icon.name, and lacked structural hooks needed for future wire deserialization.

Summary

  1. Fix all four builder ID-collision paths: Scope multi-root sequences under root_0, root_1, … inside a shared flattening context, fail loud with A2uiValidationError on duplicate explicit sibling IDs, reserve ComponentRef targets during the first pass before allocating automatic IDs, and pass reserved_ids from MacroExpander into flatten_component_tree.
  2. Add round-trip guardrails for future deserialization: Add preserve_ids, dangling_components (unattached components carried alongside a tree), and catalog_id to ComponentTree, preserve required nullable None values as explicit JSON null, emit CATALOG_ID / CATALOG_COMPONENTS / complete __all__ in generated catalogs, and add __all__ to a2ui.builder.v0_9.models.
  3. Close dart/a2ui_cli Python codegen schema gaps: Emit strict data-binding Dynamic* aliases, split DataBinding vs FunctionCall in unions (fixing Icon.name), preserve integer and minimum/minItems constraints (Slider.steps int >= 1, Tabs.tabs min_length=1), inspect allOf schemas (DateTimeInput.min/max -> DynamicString), and preserve numeric/boolean enums and required nullable fields (fix(cli): preserve Python enum types and nullable fields #4189, fix(python): preserve required null fields in builder serialization #4190).

Breaking changes: None for valid builder trees. Two previously broken patterns now fail fast instead of silently emitting corrupt wire payloads: duplicate explicit sibling IDs raise A2uiValidationError, and Icon.name rejects FunctionCall.

New public API

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

# Preserve explicit component IDs and carry unattached ("dangling") components
tree = ComponentTree(
    root=Card(id="hero", child=Text(text="Hello")),
    dangling_components=[Text(id="detached_hint", text="Hint")],
    catalog_id=CATALOG_ID,
    preserve_ids=True,
)
# Avoid auto-ID collisions with existing surface/sibling component IDs
flat = flatten_component_tree(tree.root, reserved_ids={"text_1"})

Diff breakdown & where to review

Category Files Diff Summary
Production logic 12 +592 / -106 Builder runtime (flattener.py, id_allocator.py, tree.py, base_model.py, child.py), expander.py, and dart/a2ui_cli analyzer/emitter
Generated builders & goldens 6 +288 / -146 Regenerated v0_9/v1_0 basic.py catalogs and 4 dart/a2ui_cli fixture goldens
Tests & conformance 4 +281 / -12 Builder ID-collision, schema-parity, macro collision, and Dart CLI codegen tests
Docs & changelogs 1 +13 / -0 python/a2ui_agent/CHANGELOG.md
Total 23 +1174 / -264 486 net prod lines (+592 / -106) across 12 files

Start here

  1. Two-pass flattening & collision errors (python/a2ui_agent/src/a2ui/builder/core/flattener.py): Verify first-pass reservation of explicit IDs and ComponentRef targets, and confirm fatal collision errors recorded on FlattenContext.error re-raise cleanly (since Pydantic union serialization otherwise swallows raised errors).
  2. Nullable preservation (python/a2ui_agent/src/a2ui/builder/core/base_model.py): Check the serializer hook ensuring optional None fields stay omitted while required nullable fields serialize as JSON null.
  3. Dart CLI analyzer & Python emitter (dart/a2ui_cli/lib/src/analyzer/catalog_analyzer.dart, dart/a2ui_cli/lib/src/emitters/python/python_emitter.dart): Verify allOf merging, integer/constraint Field(...) emission, and DataBinding/FunctionCall union splitting.
Implementation details
  • Builder runtime (python/a2ui_agent/src/a2ui/builder/core/):
    • flattener.py & id_allocator.py: Scopes multi-root sequences (root_id=None) as root_0, root_1, … within one shared FlattenContext. Detects duplicate explicit sibling IDs and ComponentRef collisions during Pass 1 and records fatal errors on FlattenContext.error so Pydantic v2 PlainSerializer inside Union[Sequence[Child], DynamicChildList] cannot swallow A2uiValidationError. Accepts reserved_ids: AbstractSet[str] | None.
    • tree.py: Adds preserve_ids: bool = False, dangling_components: Sequence[ComponentBuilderNode] = (), and catalog_id: str | None = None to ComponentTree.
    • base_model.py: Adds _preserve_required_none on BuilderBaseModel to keep required nullable fields set to None as explicit JSON null while excluding unset/optional None fields.
    • v0_9/models.py: Adds explicit __all__.
  • Macro expander (python/a2ui_agent/src/a2ui/transformers/macros/):
    • Passes sibling wire component IDs via reserved_ids into flatten_component_tree so auto-allocated macro subcomponents never overwrite sibling components on the same surface.
  • Dart CLI codegen (dart/a2ui_cli/):
    • catalog_analyzer.dart & types.dart: Distinguishes PrimitiveKind.integer from float, reads minimum/maximum/minItems/maxItems, merges allOf property schemas (catching DateTimeInput.min/max -> DynamicString), splits DataBinding and FunctionCall refs cleanly (fixing Icon.name), preserves numeric/boolean enums and required nullable fields (fix(cli): preserve Python enum types and nullable fields #4189, fix(python): preserve required null fields in builder serialization #4190).
    • python_emitter.dart & type_mapper.dart: Emits CATALOG_ID, CATALOG_COMPONENTS, complete runtime imports, Field(ge=..., min_length=...) constraints, strict Dynamic* aliases, and __all__.
    • Regenerated python/a2ui_agent/src/a2ui/builder/v0_9/catalogs/basic.py, v1_0/catalogs/basic.py, and 4 Dart CLI fixture goldens; fixed broken event import in test_pydantic_builders.py.
Verification — dart format, dart analyze --fatal-infos, 114 Dart tests, pyink, mypy (0 errors), and 355 Python tests passed
  • cd dart/a2ui_cli && dart format --output=none --set-exit-if-changed lib/ test/ && dart analyze --fatal-infos && dart test: 0 analyzer issues, 114 passed
  • uv run pyink --check & uv run mypy .: 0 errors across 245 source files
  • uv run pytest python/a2ui_agent/tests/test_pydantic_builders.py python/a2ui_agent/tests/test_pydantic_builders_v1_0.py python/a2ui_agent/tests/test_macros.py: 355 passed

@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 enhances the A2UI code generator and Python runtime by adding support for schema constraints (such as minimum/maximum values and item counts), introducing strict Dynamic* type aliases, preserving required nullable fields as JSON null, and resolving component ID collisions during flattening and macro expansion. The code review feedback focuses on optimizing the Dart analyzer and Python emitter code by leveraging Dart's local variable type promotion to eliminate redundant map lookups and explicit type casts.

Comment on lines +176 to +187
final num? minimum = schema['minimum'] is num
? schema['minimum'] as num
: null;
final num? maximum = schema['maximum'] is num
? schema['maximum'] as num
: null;
final int? minItems = schema['minItems'] is int
? schema['minItems'] as int
: null;
final int? maxItems = schema['maxItems'] is int
? schema['maxItems'] as int
: null;

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.

medium

By assigning the schema values to local variables, we can avoid redundant map lookups and leverage Dart's type promotion to eliminate the explicit as num and as int casts.

Suggested change
final num? minimum = schema['minimum'] is num
? schema['minimum'] as num
: null;
final num? maximum = schema['maximum'] is num
? schema['maximum'] as num
: null;
final int? minItems = schema['minItems'] is int
? schema['minItems'] as int
: null;
final int? maxItems = schema['maxItems'] is int
? schema['maxItems'] as int
: null;
final minimumVal = schema['minimum'];
final num? minimum = minimumVal is num ? minimumVal : null;
final maximumVal = schema['maximum'];
final num? maximum = maximumVal is num ? maximumVal : null;
final minItemsVal = schema['minItems'];
final int? minItems = minItemsVal is int ? minItemsVal : null;
final maxItemsVal = schema['maxItems'];
final int? maxItems = maxItemsVal is int ? maxItemsVal : null;
References
  1. Avoid unnecessary type casting when accessing properties that can be strictly typed via local variable type promotion.

Comment on lines +328 to +330
final bool isAny =
resolved.type is PrimitiveType &&
(resolved.type as PrimitiveType).primitive == PrimitiveKind.any;

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.

medium

Assigning resolved.type to a local variable allows Dart's type promotion to automatically type-promote it to PrimitiveType after the is PrimitiveType check, eliminating the need for the explicit as PrimitiveType cast.

Suggested change
final bool isAny =
resolved.type is PrimitiveType &&
(resolved.type as PrimitiveType).primitive == PrimitiveKind.any;
final resolvedType = resolved.type;
final bool isAny = resolvedType is PrimitiveType &&
resolvedType.primitive == PrimitiveKind.any;
References
  1. Access properties directly without type casting if they are already strictly typed via getters on the underlying class.

Comment on lines 349 to +352
if (schema['enum'] is List) {
final List<String> values = (schema['enum'] as List)
.map((e) => e.toString())
.toList();
var preferred = '$parentName${capitalize(propName)}';
if ((parentName == 'Row' || parentName == 'Column') &&
(propName == 'justify' || propName == 'align')) {
preferred = 'Flex${capitalize(propName)}';
}
final rawValues = schema['enum'] as List;
final bool hasNull = rawValues.any((e) => e == null);
final List<Object> values = rawValues.whereType<Object>().toList();

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.

medium

Assigning schema['enum'] to a local variable avoids redundant map lookups and allows Dart's type promotion to automatically promote it to List after the is List check, eliminating the need for the explicit as List cast.

Suggested change
if (schema['enum'] is List) {
final List<String> values = (schema['enum'] as List)
.map((e) => e.toString())
.toList();
var preferred = '$parentName${capitalize(propName)}';
if ((parentName == 'Row' || parentName == 'Column') &&
(propName == 'justify' || propName == 'align')) {
preferred = 'Flex${capitalize(propName)}';
}
final rawValues = schema['enum'] as List;
final bool hasNull = rawValues.any((e) => e == null);
final List<Object> values = rawValues.whereType<Object>().toList();
final enumVal = schema['enum'];
if (enumVal is List) {
final bool hasNull = enumVal.any((e) => e == null);
final List<Object> values = enumVal.whereType<Object>().toList();
References
  1. Avoid unnecessary type casting when accessing properties that can be strictly typed via local variable type promotion.

Comment on lines +467 to +470
final bool isNumericPrimitive =
prop.type is PrimitiveType &&
((prop.type as PrimitiveType).primitive == PrimitiveKind.integer ||
(prop.type as PrimitiveType).primitive == PrimitiveKind.float);

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.

medium

Assigning prop.type to a local variable allows Dart's type promotion to automatically type-promote it to PrimitiveType after the is PrimitiveType check, eliminating the need for the explicit as PrimitiveType casts and redundant property accesses.

    final propType = prop.type;
    final bool isNumericPrimitive = propType is PrimitiveType &&
        (propType.primitive == PrimitiveKind.integer ||
            propType.primitive == PrimitiveKind.float);
References
  1. Access properties directly without type casting if they are already strictly typed via getters on the underlying class.

@jacobsimionato jacobsimionato changed the title fix(python/builder,cli): fix ID collisions, CLI schema parity, and round-trip guardrails fix(python/builder,cli): fix ID collisions and CLI schema parity Dec 2, 2026
@jacobsimionato
jacobsimionato removed this pull request from stack #4536 December 2, 2026 23:18
@jacobsimionato
jacobsimionato removed this pull request from stack #4552 December 3, 2026 12:03
@jacobsimionato
jacobsimionato merged commit 69fae65 into main Dec 3, 2026
@jacobsimionato
jacobsimionato force-pushed the macros/2-checks-a11y-params branch from 1038deb to 6dd00f1 Compare December 3, 2026 12:04
@jacobsimionato
jacobsimionato changed the base branch from macros/2-checks-a11y-params to main December 3, 2026 12:04
@jacobsimionato
jacobsimionato force-pushed the macros/3-builder-ids-and-cli branch from 4c524d7 to 69fae65 Compare December 3, 2026 12:04
@jacobsimionato
jacobsimionato deleted the macros/3-builder-ids-and-cli branch December 3, 2026 12:04
@jacobsimionato

Copy link
Copy Markdown
Collaborator Author

GitHub marked this PR as merged when I reordered the stack: its commit became reachable from the old base branch. Nothing landed on main. The change continues in #4564, part of the reordered macros stack (https://github.com/a2ui-project/a2ui/stack/4568).

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