Styxis
Company
Knowledge

Pydantic TypeAdapter unions: checking the selected response branch before serialization

A type declaration alone does not prove that field projection occurred. Verify the selected branch and the paths actually emitted.

Pydantic TypeAdapter unions: checking the selected response branch before serialization

Widening a response type to a union can invite the assumption that the selected branch's public fields remain enforced automatically. Runtime object attributes and an approved projection are different information. If output accompanies a warning, reconcile its field paths before treating it as an acceptable public response. [1, 2, 3]

What the primary source establishes

A report describes TypeAdapter serializing all fields of non-Pydantic objects when given a union rather than a single type, or raising for an unsupported object. Some cases produce JSON despite warnings. [1]

The handover decision

Validate and select the response branch first. Compare that branch's declared paths with the emitted paths, then deliver only fields the user approved. Retain selected_branch, output_path, and allowed_path so a serializer warning cannot become an implicit approval of a wider object. [1, 3]

A reference defined before the output

The illustrative branch permits only derived_from_id. An extra-path count of 0 satisfies the projection contract. If id and name are also emitted, the difference set has 2 paths and fails. That expectation comes from the selected schema, not from the runtime object's complete attribute list. [1, 3]

The scoped Truthound check

Truthound Core 3.3.2 provides DistinctValuesEqualSetValidator to compare a prepared output-path column with the declared set. Retain nested positions and the selected branch while extracting paths; validate field-value meaning separately. Branch selection and model-instance construction remain caller responsibilities. [1, 2, 3]

Limits and alternative choices

The report does not establish that all union serialization is defective; validating domain objects first remains the caller's responsibility. Explicitly validate and construct a concrete model instance before serializing through that type. If the intended branch permits the object's full field set, those paths are not outside the contract. [1, 3]

Application conditions

Prepare the selected branch's declared paths and actual emitted paths with nested-path identity preserved.

Alternatives

Explicitly validate and construct a concrete model instance before serializing through that type.

Limitations

  • The report does not establish that all union serialization is defective; validating domain objects first remains the caller's responsibility.

Evidence

Event checked
Subject checked
Modified