Backtestspydanticrun-20261003-150343#13601

Issue #13601 Merged fix PR #13702 Run 3 Oct 2026 · run-20261003-150343 pydantic/pydantic

model_dump(exclude=...) is silently ignored in python mode when a wrap model_serializer is gated with when_used="json"

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the root cause the same way. In the function serializer's `to_python`, `json_key` and `serde_serialize`, the old code always scoped include/exclude to empty after `self.call`. That is wrong when the function was not called (`Ok((false, v))`, the `when_used` gate fails), because no filtering has happened and the fallback serializer needs the caller's include/exclude. Both patches keep the empty scope for the `Ok((true, v))` branch and pass the original state through on the fallback branch, so they are functionally equivalent on correctness.

Patch A adds a new `include_exclude()` accessor on `SerializationState`. That accessor clones the `IncludeExclude` (Bound refcount bumps) only to re-scope it into the same values, which is a small widening of the API for no real benefit. Patch B restructures each match so the fallback branch uses `state` directly. It touches only `function.rs`, avoids the clone, and its comment explains why the fallback keeps filtering.

The tests separate the two more clearly. Patch A tests plain and wrap model serializers with `when_used='json'` only. Its wrap serializer ignores the handler and returns `{'ser': True}`, which does not mirror the issue's `handler(self)` pattern. Patch B parametrizes over both `'json'` and `'json-unless-none'`, which the issue names explicitly, and over wrap and plain. It uses the issue's exact `handler(self)` shape and checks python mode, json mode and `model_dump_json`. It also covers nested include/exclude through an outer model, which exercises the scoped propagation. Finally, it adds field_serializer cases with index-level include/exclude on lists, which hit the same code path and would fail before the fix. Patch B's tests are the more thorough regression coverage of the reported scenario and its neighbours, and its implementation is slightly leaner.

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 3s

Wall-clock time in the container

Full test suite

No new failures

12,403 passed · 501 skipped · 12,904 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

131vs 59 merged

Changed lines, ours vs merged

Initial 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

Our patch+105 −26
pydantic-core/src/serializers/type_serializers/function.rsindex 5944310c..b481240c 100644@@ -217,17 +217,20 @@ 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+                        let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+                        self.return_serializer.to_python(v.bind(py), state)+                    }+                    // the function was not called, so filtering has not been applied yet:+                    // keep include/exclude for the fallback serializer+                    Ok((false, v)) => self.get_fallback_serializer().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 +239,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),+                match self.call(key, state) {+                    Ok((true, v)) => {+                        // None for include/exclude here, as filtering should be done+                        let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+                        self.return_serializer+                            .json_key(v.bind(py), state)+                            .map(|cow| Cow::Owned(cow.into_owned()))+                    }+                    // the function was not called, so filtering has not been applied yet:+                    // keep include/exclude for the fallback serializer+                    Ok((false, v)) => self+                        .get_fallback_serializer()+                        .json_key(v.bind(py), state)+                        .map(|cow| Cow::Owned(cow.into_owned())),                     Err(err) => {                         on_error(py, err, &self.function_name, state)?;-                        return infer_json_key(key, state);+                        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()))+                }             }              fn serde_serialize<'py, S: serde::ser::Serializer>(@@ -258,17 +267,22 @@ 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+                        let mut state = state.scoped_include_exclude(IncludeExclude::empty());+                        self.return_serializer.serde_serialize(v.bind(py), serializer, &mut state)+                    }+                    // the function was not called, so filtering has not been applied yet:+                    // keep include/exclude for the fallback serializer+                    Ok((false, v)) => self+                        .get_fallback_serializer()+                        .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..10308999 100644@@ -544,6 +544,71 @@ def test_model_serializer_plain_json_return_type():         assert m.model_dump_json() == '666'  +@pytest.mark.parametrize('when_used', ['json', 'json-unless-none'])+@pytest.mark.parametrize('mode', ['wrap', 'plain'])+def test_model_serializer_when_used_json_respects_include_exclude(mode, when_used) -> None:+    """https://github.com/pydantic/pydantic/issues/13601"""+    if mode == 'wrap':++        class Gated(BaseModel):+            a: int+            b: int++            @model_serializer(mode='wrap', when_used=when_used)+            def _serialize(self, handler: SerializerFunctionWrapHandler) -> object:+                return handler(self)++    else:++        class Gated(BaseModel):+            a: int+            b: int++            @model_serializer(when_used=when_used)+            def _serialize(self) -> dict[str, int]:+                return {'a': self.a}++    m = Gated(a=1, b=2)+    # python mode: the gated serializer is not used, the default one must still apply 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'}) == {'a': 1}+    assert m.model_dump_json(exclude={'b'}) == '{"a":1}'++    class Outer(BaseModel):+        inner: Gated+        c: int++    o = Outer(inner=m, c=3)+    assert o.model_dump(exclude={'inner': {'b'}}) == {'inner': {'a': 1}, 'c': 3}+    assert o.model_dump(include={'inner': {'a'}}) == {'inner': {'a': 1}}+++@pytest.mark.parametrize('serializer', ['wrap', 'plain'])+def test_field_serializer_when_used_json_respects_include_exclude(serializer) -> None:+    if serializer == 'wrap':++        class Model(BaseModel):+            x: list[int]++            @field_serializer('x', mode='wrap', when_used='json')+            def _ser_x(self, v: list[int], handler: SerializerFunctionWrapHandler) -> object:+                return handler(v)++    else:++        class Model(BaseModel):+            x: list[int]++            @field_serializer('x', when_used='json')+            def _ser_x(self, v: list[int]) -> list[int]:+                return v++    m = Model(x=[1, 2, 3])+    assert m.model_dump(exclude={'x': {1}}) == {'x': [1, 3]}+    assert m.model_dump(include={'x': {0}}) == {'x': [1]}++ def test_model_serializer_wrong_args():     m = (         r'Unrecognized model_serializer function signature for ' 
Merged fix · PR #13702+44 −15
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}