CodeSampleX

샘플

pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances

검증된 샘플 — pypi pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances. python 3.12 …

sha256:a7f8bfd32813f975440d7e5007452b0320c4fef7237de0ea68ad49b75a676d7f

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 python 3.12 linux x64 python 3.12 python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances
패키지
심벌
  • pydantic.BaseModel.model_copy
  • pydantic.BaseModel.model_validate
  • pydantic.ConfigDict.revalidate_instances
  • pydantic.ConfigDict.validate_assignment
  • pydantic.ValidationError
환경
python 3.12
생성일
2026-08-17T02:16:00Z

컨트랙트

  1. model_copy(update=...) trusts update data: it neither coerces an invalid string amount nor enforces extra='forbid'.
  2. 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.
  3. 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.
  4. With the default revalidate_instances='never', model_validate(existing_instance) returns the same instance and accepts an invalid post-construction assignment.
  5. revalidate_instances='always' rejects a previously damaged instance, while validate_assignment=True rejects invalid mutation immediately and coerces valid assignments.

파일

  • NOTES.md
  • csx.json
  • requirements.lock
  • requirements.txt
  • src/__init__.py
  • src/models.py
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# 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.
csx.json
{"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"}
requirements.lock
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
requirements.txt
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
src/__init__.py

src/models.py
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
test/contract.py
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")

오리진 시더

csx-seed