Repository navigation
feat(python/macros)!: async MacroExpander with parallel expansion (#4455) - #4562
jacobsimionato wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
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+.
| 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) |
There was a problem hiding this comment.
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.
| 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) |
| try: | ||
| await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) |
There was a problem hiding this comment.
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.
| try: | |
| await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) | |
| try: | |
| await asyncio.wait(set(tasks), return_when=asyncio.FIRST_EXCEPTION) |
📖 Docs Site Preview DeployedPreview URL: https://a2ui.org/pr-preview/pr-4562/ Modified pages in this PR: Built from commit |
…ansion (#4455) Signed-off-by: Jacob Simionato <jsimionato@google.com>
f60661d to
d361349
Compare
Problem
Macros are Python functions decorated with
@macrothat 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
@macroacceptsasync deffunctions, callable objects with a custom__call__(including__slots__classes), bound methods, andfunctools.partialwrappers. Keywords bound bypartialare left out of the model-facing JSON Schema and rejected if model output tries to pass them.transform_to_transportorexpand_macroexpands 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.async defmacros 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.transform_to_transporttakes an optional keyword-onlymax_concurrencythat caps concurrent macro calls for that call.expand_macrohas no cap, andtransform_to_inferenceis a pass-through that runs no macros.on_error="raise"(the default), and also under"passthrough"for recursion-depth, protocol, and catalog errors. Caller cancellation always propagates.Breaking changes and migration
MacroExpander.transform_to_transport,transform_to_inference, andexpand_macroare nowasync def, with no synchronous path. Callers mustawaitthem. Sync callers (scripts, tests) can wrap the call inasyncio.run(...), astests/conformance/macro_suite.pynow does. The experimentalToolPointerBinder, the community macros sample, and the docs are updated.Code that reached into
expander.processor.expand(...)(the private_MacroProcessor) now gets a coroutine. Use the publicawait expander.expand_macro(...)instead, as the community macros sample now does.API changes
max_concurrencymust beNoneor anint >= 1. Anything else, including aboolor afloat, raisesValueError, like an invalidon_errorvalue does.Where to review
Start here:
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.python/a2ui_agent/src/a2ui/transformers/macros/processor.py: the split ofexpandintoinvoke(user code and I/O, no ID allocation) andflatten_result(ID allocation).python/a2ui_agent/src/a2ui/transformers/macros/macro.py: callable unwrapping,partialkeyword filtering, and the wrapper fallback.python/a2ui_agent/tests/test_macros.py: the newtest_async_*tests.Implementation details
_MacroProcessor.invokecoerces arguments, calls the macro, awaits the result ifinspect.isawaitable(result), and validates the returned builder tree. Synchronous macros run inline on the event loop with no thread offloading._MacroProcessor.expandstays as an async wrapper overinvokeplusflatten_result.invokeruns concurrently.flatten_resultruns afterwards in input slot order, adding each sibling's emitted IDs toknown_idsso later siblings never collide, regardless of completion order._expand_component_list_slotsatdepth + 1, so nested siblings under different parents also run concurrently.asyncio.create_tasktasks awaited withasyncio.wait(..., return_when=FIRST_EXCEPTION). Tasks copy the caller'scontextvars.Context, so request-scopedContextVarvalues are visible inside macros.max_concurrency=1cannot deadlock on nested macros. Anabortedflag stops siblings still queued on the semaphore from starting after a failure or cancellation._cancel_and_draincancels unfinished siblings once, waits for their cleanup withasyncio.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 nestedfunctools.partiallayers (including apartialmethodassigned to__call__) to find type hints, docstrings, and the default name._get_callable_object_docreads 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_targetina2ui_agent_experimentalis nowasync def; both callers were already async.Verification
Measured at the stack tip (all 11 PRs applied):
This PR adds the
test_async_*tests andtest_callable_object_docstrings_and_wrapped_async_signature_compositiontopython/a2ui_agent/tests/test_macros.py. It converts existing expander tests there and intest_macro_lowering.py,test_decision_kernel.py,test_external_extension_smoke.py, andsamples/community/macros/test_server.pyto@pytest.mark.asyncio.