Backtestspydanticrun-20260930-144322#13601

Issue #13601 Merged fix PR #13702 Run 30 Sep 2026 · run-20260930-144322 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 fix the root cause the same way. In `function_type_serializer`, when `self.call` returns `Ok((false, v))` (the function was skipped by the `when_used` gate), the fallback serializer now receives the caller's original include/exclude instead of `IncludeExclude::empty()`. The empty filter is correct only when the user function actually ran, since the function (or its handler) is then responsible for filtering. Both apply this to `to_python`, `json_key` and `serde_serialize`, so correctness is effectively equal.

Patch A returns early from the `false` branch with the unchanged `state`. This avoids scoping and cloning altogether, keeps the existing structure and adds no new API surface. It also clarifies the comments.

Patch B threads a third tuple element through the match. It adds a new public `include_exclude()` accessor on `SerializationState` that clones the include/exclude, then re-scopes the state with that clone. This is functionally equivalent but slightly more machinery, including a new public method, for the same effect.

On tests, both would fail before the fix and pass after.
- Patch A parametrizes over both `json` and `json-unless-none`, which are the two gating values named in the issue. It checks include and exclude in python and json mode with a handler-calling wrap serializer, mirroring the issue's reproduction exactly.
- Patch B also covers `plain` mode, a nice extra, and asserts that the json-mode path still runs the function. However, it only tests `when_used='json'`, and it leaves a stray `"""<link>"""` placeholder docstring.

Overall the fixes are equivalent. Patch A is more minimal, adds no API, and its test matches the issue's scenarios, including `json-unless-none`, so it edges out Patch B.

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 39s19 turns

Wall-clock time in the container

Full test suite

No new failures

12,399 passed · 501 skipped · 12,900 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

40vs 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+34 −6
pydantic-core/src/serializers/type_serializers/function.rsindex 5944310c..58b94f1c 100644@@ -219,13 +219,14 @@ macro_rules! function_type_serializer {                 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),+                    // function not run (`when_used` gate), fallback keeps the original include/exclude+                    Ok((false, v)) => return 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);                     }                 };-                // None for include/exclude here, as filtering should be done+                // None for include/exclude here, as filtering should be done by the function                 let state = &mut state.scoped_include_exclude(IncludeExclude::empty());                 ret_serializer.to_python(v.bind(py), state)             }@@ -238,13 +239,19 @@ macro_rules! function_type_serializer {                 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),+                    // function not run (`when_used` gate), fallback keeps the original include/exclude+                    Ok((false, v)) => {+                        return 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);                     }                 };-                // None for include/exclude here, as filtering should be done+                // None for include/exclude here, as filtering should be done by the function                 let state = &mut state.scoped_include_exclude(IncludeExclude::empty());                 ret_serializer                     .json_key(v.bind(py), state)@@ -260,13 +267,18 @@ macro_rules! function_type_serializer {                 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),+                    // function not run (`when_used` gate), fallback keeps the original include/exclude+                    Ok((false, v)) => {+                        return 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);                     }                 };-                // None for include/exclude here, as filtering should be done+                // None for include/exclude here, as filtering should be done by the function                 let mut state = state.scoped_include_exclude(IncludeExclude::empty());                 ret_serializer.serde_serialize(v.bind(py), serializer, &mut state)             }tests/test_serialize.pyindex 57832ca0..53f9c595 100644@@ -513,6 +513,22 @@ 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_include_exclude(when_used):+    class MyModel(BaseModel):+        a: int+        b: int++        @model_serializer(mode='wrap', when_used=when_used)+        def _serialize(self, handler: SerializerFunctionWrapHandler) -> object:+            return handler(self)++    m = MyModel(a=1, b=2)+    for mode in ('python', 'json'):+        assert m.model_dump(mode=mode, exclude={'b'}) == {'a': 1}+        assert m.model_dump(mode=mode, include={'a'}) == {'a': 1}++ def test_model_serializer_plain_json_return_type():     class MyModel(BaseModel):         a: int 
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} 

What the agent reported

I fixed the bug: model_dump(exclude=...) and include=... are now honoured in python mode when a wrap model_serializer is gated with when_used="json" or "json-unless-none". The new regression test passes; the full tests/ suite has one failure, which comes from a /work vs /workspace path mismatch in the test environment.

What was wrong. The problem is in pydantic-core/src/serializers/type_serializers/function.rs, in the function_type_serializer! macro. When the when_used gate decided not to run the user's function (for example when_used="json" in python mode), the plain inner serializer still ran, but under scoped_include_exclude(IncludeExclude::empty()). That cleared the caller's include/exclude. Clearing them is only right when the user's function actually runs, because the function then applies them itself through handler. JSON mode worked because the function does run there.

What I changed.

  • Rust fix: in all three methods (to_python, json_key, serde_serialize), when the gate skips the function, the inner serializer now gets the original state with include/exclude intact. The path where the function runs is unchanged. The extension was rebuilt in place.
  • Wider effect: the same macro also serves plain function serializers. So a plain serializer gated by when_used, such as @field_serializer(..., when_used='json') on a nested model or list field, now also respects include/exclude in python mode. No existing test contradicted this, and there's no dedicated test for the plain case.
  • Test: I added test_model_serializer_wrap_when_used_include_exclude in tests/test_serialize.py. It is parametrized over json and json-unless-none and checks exclude={'b'} and include={'a'} in both python and json mode.
  • Not checked: cargo fmt couldn't run because rustfmt isn't installed here, so the formatting was done by hand.
  • Not covered by tests: the new fallback branches in json_key and serde_serialize only run when a None value hits a *-unless-none gate.

Test evidence.

  • The new test failed before the fix with assert {'a': 1, 'b': 2} == {'a': 1} in both cases, and passes after it.
  • The report's example now prints {'a': 1} in python mode, JSON mode, and with include={'a'}.
  • tests/test_serialize.py, tests/test_serialize_as_any.py and tests/test_main.py: 361 passed, 26 skipped, 1 xfailed.
  • pydantic-core/tests/serializers: 812 passed, 5 skipped, 1 xfailed.
  • Full ./bt-test: 12398 passed, 1 failed.
  • The failure is tests/test_validators.py::test_v1_validator_deprecated.
  • It compares the warning's file path (/work/tests/test_validators.py) against __file__ (/workspace/tests/test_validators.py); /work is a symlink to /workspace.
  • The test only covers a V1 @validator deprecation warning and never touches the serializer code I changed.
  • It still fails after I restored the one environment file the rebuild had changed (pydantic_core.pth, back to /work/...).
  • I did not confirm that it failed before my change, because that would have meant rebuilding the extension from the old source.
  • The reviewer found no blocking issues.

Requirements.

  1. model_dump(exclude={"b"}) omits b in python mode with when_used="json": done, covered by the test.
  2. Same for when_used="json-unless-none": done, it's a test parameter.
  3. JSON mode keeps working: covered by the test, and it passes.
  4. An ungated wrap serializer still honours exclude: the path where the function runs is unchanged, and the existing serializer tests pass.

The only changes in the working tree are the Rust file and the test file, uncommitted, with no scratch files.