Backtestspydanticrun-20261022-024030#13601

Issue #13601 Merged fix PR #13702 Run 22 Oct 2026 · run-20261022-024030 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 A = our agent, Patch B = the merged fix.

Both patches target the same root cause in the function_type_serializer macro: when `self.call` reports the function was skipped by the `when_used` gate (the `Ok((false, v))` arm), the fallback serializer was being run with include/exclude scoped to empty, so the caller's filtering vanished. Patch A short-circuits with an early return that leaves the existing state untouched; Patch B threads the choice of IncludeExclude through the match and scopes to either empty or a clone of the current state. Functionally they are equivalent across to_python, json_key and serde_serialize, and the independent tests confirm both fix the issue, including nested excludes and include. B's single-path approach is marginally more compact, but it adds a new public clone-returning accessor on SerializationState and re-scopes the state to the same value it already holds, which is slightly redundant; A's early return is a touch repetitive across three methods but avoids any clone and does not touch extra.rs. On craft the two are close. The deciding difference is tests: A adds a pydantic-core level test (plain and wrap, both json and json-unless-none, exercising include and exclude on a dict schema) plus pydantic tests for model_serializer, field_serializer with nested exclude, and a nested model case, each cross-checked against JSON mode. B adds one test covering plain and wrap with when_used='json' only, with no json-unless-none coverage and no nested or field-serializer coverage. A's tests more completely pin the behaviour the issue asks for and would catch regressions in more of the affected paths, so A is the better patch overall.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

7m 4s

Wall-clock time in the container

Full test suite

No new failures

405 passed · 91 skipped · 496 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

