Backtestspydanticrun-20260923-170312#13601
model_dump(exclude=...) is silently ignored in python mode when a wrap model_serializer is gated with when_used="json"
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 scoped include/exclude to empty before delegating, which is only valid when the serializer *function actually ran* (and did the filtering itself). When the gate (when_used='json') is off in python mode, the function does not run, the fallback serializer runs, and it must still honor the runtime include/exclude. Both fixes distinguish the ran/not-ran branches and let the fallback see include/exclude, so correctness is a tie — both resolve the issue at root and hold under the described scenarios (python vs json mode, exclude and include). Tests are also comparable: A covers plain and wrap gated serializers plus include/exclude/json paths; B covers wrap json and the json-unless-none variant explicitly named in the issue. Both sets fail before and pass after. The deciding factor is craft and scope. Patch A extends the existing match tuple to carry the chosen IncludeExclude and keeps a single call site per method — a minimal, idiomatic change that mirrors the surrounding structure, at the cost of one small, well-named helper (include_exclude()) in extra.rs. Patch B instead splits every one of the three serializer methods into duplicated if/else branches where the else arm repeats the entire serializer call verbatim (including the multi-line json_key map chain). That duplication, repeated three times, is noticeably harder to read and maintain and offers no functional advantage over A (A's scope-to-current-value is equivalent to B's pass-through). A's approach is the smaller, cleaner correct fix, so A wins.
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
25m 19s15 turns
Wall-clock time in the container
Full test suite
No new failures
6,608 passed · 368 skipped · 6,976 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
90vs 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..f164c650 100644@@ -217,17 +217,22 @@ 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, used) = match self.call(value, state) {+ Ok((true, v)) => (&*self.return_serializer, v, true),+ Ok((false, v)) => (self.get_fallback_serializer(), v, false), 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());- ret_serializer.to_python(v.bind(py), state)+ if used {+ // the serializer function ran and already applied any include/exclude filtering+ let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ ret_serializer.to_python(v.bind(py), state)+ } else {+ // gate was off: the function did not run, so the fallback must honor the runtime include/exclude+ ret_serializer.to_python(v.bind(py), state)+ } } fn json_key<'a, 'py>(@@ -236,19 +241,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),+ let (ret_serializer, v, used) = match self.call(key, state) {+ Ok((true, v)) => (&*self.return_serializer, v, true),+ Ok((false, v)) => (self.get_fallback_serializer(), v, false), 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()))+ if used {+ // the serializer function ran and already applied any include/exclude filtering+ let state = &mut state.scoped_include_exclude(IncludeExclude::empty());+ ret_serializer+ .json_key(v.bind(py), state)+ .map(|cow| Cow::Owned(cow.into_owned()))+ } else {+ // gate was off: the function did not run, so the fallback must honor the runtime include/exclude+ 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 +270,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),+ let (ret_serializer, v, used) = match self.call(value, state) {+ Ok((true, v)) => (&*self.return_serializer, v, true),+ Ok((false, v)) => (self.get_fallback_serializer(), v, false), 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());- ret_serializer.serde_serialize(v.bind(py), serializer, &mut state)+ if used {+ // the serializer function ran and already applied any include/exclude filtering+ let mut state = state.scoped_include_exclude(IncludeExclude::empty());+ ret_serializer.serde_serialize(v.bind(py), serializer, &mut state)+ } else {+ // gate was off: the function did not run, so the fallback must honor the runtime include/exclude+ ret_serializer.serde_serialize(v.bind(py), serializer, state)+ } } fn get_name(&self) -> &str {tests/test_serialize.pyindex 57832ca0..5d329af5 100644@@ -513,6 +513,39 @@ 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) -> Any:+ return handler(self)++ m = Gated(a=1, b=2)+ # python mode: gate is off so the wrap function does not run, but a runtime+ # exclude must still be honoured by the fallback serializer.+ assert m.model_dump(exclude={'b'}) == {'a': 1}+ assert m.model_dump() == {'a': 1, 'b': 2}+ # json mode: gate is on, the wrap function runs and exclude is applied via the handler.+ assert m.model_dump(mode='json', exclude={'b'}) == {'a': 1}+ assert m.model_dump_json(exclude={'b'}) == '{"a":1}'+++def test_model_serializer_wrap_when_used_json_unless_none_exclude():+ class Gated(BaseModel):+ a: int+ b: int++ @model_serializer(mode='wrap', when_used='json-unless-none')+ def _serialize(self, handler: SerializerFunctionWrapHandler) -> Any:+ return handler(self)++ m = Gated(a=1, b=2)+ assert m.model_dump(exclude={'b'}) == {'a': 1}+ assert m.model_dump(mode='json', exclude={'b'}) == {'a': 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}
What the agent reported
The fix is complete and verified. Here's my final report.
Summary
What was wrong: In pydantic-core's function_type_serializer! macro (pydantic-core/src/serializers/type_serializers/function.rs), all three serialization methods (to_python, json_key, serde_serialize) unconditionally cleared the runtime include/exclude via scoped_include_exclude(IncludeExclude::empty()) before delegating to the chosen serializer. That is only correct when the user's serializer function actually ran (the gate-on branch), because it already applied filtering (a wrap serializer via its handler). When a @model_serializer(mode="wrap", when_used="json"/"json-unless-none") runs in python mode, the gate is off, so call() returns the original, unfiltered value and delegates to the fallback (inner model) serializer — but the caller's exclude= had already been wiped, so it was silently dropped. JSON mode worked because the gate is on there.
What I changed: Threaded a used boolean out of the self.call(...) match in each of the three methods. Only the gate-on branch (used == true) clears include/exclude; the gate-off/fallback branch passes the original state through unchanged so the fallback serializer honors the runtime exclude. Minimal, applied identically across all three methods. Only function.rs (fix) and tests/test_serialize.py (tests) changed.
Test evidence:
- Two regression tests added after
test_model_serializer_wrap_info:test_model_serializer_wrap_when_used_json_excludeandtest_model_serializer_wrap_when_used_json_unless_none_exclude. - Before the fix: both failed on
model_dump(exclude={'b'}) == {'a': 1}(got{'a': 1, 'b': 2}). - After the fix (fresh container, full file): 92 passed, 1 skipped for
tests/test_serialize.py, including the two new tests and the existingtest_model_serializer_wrap/_wrap_info.
Build note: ./bt-test runs uv run --no-sync, which does not rebuild the Rust extension. The fix takes effect via maturin develop into the workspace-mounted .venv (the built .so lives at pydantic-core/python/pydantic_core/*.so, inside the mount), so it persists across fresh --rm containers — confirmed by my final full-file gate run passing in a new container.
Blast radius: The macro is shared by plain and wrap, field- and model-level function serializers gated by when_used. The gate-off branch always carries the unfiltered original value (user function never ran), so filtering is now applied exactly once — no double-filtering. This also fixes the same latent bug for gated field serializers with nested include/exclude. Gate-on behavior is unchanged. Full test_serialize.py (93 tests) passes.
Reviewer: Confirmed the fix sound and complete, tests non-tautological and exercising the exact reported scenario, no unrelated changes, no scratch files.
Requirements checklist
excludehonored in python mode forwhen_used="json"wrap serializer — ✅ implemented; regression testtest_model_serializer_wrap_when_used_json_excludepasses (failed before).- Same for
when_used="json-unless-none"(explicitly named in report) — ✅ implemented;test_model_serializer_wrap_when_used_json_unless_none_excludepasses (failed before). - JSON mode still correct — ✅ asserted in the new tests (json/json-string paths) and passing.
- Ungated
mode="wrap"still correct — ✅ existingtest_model_serializer_wrap/_wrap_infostill pass unchanged.
Changes left uncommitted in the working tree as instructed.