fix: support pydantic 2.13 by invalidating cached model schema#1694
Merged
Conversation
Pydantic 2.13 changed how `TypeAdapter(Annotated[T, FieldInfo(...)])` — FastAPI's response-serializer pattern — resolves nested schemas: it now uses the cached child snapshot instead of walking the live model. As a result, reverse-relation fields that ormar's metaclass adds to related models in `expand_reverse_relationships` were invisible from nested dumps under pydantic 2.13. Invalidate the parent's cached schema by setting `__pydantic_complete__ = False` at the end of the ormar metaclass, so the next access recompiles afresh without the stale snapshot. Make the wrap-serializer fallbacks (forward + reverse relation) defensive against the broader value types (QuerysetProxy, dead weakproxy) that pydantic 2.13 now dispatches them with. Relax the pydantic upper bound so 2.13.x is accepted.
Merging this PR will improve performance by 46.98%
|
| Mode | Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|---|
| ⚡ | WallTime | test_saving_models_individually_with_related_models[10] |
87.5 ms | 59.5 ms | +46.98% |
Tip
Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.
Comparing fix/pydantic-213-defer-build (a23f777) with master (9cd037e)1
Footnotes
Ormar relies on pydantic internals, so the upper bound is capped at <2.14 and must be bumped manually after verifying compatibility with each new release. Refreshes the lock content-hash; resolved versions are unchanged (pydantic stays at 2.12.5).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
__pydantic_complete__ = Falseat the end of ormar's metaclass for non-abstract / non-proxy / non-forward-ref models. Invalidates the cached pydantic core schema so the next access recompiles afresh — picking up the reverse-relation fields thatexpand_reverse_relationshipsadded to related models moments earlier.metaclass.get_serializer, reverse list inadd_field_serializer_for_reverse_relations) defensive against the broader value types (QuerysetProxy, dead weakproxy) that pydantic 2.13 now dispatches them with.pydantic = "^2.11.9"→">=2.11.9,<3.0.0". Unblocks build(deps): bump pydantic from 2.12.5 to 2.13.4 #1660.Root cause
Pydantic 2.13 changed how
TypeAdapter(Annotated[T, FieldInfo(...)])— exactly what FastAPI builds infastapi/_compat.py::ModelField.__post_init__for response serialization — resolves nested schemas. 2.12 walked the live model's fields; 2.13 uses the cached child snapshot. Verified with a pure-pydantic repro: same code, identical forTypeAdapter(T).dump_python(...), but theAnnotated[T, FieldInfo(...)]wrapping diverges between versions.The consequence in ormar:
expand_reverse_relationshipsaddsitemstoCategory.model_fieldsafterItem.__pydantic_core_schema__has already been compiled. StandaloneCategory.model_dump()still includesitems, butItem.model_dump()(and FastAPI's serializer) drop it from the nested category — becauseItem's schema holds a stale snapshot.Invalidating
Item.__pydantic_complete__so pydantic lazily recompiles avoids the regression without the schema-divergence side effects that an eagermodel_rebuild(force=True)triggered (FastAPI splitting the model intoCategory-Input/Category-Output, wrap serializer hittingQuerysetProxyvalues it can't handle, etc.).Test plan
tests/test_fastapi/test_fastapi_usage.py::test_read_mainpasses under pydantic 2.13.4 (was the only failing test on master).make pre-commitclean (ruff format/check + mypy strict).make coverageat 100.00% on the 2.11.9 floor. The one pydantic-2.13-only branch (hasattr(value, "ormar_config")fallback forQuerysetProxy) is marked# pragma: no coverwith a comment, mirroring the existing dialect-specific pragma pattern.