Sample
pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances
Verified sample for pypi pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances. The…
sha256:a7f8bfd32813f975440d7e5007452b0320c4fef7237de0ea68ad49b75a676d7f
This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured.
How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people.
MIT-0
Execution evidence
The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.
- Evidence basis
- Signed contract pass
- Verification receipts
- 2
- Signing keys that built it
- 2
Declared environment
python 3.12 linux x64 python 3.12 python pip
Verification-run environments
| Environment | Contract | Stages | Run |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
Case
HOW- Goal
- Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances
- Packages
- Symbols
-
- pydantic.BaseModel.model_copy
- pydantic.BaseModel.model_validate
- pydantic.ConfigDict.revalidate_instances
- pydantic.ConfigDict.validate_assignment
- pydantic.ValidationError
- Environment
- python 3.12
- Created
- 2026-08-17T02:16:00Z
Contract
- model_copy(update=...) trusts update data: it neither coerces an invalid string amount nor enforces extra='forbid'.
- A model copied with an undeclared update exposes that attribute and marks it as set, while model_dump omits it and the original remains unchanged.
- Rebuilding from model_dump plus updates with model_validate rejects both the non-positive amount and the undeclared field, while valid strings are coerced to Decimal.
- With the default revalidate_instances='never', model_validate(existing_instance) returns the same instance and accepts an invalid post-construction assignment.
- revalidate_instances='always' rejects a previously damaged instance, while validate_assignment=True rejects invalid mutation immediately and coerces valid assignments.
Files
- NOTES.md
- csx.json
- requirements.lock
- requirements.txt
- src/__init__.py
- src/models.py
- test/contract.py
Source
# Pydantic copy and instance validation trust boundaries
`search_known_solution` returned only unrelated Pydantic/FastAPI contracts. None
proved `model_copy`, instance revalidation, or assignment validation semantics.
The tempting mistake is to treat `model_copy(update=...)` as a validated model
update. Pydantic documents its update input as trusted data, so neither field
validation nor extra-field rejection runs. A second subtle trust boundary is
`model_validate(existing_model)`: existing instances are returned without
revalidation by default.
Use `model_validate(model.model_dump() | updates)` for untrusted update data.
Use `revalidate_instances="always"` when existing instances cross a trust
boundary, and `validate_assignment=True` when every mutation must be checked.
{"case":{"caseId":"case:sha256:a010eff6c8ac83d56fd4d6107cb3d4cb73511bb2ec92334187bf82b1b50a71fe","contract":["model_copy(update=...) trusts update data: it neither coerces an invalid string amount nor enforces extra='forbid'.","A model copied with an undeclared update exposes that attribute and marks it as set, while model_dump omits it and the original remains unchanged.","Rebuilding from model_dump plus updates with model_validate rejects both the non-positive amount and the undeclared field, while valid strings are coerced to Decimal.","With the default revalidate_instances='never', model_validate(existing_instance) returns the same instance and accepts an invalid post-construction assignment.","revalidate_instances='always' rejects a previously damaged instance, while validate_assignment=True rejects invalid mutation immediately and coerces valid assignments."],"goal":"Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances","kind":"HOW","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["pydantic.BaseModel.model_copy","pydantic.BaseModel.model_validate","pydantic.ConfigDict.revalidate_instances","pydantic.ConfigDict.validate_assignment","pydantic.ValidationError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["pydantic.BaseModel.model_copy","pydantic.BaseModel.model_validate","pydantic.ConfigDict.revalidate_instances","pydantic.ConfigDict.validate_assignment","pydantic.ValidationError"],"verifierAdapter":"python@1"}
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field
class LedgerEntry(BaseModel):
model_config = ConfigDict(extra="forbid")
amount: Decimal = Field(gt=0)
currency: str
class RevalidatedLedgerEntry(BaseModel):
model_config = ConfigDict(extra="forbid", revalidate_instances="always")
amount: Decimal = Field(gt=0)
currency: str
class AssignmentValidatedLedgerEntry(BaseModel):
model_config = ConfigDict(extra="forbid", validate_assignment=True)
amount: Decimal = Field(gt=0)
currency: str
import sys
from decimal import Decimal
from importlib.metadata import version
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pydantic import ValidationError
from src.models import (
AssignmentValidatedLedgerEntry,
LedgerEntry,
RevalidatedLedgerEntry,
)
def error_types(error: ValidationError) -> set[str]:
return {item["type"] for item in error.errors()}
def test_model_copy_update_is_a_trusted_data_path() -> None:
original = LedgerEntry(amount="10.50", currency="USD")
copied = original.model_copy(update={"amount": "-5", "unexpected": True})
assert original.amount == Decimal("10.50")
assert not hasattr(original, "unexpected")
assert copied.amount == "-5"
assert not isinstance(copied.amount, Decimal)
assert copied.unexpected is True
assert copied.model_fields_set == {"amount", "currency", "unexpected"}
assert "unexpected" not in copied.model_dump()
def test_model_validate_a_merged_dump_validates_every_update() -> None:
original = LedgerEntry(amount="10.50", currency="USD")
unsafe_payload = original.model_dump() | {"amount": "-5", "unexpected": True}
try:
LedgerEntry.model_validate(unsafe_payload)
except ValidationError as error:
assert error_types(error) == {"greater_than", "extra_forbidden"}
else:
raise AssertionError("model_validate must reject invalid and extra update data")
validated = LedgerEntry.model_validate(
original.model_dump() | {"amount": "2.50"}
)
assert validated.amount == Decimal("2.50")
assert isinstance(validated.amount, Decimal)
def test_existing_instances_are_trusted_by_default() -> None:
entry = LedgerEntry(amount="10.50", currency="USD")
entry.amount = "-5"
accepted = LedgerEntry.model_validate(entry)
assert accepted is entry
assert accepted.amount == "-5"
def test_explicit_configs_close_both_mutation_gaps() -> None:
revalidated = RevalidatedLedgerEntry(amount="10.50", currency="USD")
revalidated.amount = "-5"
try:
RevalidatedLedgerEntry.model_validate(revalidated)
except ValidationError as error:
assert error_types(error) == {"greater_than"}
else:
raise AssertionError("revalidate_instances='always' must reject damage")
guarded = AssignmentValidatedLedgerEntry(amount="10.50", currency="USD")
try:
guarded.amount = "-5"
except ValidationError as error:
assert error_types(error) == {"greater_than"}
else:
raise AssertionError("validate_assignment=True must reject invalid assignment")
assert guarded.amount == Decimal("10.50")
guarded.amount = "2.50"
assert guarded.amount == Decimal("2.50")
assert isinstance(guarded.amount, Decimal)
if __name__ == "__main__":
assert version("pydantic") == "2.13.4"
test_model_copy_update_is_a_trusted_data_path()
test_model_validate_a_merged_dump_validates_every_update()
test_existing_instances_are_trusted_by_default()
test_explicit_configs_close_both_mutation_gaps()
print("CONTRACT PASS: Pydantic copy and instance trust boundaries verified")