Skip to content

Preserve JSON Schema metadata on annotated Struct union members - #1213

Open
00200200 wants to merge 2 commits into
msgspec:mainfrom
00200200:fix-schema-union-struct-metadata
Open

00200200 wants to merge 2 commits into
msgspec:mainfrom
00200200:fix-schema-union-struct-metadata

Conversation

@00200200

Copy link
Copy Markdown

Summary

msgspec.json.schema already keeps extra JSON Schema from msgspec.Meta on non-struct union members (for example Annotated[None, Meta(description=...)]). The same metadata is dropped when it is attached to a Struct.

The union walker unwraps Metadata to classify each member, then previously stored only the inner StructType. Schema generation therefore never saw the annotation. This stores the original union member alongside the unwrapped type and uses that member when emitting anyOf.

Reproduced on current main:

from typing import Annotated, Union
import msgspec

class Point(msgspec.Struct):
    x: int

PointWithMeta = Annotated[Point, msgspec.Meta(description="a point")]
print(msgspec.json.schema(Union[PointWithMeta, None])["anyOf"])
# before: [{'$ref': '#/$defs/Point'}, {'type': 'null'}]
# after:  [{'$ref': '#/$defs/Point', 'description': 'a point'}, {'type': 'null'}]

The same loss happens for tagged struct unions.

Tests

  • tests/unit/test_schema.py::test_optional_union_struct_member_metadata_preserved
  • tests/unit/test_schema.py::test_struct_tagged_union_member_metadata_preserved

pytest tests/unit/test_schema.py: 126 passed, 8 skipped.

Union schema generation unwrapped Metadata before storing Struct
members, so extra schema from msgspec.Meta on an annotated Struct
was dropped. Keep the original union member when emitting schemas.

This branch had an error being deployed

1 failed deployment
docs-preview — 3e7f9886 Deployed Oct 2, 2026 by 00200200 via Deploy preview #595
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant