Backtestspydanticrun-20260929-204949#13601

Issue #13601 Merged fix PR #13702 Run 29 Sep 2026 · run-20260929-204949 pydantic/pydantic

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

Worse

The merged fix was judged better than our patch.

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

Both patches identify the same root cause correctly: the function serializer unconditionally cleared include/exclude before invoking the return-or-fallback serializer, so when the gated serializer was skipped in python mode (`Ok((false, v))`), the fallback path lost the caller's exclude/include. Both fix it by only clearing include/exclude in the used-serializer branch and preserving it in the fallback branch, and both are functionally correct across the issue's scenarios. Tests: both add failing-before/passing-after tests; A covers both plain and wrap gated serializers (showing the fix generalizes across function-serializer kinds), B covers wrap plus the json-unless-none variant the issue mentions — both solid. Craft is the tiebreaker. A makes the minimal structural change: it keeps the original single shared call site (`ret_serializer.to_python(...)`) and only makes the scoped value conditional, avoiding the code duplication B introduces (B duplicates the fallback serializer call and the `.map(|cow| Cow::Owned(...))` in json_key across branches). A's only cost is a small added `include_exclude()` helper that clones and re-scopes to the same value in the fallback case, which is slightly roundabout but negligible and equivalent. B's per-branch rewrite is more churn and duplication for no correctness gain. The margin is narrow, but A's DRY, minimal-diff approach edges it out.

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 21s28 turns

Wall-clock time in the container

Full test suite

No new failures

12,398 passed · 501 skipped · 12,899 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

95vs 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+69 −26
pydantic-core/src/serializers/type_serializers/function.rsindex 5944310c..db7bb906 100644@@ -217,17 +217,21 @@ 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) {+                    // Serializer was used: filtering was handled by the wrap handler, so the+                    // transformed value must not be re-filtered; clear include/exclude.+                    Ok((true, v)) => {+                        let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+                        self.return_serializer.to_python(v.bind(py), state)+                    }+                    // Serializer was skipped: the fallback serializes the original value and must+                    // honour the caller's include/exclude.+                    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 +240,26 @@ 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) {+                    // Serializer was used: filtering was handled by the wrap handler, so the+                    // transformed value must not be re-filtered; clear include/exclude.+                    Ok((true, v)) => {+                        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()))+                    }+                    // Serializer was skipped: the fallback serializes the original value and must+                    // honour the caller's include/exclude.+                    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 +269,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) {+                    // Serializer was used: filtering was handled by the wrap handler, so the+                    // transformed value must not be re-filtered; clear include/exclude.+                    Ok((true, v)) => {+                        let mut state = state.scoped_include_exclude(IncludeExclude::empty());+                        self.return_serializer+                            .serde_serialize(v.bind(py), serializer, &mut state)+                    }+                    // Serializer was skipped: the fallback serializes the original value and must+                    // honour the caller's include/exclude.+                    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..fc585cb9 100644@@ -513,6 +513,31 @@ 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_when_used_json_exclude():+    class Gated(BaseModel):+        a: int+        b: int++        @model_serializer(mode='wrap', when_used='json')+        def _serialize(self, handler: SerializerFunctionWrapHandler):+            return handler(self)++    assert Gated(a=1, b=2).model_dump(exclude={'b'}) == {'a': 1}+    assert Gated(a=1, b=2).model_dump(mode='json', exclude={'b'}) == {'a': 1}+    assert Gated(a=1, b=2).model_dump() == {'a': 1, 'b': 2}+    assert Gated(a=1, b=2).model_dump(include={'a'}) == {'a': 1}++    class GatedUnlessNone(BaseModel):+        a: int+        b: int++        @model_serializer(mode='wrap', when_used='json-unless-none')+        def _serialize(self, handler: SerializerFunctionWrapHandler):+            return handler(self)++    assert GatedUnlessNone(a=1, b=2).model_dump(exclude={'b'}) == {'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

Done. Only the two intended files are modified; no scratch files.

What was wrong

In pydantic-core's Rust function_type_serializer! macro (pydantic-core/src/serializers/type_serializers/function.rs), a function serializer dispatches to one of two serializers after calling self.call(...):

  • Ok((true, v)) — the user serializer was used (e.g. when_used="json" in JSON mode); the transformed value goes to return_serializer.
  • Ok((false, v)) — the serializer was skipped (e.g. when_used="json" in python mode); the original value falls back to the default model serializer.

All three methods (to_python, json_key, serde_serialize) unconditionally cleared the caller's include/exclude via scoped_include_exclude(IncludeExclude::empty()) before dispatching. Clearing is correct on the used branch (the wrap handler callable already applied filtering), but on the fallback branch it meant the default serializer never saw exclude/include — so model_dump(exclude={"b"}) silently kept b in python mode. JSON mode worked because there the serializer was used and the callable filtered.

What I changed

  • pydantic-core/src/serializers/type_serializers/function.rs: split the branches so the empty include/exclude scope is applied only on the Ok((true, v)) (serializer-used) branch; the Ok((false, v)) (fallback) branch now passes state through unchanged, so the fallback serializer honors the caller's filter. Applied consistently across to_python, json_key, and serde_serialize; rebuilt the extension with make build-dev.
  • tests/test_serialize.py: added test_model_serializer_wrap_when_used_json_exclude covering the exact reported scenario.

Test evidence

  • The regression test failed before the Rust fix ({'a': 1, 'b': 2} == {'a': 1} assertion error) and passes after.
  • Official gate ./bt-test tests/test_serialize.py tests/test_json.py: 151 passed, 1 skipped.
  • Blast-radius check on pydantic-core's own serializer tests (functions, format, model, dict, list_tuple): 204 passed, 1 skipped.
  • Reviewer confirmed the branch logic is sound (no double-filtering on the used branch, correct filtering on fallback for both plain and wrap serializers) and nothing unrelated changed.

Requirements disposition

  1. model_dump(exclude=...) honored in python mode with when_used="json" wrap serializer — ✅ implemented; test asserts Gated(a=1,b=2).model_dump(exclude={'b'}) == {'a': 1}.
  2. Same for when_used="json-unless-none" — ✅ implemented; test covers a second model gated with json-unless-none.
  3. JSON mode still correct + include honored — ✅ covered by regression assertions (json-mode exclude, include={'a'}, and no-arg sanity) and full gate.