Repository navigation
feat(python/builder,cli): enforce FunctionCall return types (#3607) - #4565
jacobsimionato wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
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.
| _ARG_ADAPTERS_CACHE: weakref.WeakKeyDictionary[ | ||
| type[Any], dict[str, TypeAdapter[Any]] | ||
| ] = weakref.WeakKeyDictionary() |
There was a problem hiding this comment.
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()| 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 |
There was a problem hiding this comment.
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…and at runtime (#3607) Signed-off-by: Jacob Simionato <jsimionato@google.com>
8b946e3 to
627b4c8
Compare
Problem
Builders are the typed Python component classes that
dart/a2ui_cligenerates from a catalog. Each catalog function (such asFormatString,Required, orOpenUrl) became a plainFunctionCallsubclass with no return type. SoText(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 ina2ui.core.schema; builder models ina2ui.builder.v0_9andv1_0wrap them for authoring.FunctionCallsubclasses to both builder packages:StringFunctionCall,NumberFunctionCall,BooleanFunctionCall,ArrayFunctionCall,ObjectFunctionCall: fit only the matchingDynamic*slot.ValidationResultFunctionCall(v1.0 only; v0.9 has no such return type, so the CLI usesBooleanFunctionCallthere): fits boolean slots andCheckRule.condition.VoidFunctionCall: side-effect calls; valid only asAction(function_call=...).AnyFunctionCall: explicit opt-out for functions whose catalog return type isany; fits any slot, like an untyped call.Dynamic*types,CheckRule.condition,AccessibilityAttributes, andActionEventso mypy and Pydantic both reject a call with the wrong return type. UntypedFunctionCall(...)without an explicitreturnTypeis still accepted in every slot.__init__annotations, so a mismatch nested inside another call's arguments is also caught.dart/a2ui_clipick each generated function's base class from the catalogreturnType, and regenerate the v0.9 and v1.0 basic catalogs.CheckRule,AccessibilityAttributes, andActionEventsubclasses 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
ValidationErrorat construction. Valid code is unaffected.CheckRule,AccessibilityAttributes, andActionEventin 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. Butbuilder.CheckRule is core.CheckRuleis nowFalse, and so isisinstance(core_obj, builder.CheckRule). Serialized JSON is unchanged.New public API
Where to review
Start here:
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 explicitreturnType.python/a2ui_agent/src/a2ui/builder/v1_0/models.py(andv0_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.dart/a2ui_cli/lib/src/emitters/python/python_emitter.dart: thereturnTypeto base class mapping.python/a2ui_agent/src/a2ui/transformers/macros/macro.py: adds the core models to the lists of model types that macros accept.Implementation details
TYPE_CHECKING,FunctionCallis a genericFunctionCall[_ReturnT](covariant, defaults toAny). Each typed subclass binds a nominal sentinel (StringReturn,BooleanReturn,VoidReturn, and so on). Nominal sentinels avoid Python'sbool <: intandstr <: Sequence[str]rules, which would otherwise let mismatched calls through.FunctionCallstays the core Pydantic model, so rawFunctionCall(call=...)keeps working. Typed subclasses inherit from a private_TypedFunctionCalland set a_declared_return_typeclass variable, which is not serialized.Dynamic*aliases useAnnotated[FunctionCall, validate_function_return_type(...)]. The validator rejects a mismatched_declared_return_typeor explicitreturnType, and treats"any"as assignable.FunctionCallin a typed slot, the validator infersreturn_typeon a copy without marking it set, matching the coreReturnTypeinference, so it stays off the wire. This inference never rejects a call. v0.9 has noValidationResultFunctionCall; the CLI mapsvalidationResulttoBooleanFunctionCallthere.validate_typed_function_argsbuilds cachedTypeAdapters from the subclass's__init__hints. It maps wire keys back to parameter names with the sametoSnakeCaserule the CLI uses (baseURLtobase_url,max-lengthtomax_length) and stores coerced values back intoargs.CheckRule,AccessibilityAttributes, andActionEventusecoerce_core_modelin abeforevalidator to accept core instances.ActionEventalso rejects an explicit nulluserMessage, as the core model does.AnalysedFunctionApi.returnKind(A2uiReturnType, defaultany) is filled in byCatalogAnalyzer. The goldens change only in their imports and__all__.Verification
Measured at the stack tip (all 11 commits applied):
a2ui_clitests pass (116).This PR adds
test_shared_builder_models_extend_core_modelsandtest_v09_return_typed_function_calls_runtime_and_mypytopython/a2ui_agent/tests/test_pydantic_builders.py, andtest_v10_return_typed_function_calls_runtime_and_mypyandtest_v10_typed_function_call_edge_casestotest_pydantic_builders_v1_0.py. The mypy tests runmypy.apiwith--stricton snippets. It also adds adart/a2ui_cli/test/codegen_test.dartcase that maps all 8A2uiReturnTypevalues to their base classes.