Skip to content

set metadata in agent.__init__

396f322
Select commit
Loading
Failed to load commit list.
Merged

fix(pydantic-ai): Use first-class hooks when available #5947

set metadata in agent.__init__
396f322
Select commit
Loading
Failed to load commit list.
@sentry/warden / warden completed Apr 9, 2026 in 9m 38s

3 issues

Medium

Potential race condition when storing span in shared metadata - `sentry_sdk/integrations/pydantic_ai/__init__.py:51-52`

The _sentry_span is stored in ctx.metadata which, according to the docstring (line 126-127), is initialized from Agent.metadata as a shared reference. If multiple concurrent run() calls share the same metadata dictionary, the _sentry_span key could be overwritten by concurrent requests, causing spans to be mismatched between on_request and on_response/on_error handlers. This could result in spans being closed with the wrong response data or orphaned spans.

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.

4 skills analyzed
Skill Findings Duration Cost
code-review 1 5m 19s $1.71
find-bugs 2 9m 25s $3.00
skill-scanner 0 5m 2s $0.83
security-review 0 2m 43s $0.85

Duration: 22m 30s · Tokens: 4.3M in / 54.5k out · Cost: $6.43 (+dedup: $0.02, +extraction: $0.01, +merge: $0.00, +fix_gate: $0.00)