130vs 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+121 −9
pydantic-core/src/serializers/type_serializers/function.rsindex 5944310c..ce3a8b33 100644@@ -217,14 +217,19 @@ 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 (used, ret_serializer, v) = match self.call(value, state) {+                    Ok((true, v)) => (true, &*self.return_serializer, v),+                    Ok((false, v)) => (false, self.get_fallback_serializer(), v),                     Err(err) => {                         on_error(py, err, &self.function_name, state)?;                         return infer_to_python(value, state);                     }                 };+                if !used {+                    // the function was skipped (see `when_used`), so the fallback serializer+                    // must still apply the caller's include/exclude+                    return ret_serializer.to_python(v.bind(py), 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)@@ -236,14 +241,21 @@ 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 (used, ret_serializer, v) = match self.call(key, state) {+                    Ok((true, v)) => (true, &*self.return_serializer, v),+                    Ok((false, v)) => (false, self.get_fallback_serializer(), v),                     Err(err) => {                         on_error(py, err, &self.function_name, state)?;                         return infer_json_key(key, state);                     }                 };+                if !used {+                    // the function was skipped (see `when_used`), so the fallback serializer+                    // must still apply the caller's include/exclude+                    return ret_serializer+                        .json_key(v.bind(py), state)+                        .map(|cow| Cow::Owned(cow.into_owned()));+                }                 // None for include/exclude here, as filtering should be done                 let state = &mut state.scoped_include_exclude(IncludeExclude::empty());                 ret_serializer@@ -258,14 +270,19 @@ 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 (used, ret_serializer, v) = match self.call(value, state) {+                    Ok((true, v)) => (true, &*self.return_serializer, v),+                    Ok((false, v)) => (false, self.get_fallback_serializer(), v),                     Err(err) => {                         on_error(py, err, &self.function_name, state).map_err(py_err_se_err)?;                         return infer_serialize(value, serializer, state);                     }                 };+                if !used {+                    // the function was skipped (see `when_used`), so the fallback serializer+                    // must still apply the caller's include/exclude+                    return ret_serializer.serde_serialize(v.bind(py), 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)pydantic-core/tests/serializers/test_functions.pyindex b6bd900e..83509561 100644@@ -304,6 +304,24 @@ def test_function_only_json():     assert s.to_json(4) == b'8'  +@pytest.mark.parametrize('when_used', ['json', 'json-unless-none'])+@pytest.mark.parametrize('function_type', ['plain', 'wrap'])+def test_function_when_used_json_fallback_respects_include_exclude(function_type, when_used):+    if function_type == 'wrap':+        ser_schema = core_schema.wrap_serializer_function_ser_schema(lambda v, h: h(v), when_used=when_used)+    else:+        ser_schema = core_schema.plain_serializer_function_ser_schema(lambda v: v, when_used=when_used)+    s = SchemaSerializer(+        core_schema.dict_schema(core_schema.str_schema(), core_schema.int_schema(), serialization=ser_schema)+    )+    # in python mode the function is skipped, the fallback serializer must still apply include/exclude+    assert s.to_python({'a': 1, 'b': 2}, exclude={'b'}) == {'a': 1}+    assert s.to_python({'a': 1, 'b': 2}, include={'a'}) == {'a': 1}+    if function_type == 'wrap':+        assert s.to_python({'a': 1, 'b': 2}, mode='json', exclude={'b'}) == {'a': 1}+        assert s.to_json({'a': 1, 'b': 2}, exclude={'b'}) == b'{"a":1}'++ def test_function_unless_none():     s = SchemaSerializer(         core_schema.any_schema(tests/test_serialize.pyindex 57832ca0..f6f2d05c 100644@@ -1437,3 +1437,80 @@ 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'})+++@pytest.mark.parametrize('when_used', ['json', 'json-unless-none'])+@pytest.mark.parametrize('mode', ['plain', 'wrap'])+def test_model_serializer_when_used_json_respects_include_exclude_in_python_mode(mode: str, when_used: str) -> None:+    if mode == 'wrap':++        class Model(BaseModel):+            a: int+            b: int++            @model_serializer(mode='wrap', when_used=when_used)+            def _serialize(self, handler: SerializerFunctionWrapHandler) -> Any:+                return handler(self)++    else:++        class Model(BaseModel):+            a: int+            b: int++            @model_serializer(mode='plain', when_used=when_used)+            def _serialize(self) -> Any:+                return {'a': self.a, 'b': self.b}++    m = Model(a=1, b=2)+    # the gate skips the function in python mode, so the default serializer must still filter+    assert m.model_dump(exclude={'b'}) == {'a': 1}+    assert m.model_dump(include={'a'}) == {'a': 1}+    assert m.model_dump() == {'a': 1, 'b': 2}+    if mode == 'wrap':+        assert m.model_dump(mode='json', exclude={'b'}) == {'a': 1}+        assert m.model_dump_json(exclude={'b'}) == '{"a":1}'+++@pytest.mark.parametrize('mode', ['plain', 'wrap'])+def test_field_serializer_when_used_json_respects_nested_exclude_in_python_mode(mode: str) -> None:+    if mode == 'wrap':++        class Model(BaseModel):+            d: dict[str, int]++            @field_serializer('d', mode='wrap', when_used='json')+            def _ser_d(self, v: Any, handler: SerializerFunctionWrapHandler) -> Any:+                return handler(v)++    else:++        class Model(BaseModel):+            d: dict[str, int]++            @field_serializer('d', mode='plain', when_used='json')+            def _ser_d(self, v: Any) -> Any:+                return v++    m = Model(d={'x': 1, 'y': 2})+    assert m.model_dump(exclude={'d': {'y'}}) == {'d': {'x': 1}}+    assert m.model_dump(include={'d': {'x'}}) == {'d': {'x': 1}}+    if mode == 'wrap':+        assert m.model_dump(mode='json', exclude={'d': {'y'}}) == {'d': {'x': 1}}+++def test_nested_model_serializer_when_used_json_respects_exclude_in_python_mode() -> None:+    class Inner(BaseModel):+        a: int+        b: int++        @model_serializer(mode='wrap', when_used='json')+        def _serialize(self, handler: SerializerFunctionWrapHandler) -> Any:+            return handler(self)++    class Outer(BaseModel):+        sub: Inner++    m = Outer(sub=Inner(a=1, b=2))+    assert m.model_dump(exclude={'sub': {'b'}}) == {'sub': {'a': 1}}+    assert m.model_dump(mode='json', exclude={'sub': {'b'}}) == {'sub': {'a': 1}} 
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}