Backtestspydanticrun-20261009-110034#13647

Issue #13647 Merged fix PR #13922 Run 9 Oct 2026 · run-20261009-110034 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 A = our agent, Patch B = the merged fix.

Both patches fix the root cause in the same place. They change `get_pydantic_serializer` in `infer.rs` to call `MockValSer.rebuild()` when the attribute is not a real `SchemaSerializer`, and they route `serialize_pydantic_serializable` through that helper. That repairs the `SerializeAsAny`, `serialize_as_any=True`, `Any` inference and polymorphic paths. On the issue's main scenario the two are equivalent.

B is better on correctness at the edges.

1. **Frame namespace.** A calls `rebuild()` with no arguments, so the rebuild runs with the default `_parent_namespace_depth=5`. When the call comes from Rust in the middle of serialization, depth 5 points at an arbitrary frame in the caller's stack. Forward references could then resolve silently against an unrelated namespace. 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 exactly this case: a local `Undefined` in the caller must not be used, and the model must stay incomplete.

2. **Error swallowing in the polymorphic path.** `PolymorphismTrampoline` still uses `let Ok(serializer) = get_pydantic_serializer(value)` under A. Any rebuild error, such as an undefined forward ref, is swallowed there, and serialization silently falls back to the parent serializer. B changes the helper to return `Option`, with `None` only when the attribute is missing (stdlib dataclasses). It then uses `?` in the trampoline, so real rebuild errors surface instead of producing silently wrong output.

3. **`rebuild()` returning `None`.** B also handles this case explicitly.

**Tests.** A has solid tests for the issue's scenario across four paths in both python and json modes. B covers `serialize_as_any` and polymorphic deferred subclasses, an incomplete model with forward refs rebuilt via `Any` inference, and the namespace-isolation case. B's xfail `model_construct` test and the move of `py_get_attrs` into `tools.rs` are neutral scope extras.

**Risk.** B touches the Python mock signatures, which adds some risk, but the change is coherent and defaults keep current behavior.

Overall, B fixes the issue more robustly and avoids the wrong-namespace and silent-fallback pitfalls left in A.

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

8m 31s

Wall-clock time in the container

Full test suite

No new failures

12,930 passed · 527 skipped · 13,457 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

107vs 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+104 −3
pydantic-core/src/serializers/infer.rsindex a99b22ba..dd671afc 100644@@ -660,9 +660,19 @@ pub(crate) fn infer_json_key_known<'a, 'py>(     } } +/// Get the `SchemaSerializer` from the `__pydantic_serializer__` attribute of `value`.+///+/// If the attribute is not a `SchemaSerializer` (e.g. a `MockValSer` on a model with `defer_build=True`+/// which hasn't been built yet), its `rebuild()` method is called to obtain the actual serializer. 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__"))?;+    if !py_serializer.is_exact_instance_of::<SchemaSerializer>() {+        let rebuild = intern!(py, "rebuild");+        if py_serializer.hasattr(rebuild)? {+            return py_serializer.call_method0(rebuild)?.cast_into_exact().map_err(Into::into);+        }+    }     py_serializer.cast_into_exact().map_err(Into::into) } @@ -674,9 +684,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>(tests/test_serialize_as_any.pyindex 2bf6091c..b8648994 100644@@ -1,4 +1,5 @@ import json+from typing import Any, Literal, Optional  import pytest from typing_extensions import TypedDict@@ -209,3 +210,94 @@ 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: Literal['python', 'json']) -> None:+    """https://github.com/pydantic/pydantic/issues/12282: serializing an instance of a deferred model+    which was never built (so `__pydantic_serializer__` is still a `MockValSer`) should build it."""++    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++    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: Literal['python', 'json']) -> 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_any_field_with_deferred_model(mode: Literal['python', 'json']) -> None:+    class Deferred(BaseModel):+        model_config = ConfigDict(defer_build=True)+        x: int = 1++    class Parent(BaseModel):+        content: Any = None++    parent = Parent.model_construct(content=Deferred.model_construct(x=3))+    assert Deferred.__pydantic_complete__ is False++    if mode == 'json':+        assert parent.model_dump_json() == '{"content":{"x":3}}'+    else:+        assert parent.model_dump() == {'content': {'x': 3}}+    assert Deferred.__pydantic_complete__ is True+++@pytest.mark.parametrize('mode', ['python', 'json'])+def test_polymorphic_serialization_with_deferred_subclass(mode: Literal['python', 'json']) -> None:+    """Polymorphic serialization should not silently fall back to the parent serializer+    when the subclass is a deferred model which was never built."""++    class Child(BaseModel):+        model_config = ConfigDict(defer_build=True, polymorphic_serialization=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() == '{"content":{"x":1,"y":2}}'+    else:+        assert parent.model_dump() == {'content': {'x': 1, 'y': 2}}+    assert Sub.__pydantic_complete__ is True 
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