Repository navigation
feat(python): add async and parallel macro expansion (#4455) - #4456
jacobsimionato wants to merge 8 commits into
Conversation
Signed-off-by: Jacob Simionato <jsimionato@google.com>
Signed-off-by: Jacob Simionato <jsimionato@google.com>
There was a problem hiding this comment.
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/CHANGELOG.md
…-macros # Conflicts: # python/a2ui_agent/CHANGELOG.md
…-macros # Conflicts: # python/a2ui_agent/src/a2ui/transformers/macros/expander.py # python/a2ui_agent/src/a2ui/transformers/macros/macro.py
|
This change is now folded into the macros stack (https://github.com/a2ui-project/a2ui/stack/4568) as #4562, which keeps the async-only |
Problem
Macros in
a2ui-agent-sdklet a language model emit a compact domain component while the server lowers it into standard A2UI primitives before transport. Until now,MacroExpander.transform_to_transportexecuted 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 deffunctions with@macroand lower outbound messages withawait expander.atransform_to_transport(...):Key runtime behaviors for developers:
messagesrun sequentially socreateSurfaceanddeleteSurfaceupdates apply before subsequentupdateComponentspayloads. Within each component list, sibling macro invocations run concurrently and produce the exact same component ordering and generated IDs astransform_to_transport.max_concurrencybounds concurrent macro invocations per call. The semaphore wraps only the macro invocation itself and releases before recursively expanding nested macros, somax_concurrency=1does not deadlock on nested async macros.MacroExpander. Synchronous macros run inline on the event loop without thread offloading.asyncio.create_taskpreserves the caller'scontextvars.Context, so request-scoped dependency injection withContextVarworks without adding extra parameters to macro signatures.on_error="raise"(or on structural errors such asA2uiRecursionErrororA2uiCatalogError), a failing sibling cancels and drains in-flight sibling tasks before propagating the error. Externalasyncio.CancelledErroralways propagates, even underon_error="passthrough"or when cancellation arrives while draining a sibling failure.transform_to_transportalways raisesA2uiValidationErrorpointing toatransform_to_transport(regardless ofon_error) and closes or cancels any returned coroutine orasyncio.Futureto 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 ina2ui.transformers.macros(still["MacroExpander", "macro"]):MacroExpander.atransform_to_transport:max_concurrencymust beNoneor anint >= 1(booland non-integers such asfloatraiseValueError).@macro(signature unchanged) to supportasync deffunctions, callable objects withasync def __call__(including__slots__classes and bound methods), andfunctools.partialwrappers. Added__all__ = ["macro"]tomacro.py.MacroExpander.transform_to_transport: surface lifecycle updates are now staged locally and committed atomically only if the call succeeds, and encountering an async macro raisesA2uiValidationErrorregardless ofon_error._MacroProcessor._aexpand,_ExpansionContext,_ResolvedInvocation,_PreparedMessageBody) is underscore-prefixed and stays private.Key implementation changes
macro.py: Addedis_asyncto_MacroMetadata; unwrappedfunctools.partiallayers and callable objects (__call__) for type hints,inspect.getdocdocstring resolution, and default naming; excludedpartial.keywordsfrom model-facing schemas and rejected runtime overrides; added a wrapper fallback whensetattrfails on__slots__objects or bound methods.processor.py: Splitexpandinto shared_prepare_invocationand_finalize_result, added_aexpand, checkedmeta.is_asyncbefore argument coercion in synchronousexpand, and closed/cancelled any returned coroutine orasyncio.Futurebefore raising_MacroProtocolError.expander.py: Introduced_ExpansionContext,_ResolvedInvocation,_begin_transform,_prepare_message,_assemble_message,_resolve_macro_invocation, and_handle_expansion_errorto share validation, surface staging, envelope merging, error policy, and catalog stamping between sync and async paths. Addedatransform_to_transportand_aexpand_component_listwith a single-macro fast path, optional per-call semaphore, and cancellation-resilient task draining. Skippedmodel_validateon untouched messages and avoided applying instance surface eviction limits to caller-ownedsurface_catalogs.README.mdandCHANGELOG.md: Documented async macro usage, per-callmax_concurrency, inline sync execution, fail-loud guard, and atomic lifecycle commits.test_macros.py: Added@pytest.mark.asynciotests for concurrent execution, completion-order ID determinism,max_concurrencybounds and validation, nested non-deadlock atmax_concurrency=1, sibling cancellation and external cancellation during drain, sync-on-async fail-loud without coroutine/Future leaks,partialbound-kwarg isolation,__slots__/bound-method callables,ContextVarpropagation, 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
uv run pytest python/a2ui_agent/tests/test_macros.py: 35 passed, 0 failed.uv run pytest python/a2ui_agent/tests: 2,799 passed, 330 skipped, 10 deselected, 0 failed.uv run mypy python/a2ui_agent/src/a2ui/transformers/macros/: 0 issues across 4 source files.uv run pyink python/a2ui_agent/src/a2ui/transformers/macros/ python/a2ui_agent/tests/test_macros.py: clean.gh pr checks 4456): 39 passed, 0 failing, 16 skipped.Closes #4455