Skip to content

Only coerce between models when the target is a context - #300

Draft
hintse wants to merge 1 commit into
mainfrom
fix/union-model-coercion-last
Draft

hintse wants to merge 1 commit into
mainfrom
fix/union-model-coercion-last

Conversation

@hintse

@hintse hintse commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

BaseModel._base_model_validator coerced an instance of any model into any other model whose fields fit, by dumping it and re-validating the dict. Inside a union, pydantic tries the members in order, so this coercion ran for every member ahead of the one that matched:

class A(BaseModel):
    x: int = 1

class B(BaseModel):
    x: int = 1

class Holder(BaseModel):
    f: A | B

b = B()
Holder(f=b)  # returns b, but only after building an A from b.model_dump() and discarding it

Problems with this:

  • Objects of the wrong type got built and discarded, and their validators (and any side effects) ran on the coerced data.
  • If one of those validators raised something other than a ValidationError, the whole union failed, even though a later member was an exact match.
  • With union_mode="left_to_right", the field got the coerced A instead of the B passed in.

Change

Following the suggestion in the review, coercion between models now only applies when the target is a context:

if isinstance(v, PydanticBaseModel) and issubclass(cls, ContextBase):
    v = v.model_dump(exclude={"type_"})

Contexts are frozen value objects, so any model whose fields fit is a valid input, and CallableModel relies on this to convert one context type into another. Other models reject instances of unrelated models, as in pydantic.

Comparison with plain pydantic

With A and B unrelated non-context models that have the same fields, and an instance of B passed in (measured on pydantic 2.14.4):

Field type Plain pydantic ccflow before this PR ccflow with this PR
A | B (smart mode, the default) the B passed in, no A built the B passed in, but an A is built from it and discarded the B passed in, no A built
A | B with union_mode="left_to_right" the B passed in, no A built a new A built from the B the B passed in, no A built
A | B in TypeAdapter or a plain pydantic model the B passed in, no A built the B passed in, but an A is built from it and discarded the B passed in, no A built
A (not a union) rejected (model_type error) a new A built from the B rejected (ValidationError)

Contexts behave as before: a context still validates from any model whose fields fit, including inside unions.

Behaviour changes

  • Passing an instance of a model where an unrelated, non-context model is expected now raises a ValidationError.
  • With union_mode="left_to_right", an instance of a later union member now comes back unchanged instead of being coerced into an earlier member.

Docs

docs/wiki/reference/Contexts-and-Results.md now describes context coercion, and notes that context validators should have no side effects, since validation may build a context more than once (for example while trying the members of a union) and discard it.

Type of Change

  • Bug fix
  • New feature
  • Documentation update
  • Refactor / code cleanup
  • CI / build configuration
  • Other (describe below)

Checklist

  • Linting passes (ruff check, ruff format --check, mdformat --check, codespell on the changed doc)
  • Tests pass: full suite on Python 3.11 / pydantic 2.14.4, 1636 passed. Not run on other Python or pydantic versions.
  • New tests added for new functionality
  • Documentation updated (if applicable)
  • Changelog / version bump (if applicable)

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.63%. Comparing base (58ae11d) to head (fab3dbf).

Files with missing lines Patch % Lines
ccflow/tests/test_base.py 93.87% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #300      +/-   ##
==========================================
- Coverage   93.89%   93.63%   -0.27%     
==========================================
  Files         205      205              
  Lines       23126    23171      +45     
  Branches     1517     1517              
==========================================
- Hits        21715    21696      -19     
- Misses       1119     1183      +64     
  Partials      292      292              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ptomecek

Copy link
Copy Markdown
Collaborator

Alternative proposal: only coerce between models when the target is a context.

if isinstance(v, PydanticBaseModel) and issubclass(cls, ContextBase):
    v = v.model_dump(exclude={"type_"})

Contexts are frozen value objects, so treating "any model whose fields fit" as a valid input is like pydantic accepting "1" for an int. The rule lives on the type, so field validation and call-time conversion stay the same.

Behaviour change:

  • Passing an instance of model B where an unrelated, non-context model A is expected now raises a ValidationError.
  • Unions of non-context models behave like pydantic, including in TypeAdapter and plain pydantic models.
  • Unions of contexts keep today's behaviour. Context validators should have no side effects, and we'd document that.

BaseModel validation coerced an instance of any model into any other model
whose fields fit, by dumping it and re-validating the result. Inside a union,
pydantic tries each member in turn, so this ran for every member ahead of the
one that matched: it built objects that were then discarded, ran their
validators on the coerced data, and an error other than a ValidationError in
one of them aborted the whole union. With union_mode="left_to_right", it also
returned the coerced object instead of the instance passed in.

Coercion now only applies when the target is a context. Contexts are frozen
value objects, so any model whose fields fit is a valid input, and
CallableModel relies on this to convert one context type into another. Other
models reject instances of unrelated models, as in pydantic, so their unions
behave like pydantic's, including in TypeAdapter and plain pydantic models.

Signed-off-by: Hin Tse <5867507+hintse@users.noreply.github.com>
@hintse
hintse force-pushed the fix/union-model-coercion-last branch from 2b01f0d to fab3dbf Compare November 26, 2026 04:35
@hintse hintse changed the title Coerce models in unions only as a last resort Only coerce between models when the target is a context Nov 26, 2026
@hintse

hintse commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, I've switched the PR to this approach (fab3dbf).

  • You were right about TypeAdapter. With the previous version, TypeAdapter(A | B).validate_python(B()) and an A | B field on a plain pydantic model still built an A and discarded it. With the context-only check, no A is built in any of these cases.
  • test_coerce_from_other_type now expects a ValidationError, and test_coerce_from_other_context_type tests the same coercion between two contexts. There are also new tests for unions in a ccflow model (smart and left_to_right), in TypeAdapter and in a plain pydantic model, and for a union of contexts that still coerces.
  • docs/wiki/reference/Contexts-and-Results.md now describes context coercion and says context validators should have no side effects.

The full suite passes locally (1636 passed, Python 3.11, pydantic 2.14.4).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants