Backtestspydanticrun-20261002-175417#13601
model_dump(exclude=...) is silently ignored in python mode when a wrap model_serializer is gated with when_used="json"
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches find the same root cause. In function.rs, the shared tail of to_python/json_key/serde_serialize always wrapped the state in `scoped_include_exclude(IncludeExclude::empty())`. That was true even when `call` returned `(false, v)`, meaning the function was skipped because of `when_used` and the fallback serializer should run instead. As a result the fallback model serializer never saw the caller's include/exclude in python mode. Both patches fix this the same way: they clear include/exclude only when the function actually ran, and pass it through unchanged to the fallback otherwise. Patch A does this by splitting the match arms and passing `state` directly to the fallback. Patch B keeps the original shape and re-scopes with a cloned copy via a new `SerializationState::include_exclude()` accessor. The two are semantically equivalent across all three methods. B's diff is a bit smaller and stays closer to the existing structure, at the cost of a new accessor and a redundant clone and re-scope. A's restructure is still clear and well commented. On correctness and scope they are effectively tied. The difference is in the tests. Patch A parametrizes over both `json` and `json-unless-none` (the issue names both). It uses the issue's exact wrap pattern (`return handler(self)`), checks both include and exclude in python mode, checks JSON mode, and checks `model_dump_json`. It also adds a plain `when_used='json'` model-serializer test and a nested field_serializer test (plain and wrap) with nested include/exclude. That last test exercises the same function-serializer code path in a different context, and would fail before the fix. Patch B's test covers plain and wrap in python mode for `when_used='json'` only. Its wrap serializer returns a constant instead of calling the handler, so it does not mirror the reported scenario. It also skips `json-unless-none` and the field-serializer path. Both sets of tests would fail before the fix and pass after, but A's are broader and closer to the issue's scenarios, so A wins on the tests criterion.
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
15m 32s
Wall-clock time in the container
Full test suite
No new failures
12,402 passed · 501 skipped · 12,903 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
128vs 59 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
When a model declares @model_serializer(mode="wrap") with when_used="json" (or "json-unless-none"), the runtime exclude argument passed to model_dump() is silently ignored in python mode. The same call in JSON mode behaves correctly.
Expected: model_dump(exclude={"b"}) omits b regardless of when_used, since the gate concerns which serializer runs and not which fields the caller asked to drop.
Actual: b is present in python mode.
Example Code
from pydantic import BaseModel, SerializerFunctionWrapHandler, model_serializer
class Gated(BaseModel):
a: int
b: int
@model_serializer(mode="wrap", when_used="json")
def _serialize(self, handler: SerializerFunctionWrapHandler) -> object:
return handler(self)
class Always(BaseModel):
a: int
b: int
@model_serializer(mode="wrap")
def _serialize(self, handler: SerializerFunctionWrapHandler) -> object:
return handler(self)
# Gated to JSON: python mode ignores exclude.
print(Gated(a=1, b=2).model_dump(exclude={"b"})) # {'a': 1, 'b': 2} <-- expected {'a': 1}
print(Gated(a=1, b=2).model_dump(mode="json", exclude={"b"})) # {'a': 1} <-- correct
# Identical model without the gate: python mode honours exclude.
print(Always(a=1, b=2).model_dump(exclude={"b"})) # {'a': 1}
Output:
gated python: {'a': 1, 'b': 2}
gated json : {'a': 1}
always python: {'a': 1}
Python, Pydantic & OS Version
pydantic version: 2.13.2
pydantic-core version: 2.46.2
pydantic-core build: profile=release pgo=false
python version: 3.13.12 (main, Mar 25 2026, 02:48:22) [Clang 22.1.1 ]
platform: macOS-26.6-arm64-arm-64bit-Mach-O
related packages: mypy-2.1.0 typing_extensions-4.15.0
Reproducible in 2.13.3 and 2.13.4 as well.
The two patches
pydantic-core/src/serializers/type_serializers/function.rsindex 5944310c..71c66e60 100644@@ -217,17 +217,24 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> PyResult<Py<PyAny>> { let py = value.py();- let (ret_serializer, v) = match self.call(value, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ match self.call(value, state) {+ Ok((true, v)) => {+ // None for include/exclude here, as filtering should be done+ // by the function (or its handler)+ let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ self.return_serializer.to_python(v.bind(py), state)+ }+ // the function was not used (`when_used`), so the fallback serializer+ // must apply include/exclude itself+ Ok((false, v)) => {+ let fallback = self.get_fallback_serializer();+ fallback.to_python(v.bind(py), state)+ } Err(err) => { on_error(py, err, &self.function_name, state)?;- return infer_to_python(value, state);+ infer_to_python(value, state) }- };- // None for include/exclude here, as filtering should be done- let state = &mut state.scoped_include_exclude(IncludeExclude::empty());- ret_serializer.to_python(v.bind(py), state)+ } } fn json_key<'a, 'py>(@@ -236,19 +243,25 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> PyResult<Cow<'a, str>> { let py = key.py();- let (ret_serializer, v) = match self.call(key, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ let key_str = match self.call(key, state) {+ Ok((true, v)) => {+ // None for include/exclude here, as filtering should be done+ // by the function (or its handler)+ let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ self.return_serializer.json_key(v.bind(py), state)?.into_owned()+ }+ // the function was not used (`when_used`), so the fallback serializer+ // must apply include/exclude itself+ Ok((false, v)) => {+ let fallback = self.get_fallback_serializer();+ fallback.json_key(v.bind(py), state)?.into_owned()+ } Err(err) => { on_error(py, err, &self.function_name, state)?; return infer_json_key(key, state); } };- // None for include/exclude here, as filtering should be done- let state = &mut state.scoped_include_exclude(IncludeExclude::empty());- ret_serializer- .json_key(v.bind(py), state)- .map(|cow| Cow::Owned(cow.into_owned()))+ Ok(Cow::Owned(key_str)) } fn serde_serialize<'py, S: serde::ser::Serializer>(@@ -258,17 +271,24 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> Result<S::Ok, S::Error> { let py = value.py();- let (ret_serializer, v) = match self.call(value, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ match self.call(value, state) {+ Ok((true, v)) => {+ // None for include/exclude here, as filtering should be done+ // by the function (or its handler)+ let mut state = state.scoped_include_exclude(IncludeExclude::empty());+ self.return_serializer.serde_serialize(v.bind(py), serializer, &mut state)+ }+ // the function was not used (`when_used`), so the fallback serializer+ // must apply include/exclude itself+ Ok((false, v)) => {+ let fallback = self.get_fallback_serializer();+ fallback.serde_serialize(v.bind(py), serializer, state)+ } Err(err) => { on_error(py, err, &self.function_name, state).map_err(py_err_se_err)?;- return infer_serialize(value, serializer, state);+ infer_serialize(value, serializer, state) }- };- // None for include/exclude here, as filtering should be done- let mut state = state.scoped_include_exclude(IncludeExclude::empty());- ret_serializer.serde_serialize(v.bind(py), serializer, &mut state)+ } } fn get_name(&self) -> &str {tests/test_serialize.pyindex 57832ca0..ecc489c2 100644@@ -513,6 +513,66 @@ def test_model_serializer_wrap_info(): assert m.model_dump_json(exclude={'a'}) == '{"b":"boom","info":"mode=json exclude={\'a\'}"}' +@pytest.mark.parametrize('when_used', ['json', 'json-unless-none'])+def test_model_serializer_wrap_when_used_json_include_exclude(when_used) -> None:+ class Model(BaseModel):+ a: int+ b: int++ @model_serializer(mode='wrap', when_used=when_used)+ def _serialize(self, handler: SerializerFunctionWrapHandler) -> object:+ return handler(self)++ m = Model(a=1, b=2)+ assert m.model_dump(exclude={'b'}) == {'a': 1}+ assert m.model_dump(include={'a'}) == {'a': 1}+ assert m.model_dump(mode='json', exclude={'b'}) == {'a': 1}+ assert m.model_dump(mode='json', include={'a'}) == {'a': 1}+ assert m.model_dump_json(exclude={'b'}) == '{"a":1}'+++def test_model_serializer_plain_when_used_json_include_exclude() -> None:+ class Model(BaseModel):+ a: int+ b: int++ @model_serializer(when_used='json')+ def _serialize(self) -> str:+ return f'Model(a={self.a}, b={self.b})'++ m = Model(a=1, b=2)+ # the serializer is not used in python mode, so the default model serialization must honour include/exclude+ assert m.model_dump(exclude={'b'}) == {'a': 1}+ assert m.model_dump(include={'a'}) == {'a': 1}+ assert m.model_dump(mode='json', exclude={'b'}) == 'Model(a=1, b=2)'+++@pytest.mark.parametrize('mode', ['plain', 'wrap'])+def test_field_serializer_when_used_json_nested_include_exclude(mode) -> None:+ class Inner(BaseModel):+ x: int+ y: int++ class Outer(BaseModel):+ inner: Inner++ if mode == 'plain':++ @field_serializer('inner', when_used='json')+ def _ser_inner(self, value: Inner) -> dict[str, int]:+ return {'x': value.x, 'y': value.y}++ else:++ @field_serializer('inner', mode='wrap', when_used='json')+ def _ser_inner(self, value: Inner, handler: SerializerFunctionWrapHandler) -> object:+ return handler(value)++ m = Outer(inner=Inner(x=1, y=2))+ assert m.model_dump(exclude={'inner': {'y'}}) == {'inner': {'x': 1}}+ assert m.model_dump(include={'inner': {'x'}}) == {'inner': {'x': 1}}++ def test_model_serializer_plain_json_return_type(): class MyModel(BaseModel): a: int
pydantic-core/src/serializers/extra.rsindex e54b05732..1551057bc 100644@@ -146,6 +146,10 @@ impl<'py> SerializationState<'py> { self.field_name.as_ref() } + pub fn include_exclude(&self) -> IncludeExclude<'py> {+ self.include_exclude.clone()+ }+ pub fn include(&self) -> Option<&Bound<'py, PyAny>> { self.include_exclude.include.as_ref() }pydantic-core/src/serializers/type_serializers/function.rsindex 5944310cc..736763775 100644@@ -217,16 +217,16 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> PyResult<Py<PyAny>> { let py = value.py();- let (ret_serializer, v) = match self.call(value, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ let (ret_serializer, v, include_exclude) = match self.call(value, state) {+ // Filtering was done by the function, so drop include/exclude for the return serializer:+ Ok((true, v)) => (&*self.return_serializer, v, IncludeExclude::empty()),+ Ok((false, v)) => (self.get_fallback_serializer(), v, state.include_exclude()), Err(err) => { on_error(py, err, &self.function_name, state)?; return infer_to_python(value, state); } };- // None for include/exclude here, as filtering should be done- let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ let state = &mut state.scoped_include_exclude(include_exclude); ret_serializer.to_python(v.bind(py), state) } @@ -236,16 +236,16 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> PyResult<Cow<'a, str>> { let py = key.py();- let (ret_serializer, v) = match self.call(key, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ let (ret_serializer, v, include_exclude) = match self.call(key, state) {+ // Filtering was done by the function, so drop include/exclude for the return serializer:+ Ok((true, v)) => (&*self.return_serializer, v, IncludeExclude::empty()),+ Ok((false, v)) => (self.get_fallback_serializer(), v, state.include_exclude()), Err(err) => { on_error(py, err, &self.function_name, state)?; return infer_json_key(key, state); } };- // None for include/exclude here, as filtering should be done- let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ let state = &mut state.scoped_include_exclude(include_exclude); ret_serializer .json_key(v.bind(py), state) .map(|cow| Cow::Owned(cow.into_owned()))@@ -258,16 +258,16 @@ macro_rules! function_type_serializer { state: &mut SerializationState<'py>, ) -> Result<S::Ok, S::Error> { let py = value.py();- let (ret_serializer, v) = match self.call(value, state) {- Ok((true, v)) => (&*self.return_serializer, v),- Ok((false, v)) => (self.get_fallback_serializer(), v),+ let (ret_serializer, v, include_exclude) = match self.call(value, state) {+ // Filtering was done by the function, so drop include/exclude for the return serializer:+ Ok((true, v)) => (&*self.return_serializer, v, IncludeExclude::empty()),+ Ok((false, v)) => (self.get_fallback_serializer(), v, state.include_exclude()), Err(err) => { on_error(py, err, &self.function_name, state).map_err(py_err_se_err)?; return infer_serialize(value, serializer, state); } };- // None for include/exclude here, as filtering should be done- let mut state = state.scoped_include_exclude(IncludeExclude::empty());+ let mut state = state.scoped_include_exclude(include_exclude); ret_serializer.serde_serialize(v.bind(py), serializer, &mut state) } tests/test_serialize.pyindex 57832ca0a..1c9e8cb7b 100644@@ -1437,3 +1437,28 @@ def test_model_serializer_index_key_type_error() -> None: 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'})+++def test_model_serializer_when_used_fallback_respects_include_exclude() -> None:+ """https://github.com/pydantic/pydantic/issues/13601"""++ class Plain(BaseModel):+ a: int+ b: int++ @model_serializer(mode='plain', when_used='json')+ def _serialize(self) -> Any:+ return {'ser': True}++ class Wrap(BaseModel):+ a: int+ b: int++ @model_serializer(mode='wrap', when_used='json')+ def _serialize(self, handler: SerializerFunctionWrapHandler) -> Any:+ return {'ser': True}++ for m in (Plain(a=1, b=2), Wrap(a=1, b=2)):+ assert m.model_dump(exclude={'b'}) == {'a': 1}+ assert m.model_dump(include={'a'}) == {'a': 1}+ assert m.model_dump(mode='json', exclude={'b'}) == {'ser': True}