#13681·pydantic

Independently rebuild nested models when used within other core schema generation contexts

Author: ViicosCreated Aug 18, 2026Updated Sep 28, 2026
Labelstopic-performance

https://github.com/pydantic/pydantic/pull/11388 refactored how fields (in particular incomplete fields) were handled during core schema generation. It fixed a class of issues where FieldInfo instances of a model referenced by another model were wrongly mutated:

python
class Sub(BaseModel):
    f: 'Forward'

# Sub.f is incomplete

class Main(BaseModel):
    sub: Sub

# When building `Main`, building field `sub` would mutate the `FieldInfo` instance
# of `Sub.f`, leading to all kind of issues.

# Sub.f is complete

This is no longer the case today. When encountering an incomplete sub model (e.g. Sub in our example), we independently re-collect model fields without altering anything on Sub:

https://github.com/pydantic/pydantic/blob/59af43ad35d6b69534e7d18230ee87189320bac4/pydantic/_internal/_generate_schema.py#L835-L862

And https://github.com/pydantic/pydantic/pull/11388 states:

On important thing to acknowledge: when encountering sub: Sub, we don't call Sub.model_rebuild(). Doing so might be the right thing to do, but is unfortunately not backwards compatible. The reason is that the NS Resolver used for Model might contain annotations (e.g. provided through the parent_namespace) that should be available for Sub. This means that even if sub: Sub successfully builds, Sub isn't complete yet — each model should be rebuilt independently, through model_rebuild()).

This backwards compatibility edge case is covered in this test:

https://github.com/pydantic/pydantic/blob/d6e2021f761fc6bd53bd955a9cc3916cc5d0bfe6/tests/test_forward_ref.py#L1196-L1224

However, this is a missed opportunity, in particular when using defer_build. Most of the time, it is perfectly fine to have Sub being rebuilt, without risks of polluting namespace resolution:

python
class Sub(BaseModel, defer_build=True):
    f: int

class Main1(BaseModel):
    sub: Sub

# At this point, Sub is still incomplete

class Main2(BaseModel):
    sub: Sub

# At this point, Sub is still incomplete too,
# and the building process of Sub was done twice

In particular, this means prebuilt validator/serializer reuse (introduced in https://github.com/pydantic/pydantic-core/pull/1616) wont work here. Measured on https://github.com/Kludex/httpx2-k8s, this goes from ~24MB to 5MB.