Skip to content

feat(python/macros)!: async MacroExpander with parallel expansion (#4455) - #4562

Open
jacobsimionato wants to merge 1 commit into
macros/2-checks-a11y-paramsfrom
macros/5c-async-parallel-macros
Open

jacobsimionato wants to merge 1 commit into
macros/2-checks-a11y-paramsfrom
macros/5c-async-parallel-macros

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Macros are Python functions decorated with @macro that the server expands into standard A2UI components before sending them to the client. Until now every macro ran synchronously and one after another. A macro that needs server-side I/O (live pricing, inventory, media URLs, database records) either blocked the event loop in an async server such as FastAPI or an ADK/A2A handler, or needed a separate pre-fetch step outside the macro layer. A list of N such cards also cost N sequential round trips.

Fixes #4455
Replaces #4456 (closed).

Stack: 7/11 (overview) · previous: #4529 · next: #4533

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

Summary

  1. @macro accepts async def functions, callable objects with a custom __call__ (including __slots__ classes), bound methods, and functools.partial wrappers. Keywords bound by partial are left out of the model-facing JSON Schema and rejected if model output tries to pass them.
  2. When transform_to_transport or expand_macro expands a list of components, sibling macros run concurrently, including nested macros. Output order and generated component IDs match sequential expansion. Separate messages in one call are still processed in order.
  3. Only async def macros that await I/O overlap. Sync macros still run inline on the event loop, so they gain no parallelism, and a blocking sync macro still blocks the loop.
  4. transform_to_transport takes an optional keyword-only max_concurrency that caps concurrent macro calls for that call. expand_macro has no cap, and transform_to_inference is a pass-through that runs no macros.
  5. If one sibling raises and the error propagates, the other running siblings are cancelled and their cleanup finishes before the error is re-raised. Errors propagate under on_error="raise" (the default), and also under "passthrough" for recursion-depth, protocol, and catalog errors. Caller cancellation always propagates.

Breaking changes and migration

  1. MacroExpander.transform_to_transport, transform_to_inference, and expand_macro are now async def, with no synchronous path. Callers must await them. Sync callers (scripts, tests) can wrap the call in asyncio.run(...), as tests/conformance/macro_suite.py now does. The experimental ToolPointerBinder, the community macros sample, and the docs are updated.

    # Before
    transport_messages = expander.transform_to_transport(messages)
    # After
    transport_messages = await expander.transform_to_transport(messages)
  2. Code that reached into expander.processor.expand(...) (the private _MacroProcessor) now gets a coroutine. Use the public await expander.expand_macro(...) instead, as the community macros sample now does.

API changes

from a2ui.builder.v1_0 import Card, Text
from a2ui.transformers.macros import MacroExpander, macro

@macro
async def ArtistBadge(artist_name: str) -> Card:
    """Hydrates an artist name into a card."""
    profile = await lookup_artist(artist_name)  # your async I/O
    return Card(child=Text(text=f"{profile.name} ({profile.era})"))

# Inside an async function:
expander = MacroExpander([ArtistBadge])
transport_messages = await expander.transform_to_transport(
    messages, max_concurrency=8  # optional; None (default) means no cap
)

max_concurrency must be None or an int >= 1. Anything else, including a bool or a float, raises ValueError, like an invalid on_error value does.

Where to review

Category Files Diff (+/-)
Production (SDK, binder, sample) 6 +446 / -98
Tests 6 +1252 / -147
Docs and changelog 4 +39 / -9
Total 16 +1737 / -254

Start here:

  1. python/a2ui_agent/src/a2ui/transformers/macros/expander.py, _expand_component_list_slots: runs sibling macros concurrently, then assigns IDs in input order, then expands nested macros. Also check the path that cancels siblings after a failure.
  2. python/a2ui_agent/src/a2ui/transformers/macros/processor.py: the split of expand into invoke (user code and I/O, no ID allocation) and flatten_result (ID allocation).
  3. python/a2ui_agent/src/a2ui/transformers/macros/macro.py: callable unwrapping, partial keyword filtering, and the wrapper fallback.
  4. python/a2ui_agent/tests/test_macros.py: the new test_async_* tests.
Implementation details
  • _MacroProcessor.invoke coerces arguments, calls the macro, awaits the result if inspect.isawaitable(result), and validates the returned builder tree. Synchronous macros run inline on the event loop with no thread offloading. _MacroProcessor.expand stays as an async wrapper over invoke plus flatten_result.
  • IDs stay deterministic because only invoke runs concurrently. flatten_result runs afterwards in input slot order, adding each sibling's emitted IDs to known_ids so later siblings never collide, regardless of completion order.
  • Nested macros are expanded level by level: all components emitted at one level are collected into a single list and passed back to _expand_component_list_slots at depth + 1, so nested siblings under different parents also run concurrently.
  • A single pending macro skips task creation. With two or more, siblings run as asyncio.create_task tasks awaited with asyncio.wait(..., return_when=FIRST_EXCEPTION). Tasks copy the caller's contextvars.Context, so request-scoped ContextVar values are visible inside macros.
  • The semaphore wraps only the macro call, not the nested expansion, so max_concurrency=1 cannot deadlock on nested macros. An aborted flag stops siblings still queued on the semaphore from starting after a failure or cancellation.
  • _cancel_and_drain cancels unfinished siblings once, waits for their cleanup with asyncio.wait (which never cancels its own tasks), forwards one further caller cancellation if it arrives mid-drain, and marks sibling exceptions as retrieved.
  • macro() unwraps nested functools.partial layers (including a partialmethod assigned to __call__) to find type hints, docstrings, and the default name. _get_callable_object_doc reads the docstring of a custom __call__ or its class, avoiding Python's generic "Call self as a function." text.
  • macro() returns a thin sync or async wrapper (with a filtered __signature__ and __annotations__) when keywords are bound, when the target is already a macro, or when setting __a2ui_macro__ fails (for example on __slots__ objects or bound methods).
  • ToolPointerBinder._finalize_target in a2ui_agent_experimental is now async def; both callers were already async.
Verification

Measured at the stack tip (all 11 PRs applied):

  1. Full Python suite passes (6027 passed).
  2. mypy is clean (283 source files).
  3. 56 conformance goldens are valid.
  4. Prettier and pyink are clean on every commit, and every commit has a DCO sign-off.

This PR adds the test_async_* tests and test_callable_object_docstrings_and_wrapped_async_signature_composition to python/a2ui_agent/tests/test_macros.py. It converts existing expander tests there and in test_macro_lowering.py, test_decision_kernel.py, test_external_extension_smoke.py, and samples/community/macros/test_server.py to @pytest.mark.asyncio.

@jacobsimionato
jacobsimionato removed this pull request from stack #4563 December 3, 2026 12:06

@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 transitions MacroExpander.transform_to_transport, transform_to_inference, and expand_macro to be asynchronous (async def), enabling parallel sibling macro expansion, optional concurrency throttling, and sibling cancellation on failure. The review comments correctly identify two critical runtime issues in expander.py where asyncio.wait is passed a list instead of a set, which will raise a TypeError in Python 3.11+.

Comment on lines +1061 to +1065
while not_done := [task for task in tasks if not task.done()]:
try:
# ``asyncio.wait`` never cancels its tasks, so siblings see one
# cancellation per cancel request (like ``asyncio.TaskGroup``).
await asyncio.wait(not_done)

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

In Python 3.11+, asyncio.wait strictly requires a set of tasks/futures and no longer accepts a list (doing so raises a TypeError). Since not_done is currently constructed as a list, this will crash at runtime on Python 3.11+. We should use a set comprehension instead.

Suggested change
while not_done := [task for task in tasks if not task.done()]:
try:
# ``asyncio.wait`` never cancels its tasks, so siblings see one
# cancellation per cancel request (like ``asyncio.TaskGroup``).
await asyncio.wait(not_done)
while not_done := {task for task in tasks if not task.done()}:
try:
# asyncio.wait never cancels its tasks, so siblings see one
# cancellation per cancel request (like asyncio.TaskGroup).
await asyncio.wait(not_done)

Comment on lines +1087 to +1088
try:
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)

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

In Python 3.11+, asyncio.wait strictly requires a set of tasks/futures and will raise a TypeError if passed a list. Since we need tasks to remain a list to preserve the input order for outcomes, we should wrap tasks in set() when calling asyncio.wait.

Suggested change
try:
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
try:
await asyncio.wait(set(tasks), return_when=asyncio.FIRST_EXCEPTION)

github-actions Bot added a commit that referenced this pull request Dec 3, 2026
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

📖 Docs Site Preview Deployed

Preview URL: https://a2ui.org/pr-preview/pr-4562/

Modified pages in this PR:

Built from commit f60661d · Workflow run · GitHub Pages may take ~30–60s to propagate updates. This preview is removed automatically when the PR closes.

github-actions Bot added a commit that referenced this pull request Dec 3, 2026
@jacobsimionato jacobsimionato changed the title feat(python/macros)!: make MacroExpander async-only with parallel expansion (#4455) feat(python/macros)!: async MacroExpander with parallel expansion (#4455) Dec 3, 2026
…ansion (#4455)

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/5c-async-parallel-macros branch from f60661d to d361349 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.

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

1 participant