Skip to content

feat(python): add async and parallel macro expansion (#4455) - #4456

Closed
jacobsimionato wants to merge 8 commits into
a2ui-project:mainfrom
jacobsimionato:feat/async-parallel-macros
Closed

jacobsimionato wants to merge 8 commits into
a2ui-project:mainfrom
jacobsimionato:feat/async-parallel-macros

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Macros in a2ui-agent-sdk let a language model emit a compact domain component while the server lowers it into standard A2UI primitives before transport. Until now, MacroExpander.transform_to_transport executed macros synchronously and sequentially.

When a macro needs to hydrate an identifier with server-side I/O (such as fetching live pricing, inventory, media URLs, or database records), developers had two awkward choices: block the event loop in an async server (FastAPI, Starlette, async ADK/A2A handlers), or build a separate pre-fetching step outside the macro layer. Even then, expanding a list of N hydrating cards sequentially turned one network round-trip into N sequential round-trips.

Developer usage

Developers can now write async def functions with @macro and lower outbound messages with await expander.atransform_to_transport(...):

import functools

from a2ui.builder.v1_0 import Card, Column, Text
from a2ui.core.basic_catalog import BasicCatalog
from a2ui.transformers.macros import MacroExpander, macro


@macro
def SectionHeading(title: str) -> Text:
    """Synchronous macros can be registered alongside async macros."""
    return Text(text=title, variant="h2")


@macro
async def ProductCard(item_id: str) -> Card:
    """Hydrates a product ID into a card asynchronously."""
    record = await catalog_client.fetch_item(item_id)
    return Card(
        child=Column(
            children=[
                Text(text=record["title"], variant="body"),
                Text(text=record["price"], variant="caption"),
            ]
        )
    )


# Dependencies can also be injected via functools.partial or callable objects.
# Bound keyword arguments (here `client`) are omitted from the LLM JSON Schema
# and rejected if model output attempts to pass them.
async def _fetch_badge(artist_id: str, *, client: ArtistClient) -> Card:
    profile = await client.lookup(artist_id)
    return Card(child=Text(text=f"{profile.name} ({profile.era})"))


ArtistBadge = macro(functools.partial(_fetch_badge, client=artist_client))

basic = BasicCatalog("1.0")
expander = MacroExpander(
    [SectionHeading, ProductCard, ArtistBadge],
    base_catalogs=[basic],
    on_error="raise",
)

# Envelopes run in order; sibling macros within each message run concurrently
# and reassemble in input order with the same IDs as synchronous expansion.
transport_messages = await expander.atransform_to_transport(
    messages,
    surface_catalogs={"shop": basic.catalog_id},  # pass per call when sharing one expander
    max_concurrency=8,  # optional per-call cap on concurrent macro invocations
)

Key runtime behaviors for developers:

  1. Envelopes in messages run sequentially so createSurface and deleteSurface updates apply before subsequent updateComponents payloads. Within each component list, sibling macro invocations run concurrently and produce the exact same component ordering and generated IDs as transform_to_transport.
  2. max_concurrency bounds concurrent macro invocations per call. The semaphore wraps only the macro invocation itself and releases before recursively expanding nested macros, so max_concurrency=1 does not deadlock on nested async macros.
  3. Synchronous and async macros can be mixed in the same MacroExpander. Synchronous macros run inline on the event loop without thread offloading.
  4. asyncio.create_task preserves the caller's contextvars.Context, so request-scoped dependency injection with ContextVar works without adding extra parameters to macro signatures.
  5. Under on_error="raise" (or on structural errors such as A2uiRecursionError or A2uiCatalogError), a failing sibling cancels and drains in-flight sibling tasks before propagating the error. External asyncio.CancelledError always propagates, even under on_error="passthrough" or when cancellation arrives while draining a sibling failure.
  6. Passing an async macro to synchronous transform_to_transport always raises A2uiValidationError pointing to atransform_to_transport (regardless of on_error) and closes or cancels any returned coroutine or asyncio.Future to prevent unawaited-coroutine warnings.

Public API changes

The public API expansion is limited to one new method on MacroExpander, with no new top-level exports in a2ui.transformers.macros (still ["MacroExpander", "macro"]):

  1. Added MacroExpander.atransform_to_transport:
    async def atransform_to_transport(
        self,
        messages: Sequence[AgentToRendererMessage],
        *,
        surface_catalogs: Mapping[str, str | None] | None = None,
        max_concurrency: int | None = None,
    ) -> list[AgentToRendererMessage]:
    max_concurrency must be None or an int >= 1 (bool and non-integers such as float raise ValueError).
  2. Broadened accepted callables on existing @macro (signature unchanged) to support async def functions, callable objects with async def __call__ (including __slots__ classes and bound methods), and functools.partial wrappers. Added __all__ = ["macro"] to macro.py.
  3. Tightened behavior on existing MacroExpander.transform_to_transport: surface lifecycle updates are now staged locally and committed atomically only if the call succeeds, and encountering an async macro raises A2uiValidationError regardless of on_error.
  4. All new internal machinery (_MacroProcessor._aexpand, _ExpansionContext, _ResolvedInvocation, _PreparedMessageBody) is underscore-prefixed and stays private.

Key implementation changes

  1. macro.py: Added is_async to _MacroMetadata; unwrapped functools.partial layers and callable objects (__call__) for type hints, inspect.getdoc docstring resolution, and default naming; excluded partial.keywords from model-facing schemas and rejected runtime overrides; added a wrapper fallback when setattr fails on __slots__ objects or bound methods.
  2. processor.py: Split expand into shared _prepare_invocation and _finalize_result, added _aexpand, checked meta.is_async before argument coercion in synchronous expand, and closed/cancelled any returned coroutine or asyncio.Future before raising _MacroProtocolError.
  3. expander.py: Introduced _ExpansionContext, _ResolvedInvocation, _begin_transform, _prepare_message, _assemble_message, _resolve_macro_invocation, and _handle_expansion_error to share validation, surface staging, envelope merging, error policy, and catalog stamping between sync and async paths. Added atransform_to_transport and _aexpand_component_list with a single-macro fast path, optional per-call semaphore, and cancellation-resilient task draining. Skipped model_validate on untouched messages and avoided applying instance surface eviction limits to caller-owned surface_catalogs.
  4. README.md and CHANGELOG.md: Documented async macro usage, per-call max_concurrency, inline sync execution, fail-loud guard, and atomic lifecycle commits.
  5. test_macros.py: Added @pytest.mark.asyncio tests for concurrent execution, completion-order ID determinism, max_concurrency bounds and validation, nested non-deadlock at max_concurrency=1, sibling cancellation and external cancellation during drain, sync-on-async fail-loud without coroutine/Future leaks, partial bound-kwarg isolation, __slots__/bound-method callables, ContextVar propagation, async recursion cycle limits without re-wrapping, atomic sync/async surface lifecycle rollback, and v0.9/v1.0/Express end-to-end lowering.

Verification and testing

  1. uv run pytest python/a2ui_agent/tests/test_macros.py: 35 passed, 0 failed.
  2. uv run pytest python/a2ui_agent/tests: 2,799 passed, 330 skipped, 10 deselected, 0 failed.
  3. uv run mypy python/a2ui_agent/src/a2ui/transformers/macros/: 0 issues across 4 source files.
  4. uv run pyink python/a2ui_agent/src/a2ui/transformers/macros/ python/a2ui_agent/tests/test_macros.py: clean.
  5. GitHub CI (gh pr checks 4456): 39 passed, 0 failing, 16 skipped.

Closes #4455

Signed-off-by: Jacob Simionato <jsimionato@google.com>
Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato jacobsimionato added type: feature/enhancement component: agent sdk Relating to the agent SDK libraries in any language feature: macros Affects the Macros or Typesafe Builder API features lang: python Affects SDKs or apps in the Python programming language inference-latency labels Nov 30, 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 introduces asynchronous and parallel macro expansion capabilities to the MacroExpander class, allowing async def macros to be expanded concurrently via a new atransform_to_transport method. The implementation includes shared message preparation refactoring, async-specific expansion logic, and comprehensive test coverage. Feedback on the changes suggests improving error handling by preventing redundant wrapping of A2uiRecursionError during recursive unwinding, and tightening the validation of max_concurrency to explicitly verify it is an integer rather than allowing floats to bypass the check.

…-macros

# Conflicts:
#	python/a2ui_agent/src/a2ui/transformers/macros/expander.py
#	python/a2ui_agent/src/a2ui/transformers/macros/macro.py
@jacobsimionato

Copy link
Copy Markdown
Collaborator Author

This change is now folded into the macros stack (https://github.com/a2ui-project/a2ui/stack/4568) as #4562, which keeps the async-only MacroExpander with parallel expansion. The changes from review: Phase 1 now uses asyncio.wait(FIRST_EXCEPTION) with cancel-and-drain, so a sibling failure or an outer cancellation stops queued work cleanly, and the downstream pipeline and ADK/A2A integration are built on it. Closing this in favor of #4562.

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

Labels

component: agent sdk Relating to the agent SDK libraries in any language feature: macros Affects the Macros or Typesafe Builder API features inference-latency lang: python Affects SDKs or apps in the Python programming language type: feature/enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(python): support async @macro functions and parallel expansion in MacroExpander

1 participant