Skip to content

Commit 6c32588

Browse files
authored
Operate on a deepcopy of $defs in JsonSchemaTransformer instead of the original schema (#3758)
1 parent acde3ec commit 6c32588

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

pydantic_ai_slim/pydantic_ai/_json_schema.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def __init__(
4545
self.prefer_inlined_defs = prefer_inlined_defs
4646
self.simplify_nullable_unions = simplify_nullable_unions
4747

48-
self.defs: dict[str, JsonSchema] = self.schema.get('$defs', {})
48+
self.defs: dict[str, JsonSchema] = deepcopy(self.schema.get('$defs', {}))
4949
self.refs_stack: list[str] = []
5050
self.recursive_refs = set[str]()
5151

tests/test_json_schema.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations as _annotations
44

5+
from copy import deepcopy
56
from typing import Any
67

78
from pydantic_ai._json_schema import JsonSchemaTransformer
@@ -49,3 +50,40 @@ def transform(self, schema: dict[str, Any]) -> dict[str, Any]:
4950
# Should keep anyOf since it's not nullable
5051
assert 'anyOf' in result3
5152
assert len(result3['anyOf']) == 2
53+
54+
55+
def test_schema_defs_not_modified():
56+
"""Test that the original schema $defs are not modified during transformation."""
57+
58+
# Create a concrete subclass for testing
59+
class TestTransformer(JsonSchemaTransformer):
60+
def transform(self, schema: dict[str, Any]) -> dict[str, Any]:
61+
return schema
62+
63+
# Create a schema with $defs that should not be modified
64+
original_schema = {
65+
'type': 'object',
66+
'properties': {'value': {'$ref': '#/$defs/TestUnion'}},
67+
'$defs': {
68+
'TestUnion': {
69+
'anyOf': [
70+
{'type': 'string'},
71+
{'type': 'number'},
72+
],
73+
'title': 'TestUnion',
74+
}
75+
},
76+
}
77+
78+
# Keep a deepcopy to compare against later
79+
original_schema_copy = deepcopy(original_schema)
80+
81+
# Transform the schema
82+
transformer = TestTransformer(original_schema)
83+
result = transformer.walk()
84+
85+
# Verify the original schema was not modified
86+
assert original_schema == original_schema_copy
87+
88+
# Verify the result is correct
89+
assert result == original_schema_copy

0 commit comments

Comments
 (0)