Backtestspydanticrun-20261007-130130#13647
SerializeAsAny fails on a deferred model: TypeError: 'MockValSer' object is not an instance of 'SchemaSerializer'
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches fix the root cause the same way. When the `SchemaSerializer` downcast in `get_pydantic_serializer` fails, they call `rebuild()` on the placeholder, and they route `serialize_pydantic_serializable` through that one helper so the SerializeAsAny and polymorphism paths are both covered. Correctness: Patch A is more careful about rebuild semantics. It calls `rebuild(parent_namespace_depth=0)` and threads that parameter through `MockValSer.rebuild` and the `attempt_rebuild` handlers. This stops forward references from being resolved against whatever happens to sit 5 frames up a serialization call stack, which is unrelated to where the model was defined. Patch B uses `rebuild.call0()`, so the default depth of 5 applies. That can silently resolve annotations against the wrong namespace, or pick up names that happen to be in scope. A's `test_serialization_inference_unbuildable_model` checks exactly this case. Error handling: A changes the helper to return `Option`, using `py_get_attrs`, so a missing attribute (stdlib dataclasses) is told apart from a real failure. In the trampoline, A propagates real errors such as a rebuild failure with a meaningful 'not fully defined' message. Patch B keeps `let Ok(...)` in the trampoline, so a failed rebuild there silently falls back to non-polymorphic serialization. B also loosens `cast_into_exact` to `cast`, a minor semantic change that was not needed. Tests: both add regression tests that fail before the fix. B's tests are broader in mode and path combinations: python/json, flag versus annotation, and trampoline via runtime and config, plus pydantic-core unit tests with a mock. A covers SerializeAsAny, polymorphic serialization, and forward-ref rebuild from core, and adds the namespace-isolation test. Scope: A has some extra churn. It moves `py_get_attrs` into `tools.rs` and adds an unrelated xfail test in `test_construction.py`. Neither change adds risk. Overall, A's namespace-correctness handling and clearer error propagation outweigh B's broader test matrix.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
9m 48s
Wall-clock time in the container
Full test suite
No new failures
12,932 passed · 527 skipped · 13,459 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
131vs 202 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Serialization with SerializeAsAny fails when the runtime class of the value is a deferred model.
A deferred model is a model with defer_build=True that pydantic did not build yet.
The call raises this error:
PydanticSerializationError: Error serializing to JSON: TypeError: 'MockValSer' object is not an instance of 'SchemaSerializer'
I expect pydantic to build the deferred model at first use, and then serialize the value.
Cause
The cause is in pydantic-core, in src/serializers/infer.rs.
The function serialize_pydantic_serializable reads the attribute __pydantic_serializer__ from the value.
On a deferred model, this attribute holds a MockValSer object, not a SchemaSerializer object.
The code downcasts the object to SchemaSerializer.
The downcast fails, and the error goes to the caller.
MockValSer has a lazy rebuild hook in __getattr__.
A Python method call starts this hook.
A Rust downcast does not start this hook.
As a result, the same deferred instance serializes correctly through a direct model_dump_json(), but fails through SerializeAsAny.
The example code below shows this asymmetry.
Impact
This failure occurred for us in production.
A worker process serialized instances of model classes that it never validated in that process.
Each model_dump_json() call on the parent model failed.
Versions tested
The failure occurs on all versions that we tested:
- pydantic 2.12.5 / pydantic-core 2.41.5
- pydantic 2.13.4 / pydantic-core 2.46.4
- pydantic 2.14.0b1 / pydantic-core 2.48.0
Related issues
- #7713 tracks
MockValSererrors in general. - #12282 reported this failure and was closed as a duplicate.
Proposed fix
I have a fix with tests ready on a fork.
The fix changes get_pydantic_serializer in infer.rs:
- The function downcasts the attribute value to
SchemaSerializeras before. - If the downcast fails, the function calls the
rebuild()method of the mock object. - The function then uses the serializer that
rebuild()returns. - An object without a
rebuild()method keeps the current downcast error.
serialize_pydantic_serializable and PolymorphismTrampoline use the same code path, so one change repairs both.
All pydantic and pydantic-core test suites pass with the fix.
Please assign this issue to me, and I will open the pull request.
Example Code
from typing import Optional
from pydantic import BaseModel, ConfigDict, SerializeAsAny
class Child(BaseModel):
model_config = ConfigDict(defer_build=True)
x: int = 1
class Sub(Child):
y: int = 2
class Parent(BaseModel):
content: Optional[SerializeAsAny[Child]] = None
# model_construct() does not validate, so pydantic does not build Sub.
# This is equal to a process that serializes a class that it never validated.
sub = Sub.model_construct(x=1, y=2)
parent = Parent.model_construct(content=sub)
assert Sub.__pydantic_complete__ is False
# 1) The SerializeAsAny path fails on the deferred model.
try:
parent.model_dump_json()
except Exception as e:
print(f"{type(e).__name__}: {e}")
# PydanticSerializationError: Error serializing to JSON: TypeError:
# 'MockValSer' object is not an instance of 'SchemaSerializer'
# 2) The direct Python path rebuilds the same deferred model and succeeds.
print(sub.model_dump_json()) # {"x":1,"y":2}
assert Sub.__pydantic_complete__ is True
# 3) After the rebuild, the SerializeAsAny path also succeeds.
print(parent.model_dump_json()) # {"content":{"x":1,"y":2}}
Python, Pydantic & OS Version
pydantic version: 2.14.0b1
pydantic-core version: 2.48.0
pydantic-core build: profile=release pgo=false
python version: 3.11.15 (main, Mar 25 2026, 02:58:47) [Clang 22.1.1 ]
platform: macOS-26.5.2-arm64-arm-64bit
related packages: typing_extensions-4.16.0
commit: unknown
The same example also fails on these versions:
- pydantic 2.13.4 / pydantic-core 2.46.4 (latest stable)
- pydantic 2.12.5 / pydantic-core 2.41.5The two patches
pydantic-core/src/serializers/infer.rsindex a99b22ba..a3832623 100644@@ -663,7 +663,18 @@ pub(crate) fn infer_json_key_known<'a, 'py>( pub(crate) fn get_pydantic_serializer<'py>(value: &Bound<'py, PyAny>) -> PyResult<Bound<'py, SchemaSerializer>> { let py = value.py(); let py_serializer = value.getattr(intern!(py, "__pydantic_serializer__"))?;- py_serializer.cast_into_exact().map_err(Into::into)+ if let Ok(serializer) = py_serializer.cast::<SchemaSerializer>() {+ return Ok(serializer.clone());+ }+ // The serializer may be a placeholder (e.g. pydantic's `MockValSer` on a model with+ // `defer_build=True` which has not been built yet). A Rust downcast doesn't trigger+ // its lazy rebuild, so explicitly call `rebuild()` to obtain the real serializer.+ if let Ok(rebuild) = py_serializer.getattr(intern!(py, "rebuild"))+ && let Ok(serializer) = rebuild.call0()?.cast_into::<SchemaSerializer>()+ {+ return Ok(serializer);+ }+ py_serializer.cast_into().map_err(Into::into) } /// Serialize `value` as if it had a `__pydantic_serializer__` attribute@@ -674,9 +685,8 @@ fn serialize_pydantic_serializable<'py, S: DoSerialize>( state: &mut SerializationState<'py>, do_serialize: S, ) -> Result<S::Ok, S::Error> {- let py = value.py();- let py_serializer = value.getattr(intern!(py, "__pydantic_serializer__"))?;- call_pydantic_serializer(py_serializer.cast().map_err(Into::into)?, value, state, do_serialize)+ let serializer = get_pydantic_serializer(value)?;+ call_pydantic_serializer(&serializer, value, state, do_serialize) } pub(crate) fn call_pydantic_serializer<'py, S: DoSerialize>(pydantic-core/tests/serializers/test_any.pyindex be6325cd..c4006ce3 100644@@ -877,3 +877,48 @@ def test_counter_subclass(any_serializer) -> None: assert output == Counter({'a': 1}) assert type(output) is Counter assert any_serializer.to_json(MyCounter({'a': 1})) == b'{"a":1}'+++class _LazySerializer:+ """Mimics pydantic's `MockValSer`: a placeholder that builds the real serializer via `rebuild()`."""++ def __init__(self, rebuild_result):+ self.rebuild_result = rebuild_result+ self.rebuild_calls = 0++ def rebuild(self):+ self.rebuild_calls += 1+ return self.rebuild_result+++def test_infer_lazy_pydantic_serializer(any_serializer):+ class Lazy:+ def __init__(self, a):+ self.a = a++ fields = {'a': core_schema.model_field(core_schema.int_schema())}+ real = SchemaSerializer(core_schema.model_schema(Lazy, core_schema.model_fields_schema(fields)))+ Lazy.__pydantic_serializer__ = lazy = _LazySerializer(real)++ m = Lazy(a=1)+ m.__pydantic_fields_set__ = {'a'}+ m.__pydantic_extra__ = None+ m.__pydantic_private__ = None+ assert any_serializer.to_python(m) == {'a': 1}+ assert any_serializer.to_json(m) == b'{"a":1}'+ assert lazy.rebuild_calls == 2+++def test_infer_invalid_pydantic_serializer(any_serializer):+ class NoRebuild:+ __pydantic_serializer__ = 42++ class BadRebuild:+ __pydantic_serializer__ = _LazySerializer(None)++ msg = "'int' object is not an instance of 'SchemaSerializer'"+ with pytest.raises(TypeError, match=msg):+ any_serializer.to_python(NoRebuild())+ msg = "'_LazySerializer' object is not an instance of 'SchemaSerializer'"+ with pytest.raises(TypeError, match=msg):+ any_serializer.to_python(BadRebuild())tests/test_serialize_as_any.pyindex 2bf6091c..130d862b 100644@@ -209,3 +209,71 @@ def test_serialize_as_any_annotation_with_incorrect_list_el_type() -> None: # notably, the warning is not raised when using the SerializeAsAny annotation ta = TypeAdapter(SerializeAsAny[list[int]]) assert ta.dump_python(['a', 'b', 'c']) == ['a', 'b', 'c']+++def _make_deferred_models(polymorphic_serialization: bool | None = None):+ class Child(BaseModel):+ model_config = ConfigDict(defer_build=True)+ if polymorphic_serialization is not None:+ model_config['polymorphic_serialization'] = polymorphic_serialization+ x: int = 1++ class Sub(Child):+ y: int = 2++ class Parent(BaseModel):+ content: SerializeAsAny[Child] | None = None+ plain: Child | None = None++ return Child, Sub, Parent+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_deferred_subclass(mode: str) -> None:+ """https://github.com/pydantic/pydantic/issues/12282: a not-yet-built deferred subclass should be built on use."""+ _, Sub, Parent = _make_deferred_models()++ sub = Sub.model_construct(x=1, y=2)+ parent = Parent.model_construct(content=sub)+ assert Sub.__pydantic_complete__ is False++ if mode == 'python':+ assert parent.model_dump() == {'content': {'x': 1, 'y': 2}, 'plain': None}+ else:+ assert json.loads(parent.model_dump_json()) == {'content': {'x': 1, 'y': 2}, 'plain': None}+ assert Sub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_flag_deferred_subclass(mode: str) -> None:+ _, Sub, Parent = _make_deferred_models()++ parent = Parent.model_construct(plain=Sub.model_construct(x=1, y=2))+ assert Sub.__pydantic_complete__ is False++ if mode == 'python':+ assert parent.model_dump(serialize_as_any=True) == {'content': None, 'plain': {'x': 1, 'y': 2}}+ else:+ assert json.loads(parent.model_dump_json(serialize_as_any=True)) == {+ 'content': None,+ 'plain': {'x': 1, 'y': 2},+ }+ assert Sub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+@pytest.mark.parametrize('via', ['runtime', 'config'])+def test_polymorphic_serialization_deferred_subclass(mode: str, via: str) -> None:+ Child, Sub, Parent = _make_deferred_models(polymorphic_serialization=True if via == 'config' else None)+ # build Child (but not Sub), so that the polymorphism trampoline is used for `plain`+ Child.model_rebuild()++ parent = Parent.model_construct(plain=Sub.model_construct(x=1, y=2))+ assert Sub.__pydantic_complete__ is False++ kwargs = {'polymorphic_serialization': True} if via == 'runtime' else {}+ if mode == 'python':+ assert parent.model_dump(**kwargs) == {'content': None, 'plain': {'x': 1, 'y': 2}}+ else:+ assert json.loads(parent.model_dump_json(**kwargs)) == {'content': None, 'plain': {'x': 1, 'y': 2}}+ assert Sub.__pydantic_complete__ is True
pydantic-core/src/lookup_key.rsindex 7af597934..56ac74dd8 100644@@ -3,7 +3,7 @@ use std::convert::Infallible; use std::fmt; use pyo3::IntoPyObjectExt;-use pyo3::exceptions::{PyAttributeError, PyTypeError, PyValueError};+use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; use pyo3::pybacked::PyBackedStr; use pyo3::types::{PyDict, PyList, PyMapping, PyString};@@ -14,7 +14,7 @@ use smallvec::SmallVec; use crate::build_tools::py_schema_err; use crate::errors::{ErrorType, LocItem, Location, ValError, ValLineError, ValResult, py_err_string}; use crate::input::StringMapping;-use crate::tools::{mapping_get, py_err};+use crate::tools::{mapping_get, py_err, py_get_attrs}; /// The possible choices for an alias value in Python #[derive(FromPyObject)]@@ -454,20 +454,3 @@ impl LookupType { (self as u8 & other as u8) != 0 } }--// TODO replace with `PyAnyMethods::getattr_opt` once https://github.com/PyO3/pyo3/pull/5985 is merged:-fn py_get_attrs<'py, N>(obj: &Bound<'py, PyAny>, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>-where- N: IntoPyObject<'py, Target = PyString>,-{- match obj.getattr(attr_name) {- Ok(attr) => Ok(Some(attr)),- Err(err) => {- if err.get_type(obj.py()).is_subclass_of::<PyAttributeError>()? {- Ok(None)- } else {- Err(err)- }- }- }-}pydantic-core/src/serializers/infer.rsindex a99b22baa..ef8ec3b2e 100644@@ -27,7 +27,7 @@ use crate::serializers::shared::serialize_to_python; use crate::serializers::type_serializers; use crate::serializers::type_serializers::any::AnySerializer; use crate::serializers::type_serializers::format::serialize_via_str;-use crate::tools::{py_err, safe_repr};+use crate::tools::{py_err, py_get_attrs, safe_repr}; use super::SchemaSerializer; use super::config::InfNanMode;@@ -660,10 +660,33 @@ pub(crate) fn infer_json_key_known<'a, 'py>( } } -pub(crate) fn get_pydantic_serializer<'py>(value: &Bound<'py, PyAny>) -> PyResult<Bound<'py, SchemaSerializer>> {+/// Get the `SchemaSerializer` stored as `__pydantic_serializer__` on `value`'s type, or `None`+/// if there's no such attribute (e.g. for stdlib dataclasses).+///+/// If the type isn't fully built yet, pydantic stores a placeholder (`MockValSer`) that rebuilds the+/// type lazily when one of its attributes is accessed from Python. Casting it from Rust bypasses that+/// mechanism, so we explicitly call its `rebuild()` method, which rebuilds the whole type and either+/// returns the built serializer or raises a meaningful error.+pub(crate) fn get_pydantic_serializer<'py>(+ value: &Bound<'py, PyAny>,+) -> PyResult<Option<Bound<'py, SchemaSerializer>>> { let py = value.py();- let py_serializer = value.getattr(intern!(py, "__pydantic_serializer__"))?;- py_serializer.cast_into_exact().map_err(Into::into)+ let Some(py_serializer) = py_get_attrs(value, intern!(py, "__pydantic_serializer__"))? else {+ return Ok(None);+ };+ if let Ok(serializer) = py_serializer.cast_exact::<SchemaSerializer>() {+ return Ok(Some(serializer.clone()));+ }+ if py_serializer.hasattr(intern!(py, "rebuild"))? {+ // The call stack is unrelated to where the type was defined, so don't use a parent frame namespace:+ let kwargs = PyDict::new(py);+ kwargs.set_item(intern!(py, "parent_namespace_depth"), 0)?;+ let rebuilt = py_serializer.call_method(intern!(py, "rebuild"), (), Some(&kwargs))?;+ if !rebuilt.is_none() {+ return Ok(Some(rebuilt.cast_into_exact()?));+ }+ }+ Ok(Some(py_serializer.cast_into_exact()?)) } /// Serialize `value` as if it had a `__pydantic_serializer__` attribute@@ -674,9 +697,11 @@ fn serialize_pydantic_serializable<'py, S: DoSerialize>( state: &mut SerializationState<'py>, do_serialize: S, ) -> Result<S::Ok, S::Error> {- let py = value.py();- let py_serializer = value.getattr(intern!(py, "__pydantic_serializer__"))?;- call_pydantic_serializer(py_serializer.cast().map_err(Into::into)?, value, state, do_serialize)+ match get_pydantic_serializer(value)? {+ Some(serializer) => call_pydantic_serializer(&serializer, value, state, do_serialize),+ // `ObType::PydanticSerializable` was inferred from the attribute being present+ None => Err(unknown_type_error(value).into()),+ } } pub(crate) fn call_pydantic_serializer<'py, S: DoSerialize>(pydantic-core/src/serializers/polymorphism_trampoline.rsindex badab29da..579b63019 100644@@ -50,7 +50,7 @@ impl PolymorphismTrampoline { && runtime_polymorphic.unwrap_or(self.enabled_from_config) && self.is_subclass(value)? // stdlib dataclasses do not have a `__pydantic_serializer__`- && let Ok(serializer) = get_pydantic_serializer(value)+ && let Some(serializer) = get_pydantic_serializer(value)? { call_pydantic_serializer(&serializer, value, state, do_serialize) } else {pydantic-core/src/tools.rsindex 6fc6df6d2..7a3533eb9 100644@@ -3,7 +3,7 @@ use core::fmt; use hashbrown::HashTable; use pyo3::PyTraverseError; use pyo3::PyVisit;-use pyo3::exceptions::PyKeyError;+use pyo3::exceptions::{PyAttributeError, PyKeyError}; use pyo3::intern; use pyo3::prelude::*; use pyo3::types::{PyDict, PyMapping, PyString};@@ -202,6 +202,23 @@ pub fn mapping_get<'py>( .map(|value| if value.is(undefined) { None } else { Some(value) }) } +// TODO replace with `PyAnyMethods::getattr_opt` once https://github.com/PyO3/pyo3/pull/5985 is merged:+pub(crate) fn py_get_attrs<'py, N>(obj: &Bound<'py, PyAny>, attr_name: N) -> PyResult<Option<Bound<'py, PyAny>>>+where+ N: IntoPyObject<'py, Target = PyString>,+{+ match obj.getattr(attr_name) {+ Ok(attr) => Ok(Some(attr)),+ Err(err) => {+ if err.get_type(obj.py()).is_subclass_of::<PyAttributeError>()? {+ Ok(None)+ } else {+ Err(err)+ }+ }+ }+}+ /// A hash table which uses (hashable) Python objects as keys #[derive(Debug)] pub struct PyHashTable<T>(HashTable<PyHashTableEntry<T>>);pydantic/_internal/_mock_val_ser.pyindex fea9713c9..b0344ac06 100644@@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Callable, Iterator, Mapping-from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar+from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol, TypeVar from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator @@ -16,6 +16,11 @@ if TYPE_CHECKING: ValSer = TypeVar('ValSer', bound=SchemaValidator | PluggableSchemaValidator | SchemaSerializer) T = TypeVar('T')+T_co = TypeVar('T_co', covariant=True)+++class AttemptRebuild(Protocol[T_co]):+ def __call__(self, *, parent_namespace_depth: int = ...) -> T_co | None: ... class MockCoreSchema(Mapping[str, Any]):@@ -30,7 +35,7 @@ class MockCoreSchema(Mapping[str, Any]): error_message: str, *, code: PydanticErrorCodes,- attempt_rebuild: Callable[[], CoreSchema | None] | None = None,+ attempt_rebuild: AttemptRebuild[CoreSchema] | None = None, ) -> None: self._error_message = error_message self._code: PydanticErrorCodes = code@@ -81,7 +86,7 @@ class MockValSer(Generic[ValSer]): *, code: PydanticErrorCodes, val_or_ser: Literal['validator', 'serializer'],- attempt_rebuild: Callable[[], ValSer | None] | None = None,+ attempt_rebuild: AttemptRebuild[ValSer] | None = None, ) -> None: self._error_message = error_message self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer@@ -99,9 +104,9 @@ class MockValSer(Generic[ValSer]): getattr(self._val_or_ser, item) raise PydanticUserError(self._error_message, code=self._code) - def rebuild(self) -> ValSer | None:+ def rebuild(self, *, parent_namespace_depth: int = 5) -> ValSer | None: if self._attempt_rebuild:- val_ser = self._attempt_rebuild()+ val_ser = self._attempt_rebuild(parent_namespace_depth=parent_namespace_depth) if val_ser is not None: return val_ser else:@@ -121,9 +126,9 @@ def set_type_adapter_mocks(adapter: TypeAdapter) -> None: f' then call `.rebuild()` on the instance.' ) - def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> Callable[[], T | None]:- def handler() -> T | None:- if adapter.rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:+ def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> AttemptRebuild[T]:+ def handler(*, parent_namespace_depth: int = 5) -> T | None:+ if adapter.rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: return attr_fn(adapter) return None @@ -162,9 +167,9 @@ def set_model_mocks(cls: type[BaseModel], undefined_name: str | None = None) -> f' then call `{cls.__name__}.model_rebuild()`.' ) - def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> Callable[[], T | None]:- def handler() -> T | None:- if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:+ def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> AttemptRebuild[T]:+ def handler(*, parent_namespace_depth: int = 5) -> T | None:+ if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: return attr_fn(cls) return None @@ -205,9 +210,9 @@ def set_dataclass_mocks(cls: type[PydanticDataclass], undefined_name: str | None f' then call `pydantic.dataclasses.rebuild_dataclass({cls.__name__})`.' ) - def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> Callable[[], T | None]:- def handler() -> T | None:- if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=5) is not False:+ def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> AttemptRebuild[T]:+ def handler(*, parent_namespace_depth: int = 5) -> T | None:+ if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=parent_namespace_depth) is not False: return attr_fn(cls) return None tests/test_construction.pyindex 1f42457e3..15350a693 100644@@ -1,5 +1,5 @@ import pickle-from typing import Any+from typing import Annotated, Any import pytest from pydantic_core import PydanticUndefined, ValidationError@@ -669,3 +669,26 @@ def test_model_construct_with_alias_choices_and_path() -> None: assert MyModel.model_construct(a='a_value').a == 'a_value' assert MyModel.model_construct(aaa='a_value').a == 'a_value' assert MyModel.model_construct(AAA={'aaa': 'a_value'}).a == 'a_value'+++@pytest.mark.xfail(+ reason='`model_construct()` does not rebuild incomplete models, and relies on `FieldInfo` instances '+ 'that may be incomplete (here, the `Field()` metadata is part of the unevaluated annotation).',+)+def test_model_construct_incomplete_model() -> None:+ # When making this test work, look at `test_string_annotation_union_type()` which assumes `model_construct()`+ # doesn't rebuild the model.+ class Model(BaseModel):+ a: 'Annotated[Later | None, Field(alias="A")]'+ b: 'Annotated[Later | None, Field(default=None)]'++ class Later(BaseModel):+ pass++ assert Model.__pydantic_complete__ is False++ later = Later()+ m = Model.model_construct(A=later)+ assert m.a is later+ assert m.b is None+ assert m.model_fields_set == {'a'}tests/test_forward_ref.pyindex 59ebb6a94..f0e69b73e 100644@@ -1731,3 +1731,44 @@ def test_string_annotation_union_type() -> None: assert typing_objects.is_union(get_origin(annotation)) assert get_args(annotation)[0] is Main+++def test_serialization_inference_rebuilds_incomplete_model(create_module) -> None:+ """https://github.com/pydantic/pydantic/issues/7713"""++ # Necessary to have classes defined at module level for forward ref+ # to resolve when rebuilding model from pydantic-core:+ @create_module+ def module():+ from typing import Optional++ from pydantic import BaseModel++ class B(BaseModel):+ a: Optional['A'] = None++ class A(BaseModel):+ b: B++ a = module.A.model_validate({'b': {}})+ assert module.B.__pydantic_complete__ is False++ assert TypeAdapter(Any).dump_python(a.b) == {'a': None}+ assert module.B.__pydantic_complete__ is True+ assert a.model_dump(serialize_as_any=True) == {'b': {'a': None}}+++def test_serialization_inference_unbuildable_model() -> None:+ """When rebuilt from pydantic-core, the caller's frame namespace should not be used to resolve annotations."""++ class Model(BaseModel):+ x: 'Undefined' # noqa: F821++ def serialize(m: Model) -> Any:+ Undefined = int # noqa: F841+ return TypeAdapter(Any).dump_python(m)++ m = Model.model_construct(x=1)+ with pytest.raises(PydanticUserError, match='`Model` is not fully defined; you should define `Undefined`'):+ serialize(m)+ assert Model.__pydantic_complete__ is Falsetests/test_serialize_as_any.pyindex 2bf6091c6..4bde976ec 100644@@ -209,3 +209,25 @@ def test_serialize_as_any_annotation_with_incorrect_list_el_type() -> None: # notably, the warning is not raised when using the SerializeAsAny annotation ta = TypeAdapter(SerializeAsAny[list[int]]) assert ta.dump_python(['a', 'b', 'c']) == ['a', 'b', 'c']+++@pytest.mark.parametrize('kwargs', [{'serialize_as_any': True}, {'polymorphic_serialization': True}])+def test_serialize_as_any_deferred_subclass(kwargs) -> None:+ """https://github.com/pydantic/pydantic/issues/13647"""++ class Base(BaseModel):+ x: int = 1++ class Sub(Base):+ model_config = ConfigDict(defer_build=True)+ y: int = 2++ class Model(BaseModel):+ b: Base++ # `model_construct()` currently doesn't trigger a rebuild of `Sub`:+ m = Model(b=Sub.model_construct(x=1, y=2))+ assert Sub.__pydantic_complete__ is False++ assert m.model_dump(**kwargs) == {'b': {'x': 1, 'y': 2}}+ assert Sub.__pydantic_complete__ is True