Backtestspydanticrun-20261007-130130#11862
Cannot use model_dump(include=...) with @model_serializer (raises PydanticOmit)
Better
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Patch A fixes the root cause. It addresses the common pattern `handler(value, info)`, which the repo's own `WrapSerializer` docstring currently demonstrates. When a forwarded `SerializationInfo` was passed as the positional `index_key`, it reached `key_filter` under include/exclude, failed to match any key, and caused `PydanticOmit`. Patch A filters out `SerializationInfo` instances before index/key filtering, so the issue's exact example now returns `{'bar': 123}`. It also widens the `SerializerFunctionWrapHandler` protocol type so this usage type-checks. Its tests would fail before the change and pass after it. They cover the core-level wrap serializer, the issue's `model_serializer` scenario (include, exclude, python, json), and nested `WrapSerializer`/`field_serializer` cases. Patch B does not make the issue's code work. Passing `info` would now raise a `TypeError` ('index_key is expected to be an integer or a string') instead of `PydanticOmit`. That is a clearer error, but the user's example still fails. Patch B also rewrites the docstring example to stop forwarding `info`, which implicitly declares the pattern unsupported, even though the codebase previously documented it and users rely on it. Its single test only checks the new error with a bytes key and never exercises the reported scenario. On correctness, which is the top criterion, A resolves the issue and B only improves the failure message. A also has stronger tests and a minimal, well-commented change.
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
7m 56s
Wall-clock time in the container
Full test suite
No new failures
12,320 passed · 499 skipped · 12,819 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
80vs 80 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
Attempting to use the include parameter to model_dump when the model has a @model_serializer method causes a PydanticOmit exception to be returned.
Example Code
from pydantic import BaseModel, model_serializer
class Foo(BaseModel):
bar:int
baz:int
@model_serializer(mode='wrap')
def _serialize(self, next_serializer, info):
return next_serializer(self, info)
f = Foo(bar=123, baz=456)
print(f.model_dump(include={'bar'}))
Output:
Traceback (most recent call last):
File "/home/phemmer/.config/JetBrains/PyCharm2025.1/scratches/scratch_12.py", line 9, in _serialize
return next_serializer(self, info)
pydantic_core._pydantic_core.PydanticOmit: PydanticOmit()
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/phemmer/.config/JetBrains/PyCharm2025.1/scratches/scratch_12.py", line 13, in <module>
print(f.model_dump(include={'bar'}))
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/home/phemmer/.local/lib/python3.13/site-packages/pydantic/main.py", line 463, in model_dump
return self.__pydantic_serializer__.to_python(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
self,
^^^^^
...<11 lines>...
serialize_as_any=serialize_as_any,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
pydantic_core._pydantic_core.PydanticSerializationError: Error calling function `_serialize`: PydanticOmit: PydanticOmit()
Python, Pydantic & OS Version
pydantic version: 2.11.4
pydantic-core version: 2.33.2
pydantic-core build: profile=release pgo=false
python version: 3.13.2 (main, Feb 4 2025, 00:00:00) [GCC 14.2.1 20240912 (Red Hat 14.2.1-3)]
platform: Linux-6.10.4-200.fc40.x86_64-x86_64-with-glibc2.39
related packages: typing_extensions-4.12.2 pydantic-settings-2.8.1 fastapi-0.115.9
commit: unknownThe two patches
Our patch+79 −1
pydantic-core/python/pydantic_core/core_schema.pyindex 85f6a8c0..9edf5c47 100644@@ -352,7 +352,7 @@ def plain_serializer_function_ser_schema( class SerializerFunctionWrapHandler(Protocol): # pragma: no cover- def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ...+ def __call__(self, input_value: Any, index_key: int | str | SerializationInfo[Any] | None = None, /) -> Any: ... # (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Anypydantic-core/src/serializers/type_serializers/function.rsindex 705c1e12..03a73cc2 100644@@ -473,6 +473,11 @@ impl SerializationCallable { let state = &mut self.extra_owned.to_state(py); + // A common pattern is `handler(value, info)`, forwarding the `SerializationInfo` received by the+ // wrap serializer. The info is not an index or key, so it must not be used for include/exclude+ // filtering (which would otherwise omit the value whenever `include`/`exclude` is set).+ let index_key = index_key.filter(|k| !k.is_instance_of::<SerializationInfo>());+ if let Some(index_key) = index_key { let filter = if let Ok(index) = index_key.extract::<usize>() { self.filter.index_filter(index, state, None)?pydantic-core/tests/serializers/test_functions.pyindex b6bd900e..18993655 100644@@ -358,6 +358,38 @@ def test_function_wrap(): assert s.to_json('foo') == b'"result=3 repr=SerializationCallable(serializer=int)"' +def test_function_wrap_info_forwarded_to_handler_include_exclude():+ """Forwarding `info` to the handler must not be treated as an include/exclude index key."""++ class BasicModel:+ def __init__(self, **kwargs):+ for key, value in kwargs.items():+ setattr(self, key, value)++ def f(value, serializer, info):+ return serializer(value, info)++ s = SchemaSerializer(+ core_schema.model_schema(+ BasicModel,+ core_schema.model_fields_schema(+ {+ 'a': core_schema.model_field(core_schema.int_schema()),+ 'b': core_schema.model_field(core_schema.int_schema()),+ }+ ),+ serialization=core_schema.wrap_serializer_function_ser_schema(f, info_arg=True),+ )+ )+ m = BasicModel(a=1, b=2)+ assert s.to_python(m) == {'a': 1, 'b': 2}+ assert s.to_python(m, include={'a'}) == {'a': 1}+ assert s.to_python(m, exclude={'a'}) == {'b': 2}+ assert s.to_python(m, include={'a'}, mode='json') == {'a': 1}+ assert s.to_json(m, include={'a'}) == b'{"a":1}'+ assert s.to_json(m, exclude={'a'}) == b'{"b":2}'++ def test_function_wrap_return_scheam(): def f(value, serializer): if value == 42:tests/test_serialize.pyindex b55e49d7..b1fc3abd 100644@@ -513,6 +513,47 @@ def test_model_serializer_wrap_info(): assert m.model_dump_json(exclude={'a'}) == '{"b":"boom","info":"mode=json exclude={\'a\'}"}' +def test_model_serializer_wrap_info_forwarded_to_handler_include_exclude():+ class MyModel(BaseModel):+ a: int+ b: int++ @model_serializer(mode='wrap')+ def _serialize(self, handler, info: SerializationInfo):+ return handler(self, info)++ m = MyModel(a=123, b=456)+ assert m.model_dump() == {'a': 123, 'b': 456}+ assert m.model_dump(include={'a'}) == {'a': 123}+ assert m.model_dump(exclude={'a'}) == {'b': 456}+ assert m.model_dump(mode='json', include={'a'}) == {'a': 123}+ assert m.model_dump_json(include={'a'}) == '{"a":123}'+ assert m.model_dump_json(exclude={'a'}) == '{"b":456}'+++def test_wrap_serializer_info_forwarded_to_handler_nested_include():+ class Inner(BaseModel):+ x: int+ y: int++ def ser(value: Any, handler: SerializerFunctionWrapHandler, info: SerializationInfo) -> Any:+ return handler(value, info)++ class Outer(BaseModel):+ inner: Annotated[Inner, WrapSerializer(ser)]+ other: int++ @field_serializer('other', mode='wrap')+ def _ser_other(self, value: int, handler: SerializerFunctionWrapHandler, info: SerializationInfo) -> Any:+ return handler(value, info)++ m = Outer(inner=Inner(x=1, y=2), other=3)+ assert m.model_dump() == {'inner': {'x': 1, 'y': 2}, 'other': 3}+ assert m.model_dump(include={'inner': {'x'}, 'other': True}) == {'inner': {'x': 1}, 'other': 3}+ assert m.model_dump(exclude={'inner': {'x'}}) == {'inner': {'y': 2}, 'other': 3}+ assert m.model_dump_json(include={'inner': {'y'}}) == '{"inner":{"y":2}}'++ def test_model_serializer_plain_json_return_type(): class MyModel(BaseModel): a: int
Merged fix · PR #13506+47 −33
pydantic-core/src/serializers/type_serializers/function.rsindex 705c1e129..5944310cc 100644@@ -2,20 +2,20 @@ use std::borrow::Cow; use std::sync::Arc; use pyo3::PyTraverseError;-use pyo3::exceptions::{PyAttributeError, PyRecursionError, PyRuntimeError};+use pyo3::exceptions::{PyAttributeError, PyRecursionError, PyRuntimeError, PyTypeError}; use pyo3::gc::PyVisit; use pyo3::intern; use pyo3::prelude::*; use pyo3::types::PyDict; -use pyo3::types::PyString;+use pyo3::types::{PyInt, PyString}; use crate::definitions::DefinitionsBuilder; use crate::py_gc::PyGcTraverse; use crate::serializers::SerializationState; use crate::serializers::extra::IncludeExclude; use crate::tools::SchemaDict;-use crate::tools::{function_name, py_err, py_error_type};+use crate::tools::{function_name, py_err, py_error_type, safe_repr}; use crate::{PydanticOmit, PydanticSerializationUnexpectedValue}; use super::format::WhenUsed;@@ -476,8 +476,13 @@ impl SerializationCallable { if let Some(index_key) = index_key { let filter = if let Ok(index) = index_key.extract::<usize>() { self.filter.index_filter(index, state, None)?- } else {+ } else if index_key.is_instance_of::<PyString>() || index_key.is_instance_of::<PyInt>() { self.filter.key_filter(index_key, state)?+ } else {+ return Err(PyTypeError::new_err(format!(+ "'index_key' is expected to be an integer or a string, got '{}'",+ safe_repr(index_key),+ ))); }; if let Some(next_include_exclude) = filter { let state = &mut state.scoped_include_exclude(next_include_exclude);pydantic/functional_serializers.pyindex 662a8c3a4..aad3a8b8d 100644@@ -97,50 +97,41 @@ class WrapSerializer: from datetime import datetime, timezone from typing import Annotated, Any - from pydantic import BaseModel, WrapSerializer-- class EventDatetime(BaseModel):- start: datetime- end: datetime+ from pydantic import (+ BaseModel,+ SerializationInfo,+ SerializerFunctionWrapHandler,+ WrapSerializer,+ ) - def convert_to_utc(value: Any, handler, info) -> dict[str, datetime]:+ def convert_to_utc(+ value: Any, handler: SerializerFunctionWrapHandler, info: SerializationInfo+ ): # Note that `handler` can actually help serialize the `value` for # further custom serialization in case it's a subclass.- partial_result = handler(value, info)+ serialized = handler(value) if info.mode == 'json':- return {- k: datetime.fromisoformat(v).astimezone(timezone.utc)- for k, v in partial_result.items()- }- return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()}+ return datetime.fromisoformat(serialized).astimezone(timezone.utc)+ else:+ return serialized.astimezone(timezone.utc) - UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)]+ UTCDatetime = Annotated[datetime, WrapSerializer(convert_to_utc)] class EventModel(BaseModel):- event_datetime: UTCEventDatetime+ event_datetime: UTCDatetime - dt = EventDatetime(- start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00'- )- event = EventModel(event_datetime=dt)+ event = EventModel(event_datetime='2024-01-01T07:00:00-08:00') print(event.model_dump()) ''' {- 'event_datetime': {- 'start': datetime.datetime(- 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc- ),- 'end': datetime.datetime(- 2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc- ),- }+ 'event_datetime': datetime.datetime(+ 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc+ ) } ''' print(event.model_dump_json())- '''- {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}}- '''+ #> {"event_datetime":"2024-01-01T15:00:00Z"} ``` Attributes:tests/test_serialize.pyindex b55e49d72..57832ca0a 100644@@ -1419,3 +1419,21 @@ def test_serialization_info_properties() -> None: 'round_trip', ): assert getattr(m.model_dump(**{property: True})['f'], property) is True, f'{property!r} check failed'+++def test_model_serializer_index_key_type_error() -> None:+ """https://github.com/pydantic/pydantic/issues/11862"""++ class Model(BaseModel):+ f: int++ @model_serializer(mode='wrap')+ def _serialize(self, handler: SerializerFunctionWrapHandler):+ return handler(self, b'not_a_valid_type_for_index_key')++ m = Model(f=1)+ with pytest.raises(+ PydanticSerializationError,+ match="Error calling function `_serialize`: TypeError: 'index_key' is expected to be an integer or a string, got 'b'not_a_valid_type_for_index_key''",+ ):+ m.model_dump(include={'f'})