Backtestspydanticrun-20261022-024030#13647

Issue #13647 Merged fix PR #13922 Run 22 Oct 2026 · run-20261022-024030 pydantic/pydantic

SerializeAsAny fails on a deferred model: TypeError: 'MockValSer' object is not an instance of 'SchemaSerializer'

Worse

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 `__pydantic_serializer__` attribute does not downcast to `SchemaSerializer`, call the mock's `rebuild()` and use the returned serializer. Both route `serialize_pydantic_serializable` and the `PolymorphismTrampoline` through the shared helper, and both stop the trampoline from silently swallowing the cast error and falling back to the parent serializer (A by returning `Option` and propagating `?`, B by a `hasattr` pre-check then `?`). All independent tests pass on both.

The meaningful difference is in how the rebuild resolves forward references. `MockValSer.rebuild()` delegates to `model_rebuild(_parent_namespace_depth=5)`, a frame depth calibrated for the `__getattr__` lazy hook being hit from a Python call site. Patch B calls `rebuild()` with no arguments from Rust, so the namespace used to resolve annotations is whatever frame happens to sit five levels above `model_rebuild` in the serialization call stack (e.g. the caller's caller of `model_dump_json`). That is an arbitrary, call-depth-dependent namespace and can resolve or fail to resolve names depending on where serialization is invoked. Patch A recognises this, adds a `parent_namespace_depth` keyword to `MockValSer.rebuild` and the `attempt_rebuild` handlers, and passes `0` from Rust so no caller frame is used. It also adds `test_serialization_inference_unbuildable_model` to pin that behaviour, and a `create_module` forward-ref test showing module-level resolution still works. B has no equivalent reasoning or test, so its fix is subtly fragile in exactly the scenario the issue describes (a worker process serializing classes it never validated, from an unrelated call stack).

On tests, B is somewhat broader on the issue's literal scenario (python/json modes, `serialize_as_any` flag, `polymorphic_serialization`, and 'not fully defined' error cases on both paths). A covers the flag and polymorphic paths in one parametrized test, the error path via the unbuildable test, and the forward-ref path. Both would fail before and pass after.

Scope: A touches more files (moves `py_get_attrs` to `tools.rs`, adds a `Protocol` type in `_mock_val_ser.py`, and adds an unrelated xfail test in `test_construction.py`). The xfail test is minor churn; the rest is in service of the namespace fix. B is leaner and uses pyo3's `getattr_opt` directly, which is slightly cleaner than A's moved helper. These are small craft points and do not outweigh A's more correct handling of namespace resolution during a Rust-triggered rebuild.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

8m 49s

Wall-clock time in the container

Full test suite

No new failures

1,314 passed · 127 skipped · 1,441 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

147vs 202 merged

Changed lines, ours vs merged

Initial 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 MockValSer errors 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:

  1. The function downcasts the attribute value to SchemaSerializer as before.
  2. If the downcast fails, the function calls the rebuild() method of the mock object.
  3. The function then uses the serializer that rebuild() returns.
  4. 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.5

The two patches

Our patch+140 −7
pydantic-core/src/serializers/infer.rsindex a99b22ba..e91c0a25 100644@@ -663,7 +663,20 @@ 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)+    let cast_err: PyErr = match py_serializer.cast_exact::<SchemaSerializer>() {+        Ok(serializer) => return Ok(serializer.clone()),+        Err(err) => err.into(),+    };+    // The serializer may be a `MockValSer` (e.g. for a model with `defer_build=True` which has+    // not been built yet). Its lazy rebuild hook is not triggered by a downcast, so explicitly+    // call `rebuild()` and use the serializer it returns.+    if let Some(rebuild) = py_serializer.getattr_opt(intern!(py, "rebuild"))? {+        let rebuilt = rebuild.call0()?;+        if !rebuilt.is_none() {+            return rebuilt.cast_into_exact().map_err(Into::into);+        }+    }+    Err(cast_err) }  /// Serialize `value` as if it had a `__pydantic_serializer__` attribute@@ -674,9 +687,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..03056876 100644@@ -1,6 +1,6 @@ use std::{borrow::Cow, sync::Arc}; -use pyo3::{prelude::*, types::PyType};+use pyo3::{intern, prelude::*, types::PyType};  use crate::serializers::{     CombinedSerializer, SerializationState,@@ -50,8 +50,9 @@ 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)+            && value.hasattr(intern!(value.py(), "__pydantic_serializer__"))?         {+            let serializer = get_pydantic_serializer(value)?;             call_pydantic_serializer(&serializer, value, state, do_serialize)         } else {             do_serialize.serialize_no_infer(&self.serializer, value, state)tests/test_serialize_as_any.pyindex 2bf6091c..89cf860d 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,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']+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_annotation_with_deferred_subclass(mode: str) -> None:+    """https://github.com/pydantic/pydantic/issues/13647"""++    class Child(BaseModel):+        model_config = ConfigDict(defer_build=True)+        x: int = 1++    class Sub(Child):+        y: int = 2++    class Parent(BaseModel):+        content: SerializeAsAny[Child] | None = None++    parent = Parent.model_construct(content=Sub.model_construct(x=1, y=2))+    assert Sub.__pydantic_complete__ is False++    if mode == 'json':+        assert parent.model_dump_json() == '{"content":{"x":1,"y":2}}'+    else:+        assert parent.model_dump() == {'content': {'x': 1, 'y': 2}}+    assert Sub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_flag_with_deferred_subclass(mode: str) -> None:+    class Child(BaseModel):+        model_config = ConfigDict(defer_build=True)+        x: int = 1++    class Sub(Child):+        y: int = 2++    class Parent(BaseModel):+        content: Child++    parent = Parent.model_construct(content=Sub.model_construct(x=1, y=2))+    assert Sub.__pydantic_complete__ is False++    if mode == 'json':+        assert 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 Sub.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_serialize_as_any_annotation_with_deferred_subclass_not_fully_defined(mode: str) -> None:+    class Child(BaseModel):+        model_config = ConfigDict(defer_build=True)+        x: int = 1++    class Sub(Child):+        y: 'Undefined'  # noqa: F821++    class Parent(BaseModel):+        content: SerializeAsAny[Child]++    parent = Parent.model_construct(content=Sub.model_construct(x=1, y=2))++    if mode == 'json':+        with pytest.raises(PydanticSerializationError, match='PydanticUserError: `Sub` is not fully defined'):+            parent.model_dump_json()+    else:+        with pytest.raises(PydanticUserError, match='`Sub` is not fully defined'):+            parent.model_dump()tests/types/test_model.pyindex 9cf2bb08..84b85ff0 100644@@ -1,8 +1,10 @@ import pytest+from pydantic_core import PydanticSerializationError  from pydantic import (     BaseModel,     ConfigDict,+    PydanticUserError,     SerializationInfo,     TypeAdapter,     model_serializer,@@ -39,6 +41,55 @@ def test_polymorphic_serialization(config: bool | None, runtime: bool | None) ->         assert serializer.to_json(ModelB(a=123, b='test'), **kwargs) == b'{"a":123}'  +@pytest.mark.parametrize('mode', ['python', 'json'])+def test_polymorphic_serialization_with_deferred_subclass(mode: str) -> None:+    """https://github.com/pydantic/pydantic/issues/13647"""++    class ModelA(BaseModel):+        model_config = ConfigDict(defer_build=True, polymorphic_serialization=True)++        a: int++    class ModelB(ModelA):+        b: str++    class Parent(BaseModel):+        content: ModelA++    parent = Parent.model_construct(content=ModelB.model_construct(a=123, b='test'))+    assert ModelB.__pydantic_complete__ is False++    if mode == 'json':+        assert parent.model_dump_json() == '{"content":{"a":123,"b":"test"}}'+    else:+        assert parent.model_dump() == {'content': {'a': 123, 'b': 'test'}}+    assert ModelB.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_polymorphic_serialization_with_deferred_subclass_not_fully_defined(mode: str) -> None:+    class ModelA(BaseModel):+        model_config = ConfigDict(defer_build=True, polymorphic_serialization=True)++        a: int++    class ModelB(ModelA):+        b: 'Undefined'  # noqa: F821++    class Parent(BaseModel):+        content: ModelA++    parent = Parent.model_construct(content=ModelB.model_construct(a=123, b='test'))++    # the subclass fields must not be silently dropped by falling back to the parent serializer+    if mode == 'json':+        with pytest.raises(PydanticSerializationError, match='PydanticUserError: `ModelB` is not fully defined'):+            parent.model_dump_json()+    else:+        with pytest.raises(PydanticUserError, match='`ModelB` is not fully defined'):+            parent.model_dump()++ @pytest.mark.parametrize('config', [True, False, None]) @pytest.mark.parametrize('runtime', [True, False, None]) def test_polymorphic_serialization_with_model_serializer(config: bool, runtime: bool) -> None: 
Merged fix · PR #13922+159 −43
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