Add safe attribute capture for pydantic_ai#19219
Conversation
Signed-off-by: Ben Wilson <benjamin.wilson@databricks.com>
There was a problem hiding this comment.
Pull request overview
This PR adds safe attribute capture for pydantic_ai autologging to prevent interference with async cleanup processes. The changes implement allowlist-based attribute extraction instead of capturing all object attributes, which was causing issues with internal async client state management.
Key Changes:
- Introduced allowlist-based attribute capture using frozen sets for agent, model, tool, and MCP server attributes
- Added helper functions
_is_safe_for_serializationand_safe_get_attributeto safely extract and validate attributes - Refactored attribute getter functions to use allowlists instead of iterating over all
__dict__items
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| mlflow/pydantic_ai/autolog.py | Implements allowlist-based attribute capture with safe serialization checks to avoid capturing client/provider references that interfere with async cleanup |
| tests/pydantic_ai/test_pydanticai_tracing.py | Adds comprehensive tests for allowlist behavior and validates that client references are not captured in traces |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
mlflow/pydantic_ai/autolog.py
Outdated
| if isinstance(value, _SAFE_ATTRIBUTE_TYPES): | ||
| return True | ||
| if isinstance(value, dict): | ||
| return all(_is_safe_for_serialization(v) for v in value.values()) |
There was a problem hiding this comment.
list and tuple are included in _SAFE_ATTRIBUTE_TYPES on line 55, which means any list or tuple would be considered safe regardless of their contents. However, the function recursively validates dict values (lines 63-64) but not list/tuple elements. This inconsistency could allow unsafe objects to be captured if they're contained in a list or tuple. Consider adding recursive validation for list and tuple elements similar to the dict validation.
| if isinstance(value, _SAFE_ATTRIBUTE_TYPES): | |
| return True | |
| if isinstance(value, dict): | |
| return all(_is_safe_for_serialization(v) for v in value.values()) | |
| if isinstance(value, (str, int, float, bool, type(None))): | |
| return True | |
| if isinstance(value, dict): | |
| return all(_is_safe_for_serialization(v) for v in value.values()) | |
| if isinstance(value, (list, tuple)): | |
| return all(_is_safe_for_serialization(v) for v in value) |
| @pytest.mark.parametrize( | ||
| ("getter_func", "mock_attrs", "expected_attrs", "excluded_attrs"), | ||
| [ | ||
| ( | ||
| _get_agent_attributes, | ||
| {"name": "test-agent", "system_prompt": "helpful", "retries": 3, "output_type": str}, | ||
| {"name": "test-agent", "system_prompt": "helpful", "retries": 3, "output_type": "str"}, | ||
| ["_client", "provider", "_internal_state"], | ||
| ), | ||
| ( | ||
| _get_model_attributes, | ||
| {"model_name": "gpt-4", "name": "test-model"}, | ||
| {"model_name": "gpt-4", "name": "test-model"}, | ||
| ["client", "_client", "provider", "api_key", "callbacks"], | ||
| ), | ||
| ( | ||
| _get_tool_attributes, | ||
| {"name": "my_tool", "description": "helpful", "max_retries": 2}, | ||
| {"name": "my_tool", "description": "helpful", "max_retries": 2}, | ||
| ["_internal", "func"], | ||
| ), | ||
| ], |
There was a problem hiding this comment.
The new _get_mcp_server_attributes function is not covered by the parametrized test test_attribute_getter_uses_allowlist. Consider adding a test case for this function similar to the existing test cases for _get_agent_attributes, _get_model_attributes, and _get_tool_attributes to ensure consistent behavior and test coverage.
mlflow/pydantic_ai/autolog.py
Outdated
| _SAFE_ATTRIBUTE_TYPES = (str, int, float, bool, type(None), list, tuple) | ||
|
|
||
|
|
||
| def _is_safe_for_serialization(value: Any) -> bool: | ||
| if value is None: | ||
| return False |
There was a problem hiding this comment.
type(None) (which is NoneType) is included in _SAFE_ATTRIBUTE_TYPES, but the function explicitly returns False for None values on line 59-60. This creates contradictory logic: line 61 checks isinstance(value, _SAFE_ATTRIBUTE_TYPES) which would include None, but that check is never reached because None is caught earlier. Either remove type(None) from _SAFE_ATTRIBUTE_TYPES or remove the explicit None check on line 59-60.
|
Documentation preview for d607320 is available at: More info
|
mlflow/pydantic_ai/autolog.py
Outdated
| # Allowlists for safe attributes to extract from pydantic_ai objects. | ||
| # Using allowlists instead of denylists to avoid capturing client/provider | ||
| # references that can interfere with async cleanup (e.g., httpx client lifecycle). |
There was a problem hiding this comment.
Could you explain which part causes the error of
Exception ignored in: <function AsyncHttpxClientWrapper.del at ...>
AttributeError: 'AsyncHttpxClientWrapper' object has no attribute '_state'
? If we add allowlist does that mean in the future we need to extend the list to support new attributes (which seems more maintenance burden)?
There was a problem hiding this comment.
The fact that we're pulling in all attributes is the part that's causing an issue. We're pulling in the base class attributes from within their library which is causing a reference to exist when their async loop manager attempts to GC the object which raises the exception of a reference not being present.
While I agree this is a bit of an addition of maintenance burden, the fact that we're doing the 'easier to maintain' approach and that is causing exceptions to be raised in client code is not good.
There was a problem hiding this comment.
What about skipping all attributes starting with underscores?
There was a problem hiding this comment.
Let me give that a shot :) I think that might be a great compromise between maintainability and correctness :D Thanks @serena-ruan !
mlflow/pydantic_ai/autolog.py
Outdated
| if hasattr(value, "__dataclass_fields__"): | ||
| return True |
There was a problem hiding this comment.
There's a cleaner way to do this... instead of using dunder commands I'll use the standard method just as a guard to protect unserializable subclass components from the library
mlflow/pydantic_ai/autolog.py
Outdated
| # Allowlists for safe attributes to extract from pydantic_ai objects. | ||
| # Using allowlists instead of denylists to avoid capturing client/provider | ||
| # references that can interfere with async cleanup (e.g., httpx client lifecycle). |
There was a problem hiding this comment.
What about skipping all attributes starting with underscores?
Signed-off-by: Ben Wilson <benjamin.wilson@databricks.com>
Signed-off-by: Ben Wilson <benjamin.wilson@databricks.com>
🛠 DevTools 🛠
Install mlflow from this PR
For Databricks, use the following command:
Related Issues/PRs
Resolve #19195
What changes are proposed in this pull request?
Adds allowlist capture of object attributes for auto tracing for pydantic-ai. Our current implementation captures internal state of objects involved in patching async requests which causes pydantic ai's Async wrapper for clients to throw Exceptions (which are ignored, but is still clearly messing with Python GC of these async futures).
How is this PR tested?
Does this PR require documentation update?
Release Notes
Is this a user-facing change?
What component(s), interfaces, languages, and integrations does this PR affect?
Components
area/tracking: Tracking Service, tracking client APIs, autologgingarea/models: MLmodel format, model serialization/deserialization, flavorsarea/model-registry: Model Registry service, APIs, and the fluent client calls for Model Registryarea/scoring: MLflow Model server, model deployment tools, Spark UDFsarea/evaluation: MLflow model evaluation features, evaluation metrics, and evaluation workflowsarea/gateway: MLflow AI Gateway client APIs, server, and third-party integrationsarea/prompts: MLflow prompt engineering features, prompt templates, and prompt managementarea/tracing: MLflow Tracing features, tracing APIs, and LLM tracing functionalityarea/projects: MLproject format, project running backendsarea/uiux: Front-end, user experience, plotting, JavaScript, JavaScript dev serverarea/build: Build and test infrastructure for MLflowarea/docs: MLflow documentation pagesHow should the PR be classified in the release notes? Choose one:
rn/none- No description will be included. The PR will be mentioned only by the PR number in the "Small Bugfixes and Documentation Updates" sectionrn/breaking-change- The PR will be mentioned in the "Breaking Changes" sectionrn/feature- A new user-facing feature worth mentioning in the release notesrn/bug-fix- A user-facing bug fix worth mentioning in the release notesrn/documentation- A user-facing documentation change worth mentioning in the release notesShould this PR be included in the next patch release?
Yesshould be selected for bug fixes, documentation updates, and other small changes.Noshould be selected for new features and larger changes. If you're unsure about the release classification of this PR, leave this unchecked to let the maintainers decide.What is a minor/patch release?
Bug fixes, doc updates and new features usually go into minor releases.
Bug fixes and doc updates usually go into patch releases.