fix(pydantic-ai): Use first-class hooks when available #5947
2 issues
find-bugs: Found 2 issues (2 medium)
Medium
Span.__exit__() call in on_response is not protected against internal errors - `sentry_sdk/integrations/pydantic_ai/__init__.py:72`
The on_response hook calls span.__exit__(None, None, None) at line 72 without any exception handling. If the span's __enter__() had failed (after being stored in metadata at line 51), the __exit__() call would raise an AttributeError because _context_manager_state was never set. Unlike the on_error hook which wraps the __exit__() call with capture_internal_exceptions(), on_response lacks this protection. This could cause internal SDK errors to propagate to user code.
Agent created before sentry_init() in test_context_cleanup_on_error - integration hooks won't be registered - `tests/integrations/pydantic_ai/test_pydantic_ai.py:1190-1201`
In test_context_cleanup_on_error, the agent is created at line 1190 (test_agent = get_test_agent()) BEFORE sentry_init() is called at lines 1198-1201. The PydanticAIIntegration patches Agent.__init__ during setup, so agents created before sentry_init() won't have the Sentry hooks registered. This differs from other tests like test_context_cleanup_after_run where sentry_init() is correctly called first. The test may pass but won't actually test the integration's cleanup behavior.
Duration: 9m 25s · Tokens: 2.2M in / 27.0k out · Cost: $3.02 (+extraction: $0.01, +merge: $0.00, +fix_gate: $0.00)
Annotations
Check warning on line 72 in sentry_sdk/integrations/pydantic_ai/__init__.py
sentry-warden / warden: find-bugs
Span.__exit__() call in on_response is not protected against internal errors
The `on_response` hook calls `span.__exit__(None, None, None)` at line 72 without any exception handling. If the span's `__enter__()` had failed (after being stored in metadata at line 51), the `__exit__()` call would raise an `AttributeError` because `_context_manager_state` was never set. Unlike the `on_error` hook which wraps the `__exit__()` call with `capture_internal_exceptions()`, `on_response` lacks this protection. This could cause internal SDK errors to propagate to user code.
Check warning on line 1201 in tests/integrations/pydantic_ai/test_pydantic_ai.py
sentry-warden / warden: find-bugs
Agent created before sentry_init() in test_context_cleanup_on_error - integration hooks won't be registered
In `test_context_cleanup_on_error`, the agent is created at line 1190 (`test_agent = get_test_agent()`) BEFORE `sentry_init()` is called at lines 1198-1201. The `PydanticAIIntegration` patches `Agent.__init__` during setup, so agents created before `sentry_init()` won't have the Sentry hooks registered. This differs from other tests like `test_context_cleanup_after_run` where `sentry_init()` is correctly called first. The test may pass but won't actually test the integration's cleanup behavior.