Backtestspydanticrun-20261013-104308#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 A = our agent, Patch B = the merged fix.
Both patches fix the root cause in `get_pydantic_serializer`. When the downcast fails, each calls the mock's `rebuild()` and uses the serializer it returns. Both also route `serialize_pydantic_serializable` through that helper, so the `SerializeAsAny` path and the polymorphism trampoline are both covered. The key correctness difference is namespace resolution during the rebuild. Patch A calls `rebuild()` with its default `_parent_namespace_depth=5`. When the call comes from Rust deep inside serialization, frame 5 is an unrelated caller frame. Forward references could then resolve against whatever namespace happens to sit there, either succeeding wrongly or failing unpredictably. Patch B adds a `parent_namespace_depth` parameter through `MockValSer.rebuild` and the `attempt_rebuild` handlers, and passes 0 from Rust. Its test `test_serialization_inference_unbuildable_model` checks that a caller-local `Undefined = int` does not leak into the rebuild. `test_serialization_inference_rebuilds_incomplete_model` checks that module-level forward refs still resolve. Error handling in the trampoline also favours B. B makes the helper return `Option`, so only a missing attribute (stdlib dataclasses) falls back, and real rebuild errors propagate. Patch A pattern-matches `AttributeError`/`TypeError` to decide when to fall back. That fallback could silently hide a `TypeError` raised during a rebuild and quietly serialize with the parent-class serializer. On tests, A has the more thorough coverage of the exact issue scenario: annotation, flag and polymorphic paths, in both python and json modes, plus rebuild-failure cases. B covers the flag and polymorphic paths, plus the namespace-correctness cases. Both sets would fail before their fix. On scope, B carries extra churn: moving `py_get_attrs` into `tools.rs` and an unrelated xfail test in `test_construction.py`. That is mostly neutral. B's handling of the frame-namespace hazard makes it the more robust fix overall.
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
6m 41s
Wall-clock time in the container
Full test suite
No new failures
1,294 passed · 127 skipped · 1,421 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
149vs 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..f844bda6 100644@@ -660,10 +660,25 @@ pub(crate) fn infer_json_key_known<'a, 'py>( } } +/// Get the `SchemaSerializer` stored in the `__pydantic_serializer__` attribute of `value`.+///+/// If the attribute is not a `SchemaSerializer` (e.g. it is pydantic's `MockValSer` placeholder for a+/// model with `defer_build=True` which has not yet been built), the object's `rebuild()` method is called+/// (if it has one) and the serializer it returns is used instead. 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());+ }+ if let Some(rebuild) = py_serializer.getattr_opt(intern!(py, "rebuild"))? {+ let rebuilt = rebuild.call0()?;+ if !rebuilt.is_none() {+ return rebuilt.cast_into().map_err(Into::into);+ }+ }+ // not a rebuildable mock, report the original cast error+ py_serializer.cast_into().map_err(Into::into) } /// Serialize `value` as if it had a `__pydantic_serializer__` attribute@@ -674,9 +689,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/src/serializers/polymorphism_trampoline.rsindex badab29d..429ced23 100644@@ -1,6 +1,10 @@ use std::{borrow::Cow, sync::Arc}; -use pyo3::{prelude::*, types::PyType};+use pyo3::{+ exceptions::{PyAttributeError, PyTypeError},+ prelude::*,+ types::PyType,+}; use crate::serializers::{ CombinedSerializer, SerializationState,@@ -49,10 +53,19 @@ impl PolymorphismTrampoline { if state.check != SerCheck::Strict // strict disables polymorphism && 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) {- call_pydantic_serializer(&serializer, value, state, do_serialize)+ match get_pydantic_serializer(value) {+ Ok(serializer) => call_pydantic_serializer(&serializer, value, state, do_serialize),+ // stdlib dataclasses do not have a `__pydantic_serializer__`+ Err(err)+ if err.is_instance_of::<PyAttributeError>(value.py())+ || err.is_instance_of::<PyTypeError>(value.py()) =>+ {+ do_serialize.serialize_no_infer(&self.serializer, value, state)+ }+ // e.g. a deferred model which failed to build+ Err(err) => Err(err.into()),+ } } else { do_serialize.serialize_no_infer(&self.serializer, value, state) }tests/test_serialize_as_any.pyindex 2bf6091c..31676e30 100644@@ -1,9 +1,10 @@ import json import pytest+from pydantic_core import PydanticSerializationError from typing_extensions import TypedDict -from pydantic import BaseModel, ConfigDict, RootModel, SecretStr, SerializeAsAny, TypeAdapter+from pydantic import BaseModel, ConfigDict, PydanticUserError, RootModel, SecretStr, SerializeAsAny, TypeAdapter from .utils import dataclass_decorators @@ -209,3 +210,106 @@ 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 _deferred_child_classes() -> tuple[type[BaseModel], type[BaseModel]]:+ class DeferredChild(BaseModel):+ model_config = ConfigDict(defer_build=True)+ x: int = 1++ class DeferredSub(DeferredChild):+ y: int = 2++ return DeferredChild, DeferredSub+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_annotation_deferred_model(mode) -> None:+ """https://github.com/pydantic/pydantic/issues/13647"""+ DeferredChild, DeferredSub = _deferred_child_classes()++ class Parent(BaseModel):+ content: SerializeAsAny[DeferredChild] | None = None++ sub = DeferredSub.model_construct(x=1, y=2)+ parent = Parent.model_construct(content=sub)+ assert DeferredSub.__pydantic_complete__ is False++ if mode == 'json':+ assert json.loads(parent.model_dump_json()) == {'content': {'x': 1, 'y': 2}}+ else:+ assert parent.model_dump() == {'content': {'x': 1, 'y': 2}}+ assert DeferredSub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_flag_deferred_model(mode) -> None:+ DeferredChild, DeferredSub = _deferred_child_classes()++ class Parent(BaseModel):+ content: DeferredChild++ parent = Parent.model_construct(content=DeferredSub.model_construct(x=1, y=2))+ assert DeferredSub.__pydantic_complete__ is False++ if mode == 'json':+ assert json.loads(parent.model_dump_json(serialize_as_any=True)) == {'content': {'x': 1, 'y': 2}}+ else:+ assert parent.model_dump(serialize_as_any=True) == {'content': {'x': 1, 'y': 2}}+ assert DeferredSub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_polymorphic_serialization_deferred_model(mode) -> None:+ DeferredChild, DeferredSub = _deferred_child_classes()++ class Parent(BaseModel):+ content: DeferredChild++ parent = Parent.model_construct(content=DeferredSub.model_construct(x=1, y=2))+ assert DeferredSub.__pydantic_complete__ is False++ if mode == 'json':+ assert json.loads(parent.model_dump_json(polymorphic_serialization=True)) == {'content': {'x': 1, 'y': 2}}+ else:+ assert parent.model_dump(polymorphic_serialization=True) == {'content': {'x': 1, 'y': 2}}+ assert DeferredSub.__pydantic_complete__ is True+++def test_serialize_as_any_deferred_model_rebuild_failure() -> None:+ class DeferredChild(BaseModel):+ model_config = ConfigDict(defer_build=True)+ x: int = 1++ class DeferredSub(DeferredChild):+ y: 'UndefinedType' # noqa: F821++ class Parent(BaseModel):+ content: SerializeAsAny[DeferredChild]++ parent = Parent.model_construct(content=DeferredSub.model_construct(x=1, y=2))++ with pytest.raises(PydanticUserError, match='`DeferredSub` is not fully defined'):+ parent.model_dump()+ with pytest.raises(PydanticSerializationError, match='`DeferredSub` is not fully defined'):+ parent.model_dump_json()+++def test_polymorphic_serialization_deferred_model_rebuild_failure() -> None:+ class DeferredChild(BaseModel):+ model_config = ConfigDict(defer_build=True)+ x: int = 1++ class DeferredSub(DeferredChild):+ y: 'UndefinedType' # noqa: F821++ class Parent(BaseModel):+ content: DeferredChild++ parent = Parent.model_construct(content=DeferredSub.model_construct(x=1, y=2))++ # the build error is raised, rather than silently falling back to the parent class serializer+ with pytest.raises(PydanticUserError, match='`DeferredSub` is not fully defined'):+ parent.model_dump(polymorphic_serialization=True)+ with pytest.raises(PydanticSerializationError, match='`DeferredSub` is not fully defined'):+ parent.model_dump_json(polymorphic_serialization=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