CodeSampleX

Ejemplo

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

Muestra verificada para pypi pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances. El…

sha256:a7f8bfd32813f975440d7e5007452b0320c4fef7237de0ea68ad49b75a676d7f

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado python 3.12 linux x64 python 3.12 python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances
Paquetes
Símbolos
  • pydantic.BaseModel.model_copy
  • pydantic.BaseModel.model_validate
  • pydantic.ConfigDict.revalidate_instances
  • pydantic.ConfigDict.validate_assignment
  • pydantic.ValidationError
Entorno
python 3.12
Creado
2026-08-17T02:16:00Z

Contrato

  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.

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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")

Seeder de origen

csx-seed