Skip to content

feat(python/builder,cli): enforce FunctionCall return types (#3607) - #4565

Open
jacobsimionato wants to merge 1 commit into
macros/3-builder-ids-and-cli-v2from
macros/4-typed-function-calls-v2
Open

jacobsimionato wants to merge 1 commit into
macros/3-builder-ids-and-cli-v2from
macros/4-typed-function-calls-v2

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Builders are the typed Python component classes that dart/a2ui_cli generates from a catalog. Each catalog function (such as FormatString, Required, or OpenUrl) became a plain FunctionCall subclass with no return type. So Text(text=OpenUrl(...)), which puts a side-effect action where a string belongs, passed both mypy and Pydantic validation. The mistake only showed up on the client renderer.

Closes #3607

Stack: 2/11 (overview) · previous: #4564 · next: #4566

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

Replaces #4531 (GitHub marked it merged during a stack reorder; nothing landed on main).

Summary

Terms: Dynamic* types (DynamicString, DynamicBoolean, DynamicValue, and so on) are the builder property types that accept a literal, a data binding, or a function call. Core models live in a2ui.core.schema; builder models in a2ui.builder.v0_9 and v1_0 wrap them for authoring.

  1. Add return-typed FunctionCall subclasses to both builder packages:
    • StringFunctionCall, NumberFunctionCall, BooleanFunctionCall, ArrayFunctionCall, ObjectFunctionCall: fit only the matching Dynamic* slot.
    • ValidationResultFunctionCall (v1.0 only; v0.9 has no such return type, so the CLI uses BooleanFunctionCall there): fits boolean slots and CheckRule.condition.
    • VoidFunctionCall: side-effect calls; valid only as Action(function_call=...).
    • AnyFunctionCall: explicit opt-out for functions whose catalog return type is any; fits any slot, like an untyped call.
  2. Narrow the Dynamic* types, CheckRule.condition, AccessibilityAttributes, and ActionEvent so mypy and Pydantic both reject a call with the wrong return type. Untyped FunctionCall(...) without an explicit returnType is still accepted in every slot.
  3. Validate the arguments of typed calls at runtime against their __init__ annotations, so a mismatch nested inside another call's arguments is also caught.
  4. Make dart/a2ui_cli pick each generated function's base class from the catalog returnType, and regenerate the v0.9 and v1.0 basic catalogs.
  5. Make builder CheckRule, AccessibilityAttributes, and ActionEvent subclasses of the core models (see breaking change 2), and let macros (Python functions that expand into A2UI components on the server) accept both versions.

Breaking changes and migration

  1. Code that passed a function call with the wrong return type now fails mypy and raises ValidationError at construction. Valid code is unaffected.
  2. CheckRule, AccessibilityAttributes, and ActionEvent in the builder packages were re-exports of the core classes and are now subclasses. isinstance(builder_obj, core.CheckRule) still passes and core instances are still accepted as field values. But builder.CheckRule is core.CheckRule is now False, and so is isinstance(core_obj, builder.CheckRule). Serialized JSON is unchanged.

New public API

from typing import Any

from a2ui.builder import v1_0 as b

b.Text(text=b.FormatString(value="Hello"))  # FormatString is a StringFunctionCall
b.CheckRule(condition=b.Required(value="x"), message="Required")
b.Action(function_call=b.OpenUrl(url="https://example.com"))  # VoidFunctionCall
# b.Text(text=b.OpenUrl(url="https://example.com"))  -> mypy error and ValidationError


class Upper(b.StringFunctionCall):  # custom function with a declared return type
    def __init__(self, *, value: b.DynamicString, **kwargs: Any):  # kwargs: e.g. catalog_id
        super().__init__(call="upper", args={"value": value}, **kwargs)

b.Text(text=Upper(value="x"))

Where to review

Category Files Diff (+/-)
Production (Python builders, macros, CLI) 9 +757 / -33
Generated (basic catalogs, CLI golden files) 6 +114 / -28
Tests 3 +502 / -9
Docs and changelogs 3 +22 / -4
Total 21 +1395 / -74

Start here:

  1. python/a2ui_agent/src/a2ui/builder/core/function_call.py (new): the two validators, one for return types in property slots and one for argument types. Check the rules for untyped calls, "any", and an explicit returnType.
  2. python/a2ui_agent/src/a2ui/builder/v1_0/models.py (and v0_9/models.py): defines the typed classes twice, a generic version for type checkers and a Pydantic version for runtime. Check that both reject the same cases.
  3. dart/a2ui_cli/lib/src/emitters/python/python_emitter.dart: the returnType to base class mapping.
  4. python/a2ui_agent/src/a2ui/transformers/macros/macro.py: adds the core models to the lists of model types that macros accept.
Implementation details
  • Static typing: under TYPE_CHECKING, FunctionCall is a generic FunctionCall[_ReturnT] (covariant, defaults to Any). Each typed subclass binds a nominal sentinel (StringReturn, BooleanReturn, VoidReturn, and so on). Nominal sentinels avoid Python's bool <: int and str <: Sequence[str] rules, which would otherwise let mismatched calls through.
  • Runtime: FunctionCall stays the core Pydantic model, so raw FunctionCall(call=...) keeps working. Typed subclasses inherit from a private _TypedFunctionCall and set a _declared_return_type class variable, which is not serialized.
  • Dynamic* aliases use Annotated[FunctionCall, validate_function_return_type(...)]. The validator rejects a mismatched _declared_return_type or explicit returnType, and treats "any" as assignable.
  • v0.9 only: for an untyped FunctionCall in a typed slot, the validator infers return_type on a copy without marking it set, matching the core ReturnType inference, so it stays off the wire. This inference never rejects a call. v0.9 has no ValidationResultFunctionCall; the CLI maps validationResult to BooleanFunctionCall there.
  • validate_typed_function_args builds cached TypeAdapters from the subclass's __init__ hints. It maps wire keys back to parameter names with the same toSnakeCase rule the CLI uses (baseURL to base_url, max-length to max_length) and stores coerced values back into args.
  • Builder CheckRule, AccessibilityAttributes, and ActionEvent use coerce_core_model in a before validator to accept core instances. ActionEvent also rejects an explicit null userMessage, as the core model does.
  • Dart: AnalysedFunctionApi.returnKind (A2uiReturnType, default any) is filled in by CatalogAnalyzer. The goldens change only in their imports and __all__.
Verification

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

  • Full Python suite passes (6027 passed); mypy is clean (283 source files).
  • Dart a2ui_cli tests pass (116).
  • 56 conformance goldens valid; Prettier and pyink clean on every commit; every commit has a DCO sign-off.

This PR adds test_shared_builder_models_extend_core_models and test_v09_return_typed_function_calls_runtime_and_mypy to python/a2ui_agent/tests/test_pydantic_builders.py, and test_v10_return_typed_function_calls_runtime_and_mypy and test_v10_typed_function_call_edge_cases to test_pydantic_builders_v1_0.py. The mypy tests run mypy.api with --strict on snippets. It also adds a dart/a2ui_cli/test/codegen_test.dart case that maps all 8 A2uiReturnType values to their base classes.

@jacobsimionato jacobsimionato changed the title feat(python/builder,cli): enforce FunctionCall returnType statically and at runtime (#3607) feat(python/builder,cli): type-check FunctionCall returnType (#3607) Dec 3, 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 return-typed FunctionCall subclasses (such as StringFunctionCall, NumberFunctionCall, etc.) across both the Dart code generator and the Python agent builders to enforce strict return-type constraints during static analysis (mypy) and runtime validation (Pydantic). It updates core models like CheckRule, AccessibilityAttributes, and ActionEvent to leverage these typed function calls and adds comprehensive test coverage. The review feedback highlights a thread-safety issue with the global cache _ARG_ADAPTERS_CACHE in function_call.py and suggests guarding its access with a threading.Lock to prevent race conditions in multi-threaded environments.

Comment on lines +28 to +30
_ARG_ADAPTERS_CACHE: weakref.WeakKeyDictionary[
type[Any], dict[str, TypeAdapter[Any]]
] = weakref.WeakKeyDictionary()

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

The global cache _ARG_ADAPTERS_CACHE is implemented as a weakref.WeakKeyDictionary, which is not thread-safe in Python. In multi-threaded environments (such as concurrent web servers or multi-threaded agents), concurrent reads and writes to this dictionary can raise KeyError or RuntimeError (e.g., dictionary changed size during iteration).

To ensure thread safety, we should guard all accesses to _ARG_ADAPTERS_CACHE with a threading.Lock.

import threading

_CACHE_LOCK = threading.Lock()
_ARG_ADAPTERS_CACHE: weakref.WeakKeyDictionary[
    type[Any], dict[str, TypeAdapter[Any]]
] = weakref.WeakKeyDictionary()

Comment on lines +122 to +164
def _compiled_arg_adapters(cls: type[Any]) -> dict[str, TypeAdapter[Any]]:
"""Builds cached Pydantic ``TypeAdapter``s from a typed ``FunctionCall`` subclass's ``__init__``."""
cached = _ARG_ADAPTERS_CACHE.get(cls)
if cached is not None:
return cached
# A thin subclass of a generated function class inherits its ``__init__``.
init = next(
(
klass.__dict__["__init__"]
for klass in cls.__mro__
if "__init__" in klass.__dict__
),
None,
)
if init is None or init is BaseModel.__init__:
_ARG_ADAPTERS_CACHE[cls] = {}
return {}
try:
hints = get_type_hints(init, include_extras=True)
except Exception:
_ARG_ADAPTERS_CACHE[cls] = {}
return {}
adapters: dict[str, TypeAdapter[Any]] = {}
sig = inspect.signature(init)
for param_name, param in sig.parameters.items():
if param_name == "self" or param.kind in (
inspect.Parameter.VAR_POSITIONAL,
inspect.Parameter.VAR_KEYWORD,
):
continue
hint = hints.get(param_name)
if hint is None or hint is Any:
continue
try:
adapter: TypeAdapter[Any] = TypeAdapter(hint)
except Exception:
continue
adapters[param_name] = adapter
stripped = param_name.rstrip("_")
if stripped and stripped not in adapters:
adapters[stripped] = adapter
_ARG_ADAPTERS_CACHE[cls] = adapters
return adapters

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

To ensure thread safety under concurrent access, guard the lookup and insertion operations on _ARG_ADAPTERS_CACHE using the newly introduced _CACHE_LOCK.

def _compiled_arg_adapters(cls: type[Any]) -> dict[str, TypeAdapter[Any]]:
    """Builds cached Pydantic ``TypeAdapter``s from a typed ``FunctionCall`` subclass's ``__init__``."""
    with _CACHE_LOCK:
        cached = _ARG_ADAPTERS_CACHE.get(cls)
        if cached is not None:
            return cached
    # A thin subclass of a generated function class inherits its ``__init__``.
    init = next(
        (
            klass.__dict__["__init__"]
            for klass in cls.__mro__
            if "__init__" in klass.__dict__
        ),
        None,
    )
    if init is None or init is BaseModel.__init__:
        with _CACHE_LOCK:
            _ARG_ADAPTERS_CACHE[cls] = {}
        return {}
    try:
        hints = get_type_hints(init, include_extras=True)
    except Exception:
        with _CACHE_LOCK:
            _ARG_ADAPTERS_CACHE[cls] = {}
        return {}
    adapters: dict[str, TypeAdapter[Any]] = {}
    sig = inspect.signature(init)
    for param_name, param in sig.parameters.items():
        if param_name == "self" or param.kind in (
            inspect.Parameter.VAR_POSITIONAL,
            inspect.Parameter.VAR_KEYWORD,
        ):
            continue
        hint = hints.get(param_name)
        if hint is None or hint is Any:
            continue
        try:
            adapter: TypeAdapter[Any] = TypeAdapter(hint)
        except Exception:
            continue
        adapters[param_name] = adapter
        stripped = param_name.rstrip("_")
        if stripped and stripped not in adapters:
            adapters[stripped] = adapter
    with _CACHE_LOCK:
        _ARG_ADAPTERS_CACHE[cls] = adapters
    return adapters

@jacobsimionato jacobsimionato changed the title feat(python/builder,cli): type-check FunctionCall returnType (#3607) feat(python/builder,cli): enforce FunctionCall return types (#3607) Dec 3, 2026
…and at runtime (#3607)

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/4-typed-function-calls-v2 branch from 8b946e3 to 627b4c8 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(builder,cli): enforce function returnType compatibility in Python component builders

1 participant