Styxis
Company
Knowledge

Pydantic alias and extra collisions: deciding which validated value owns the output key

Allowing extra input should not silently transfer ownership of a validated field's output key. Define collision handling explicitly.

Pydantic alias and extra collisions: deciding which validated value owns the output key

A validated model value does not necessarily reach the response unchanged when alias and extra keys collide. Overwritten values or duplicate keys can make consumers observe different results depending on the output path. Define explicit authority between validation and serialization instead of assuming it is preserved. [1, 2, 3]

What the primary source establishes

A report describes a Pydantic model with extra=allow receiving both an alias and its field-name key. The validated field and model_extra collide during serialization: dictionary output overwrites a value, while JSON output can contain duplicate keys. [1]

The handover decision

Keep alias input separate from extra-field provenance. Withhold a colliding response until the application explicitly decides which value is authoritative. Reconcile canonical_field, validated_value, serialized_value, and extra_key; reading the JSON into an ordinary dictionary first may already erase evidence of a duplicate key. [1, 3]

A reference defined before the output

For illustrative inputs X=1 and x=2, choosing alias X as the declared field makes 1 the approved output value. A serialized 1 is normal; replacing it with the extra value 2 fails that choice. The extra input can be handled separately or the collision rejected, but the policy must be explicit. [1, 3]

The scoped Truthound check

Truthound Core 3.3.2 can compare the validated value and the selected serialized value with ColumnPairValidator. Inspect duplicate keys in raw JSON earlier; parsing into an ordinary dictionary and retaining only the last value cannot recover the original history. The caller must define alias precedence. [1, 2, 3]

Limits and alternative choices

Duplicate JSON keys may already be lost after parsing into a table, so raw-key validation is required separately. Reject colliding alias/name combinations at ingestion or restrict the extra-field policy. If the business contract explicitly gives extra input overwrite precedence, the validated-value-first rule must change. [1, 3]

Application conditions

Preserve validated-field and extra-field provenance before serialization, then align the approved output key with its actual value.

Alternatives

Reject colliding alias/name combinations at ingestion or restrict the extra-field policy.

Limitations

  • Duplicate JSON keys may already be lost after parsing into a table, so raw-key validation is required separately.

Evidence

Event checked
Subject checked
Modified