Repository navigation
feat(v3): As* of a closed union variant rejects another variant's data - #2580
Merged
mromaszewicz merged 3 commits intoSep 26, 2026
Merged
Conversation
A union's As* decodes the union data into a variant and ignores the keys the variant doesn't declare, so it can't tell variants apart (oapi-codegen#668): of a oneOf of a Base with additionalProperties: false and an Extended that is an allOf of it, AsBase of Extended's data succeeds and drops Extended's keys. In schema-merging-behavior v3, the As* of a variant with additionalProperties: false first reads the top level of the union data into a map[string]json.RawMessage, returns an error for a key the variant doesn't allow (the first in sorted order), then decodes as before. ValueByDiscriminator calls As*, so it returns the error too. Only the top level is checked: DisallowUnknownFields, as oapi-codegen#668 proposed, would also reject extra keys in a nested open object, and a variant's custom UnmarshalJSON would skip it. Read literally, a closed variant allows only its own keys, so the union's own properties and discriminator could never appear. v3 reads it as its allOf merge reads a closed member: it closes the object the variant is part of. So As* allows the keys the variant declares (in its allOf members however deep, under their names and any json tag x-oapi-codegen-extra-tags gives them), the union's own properties and discriminator, and, in a type that combines several unions, the other unions' variants' keys. A key only the variant's siblings declare, or nothing does, is an error. So a closed variant always reads its own From* output, and there are no new generation errors. additionalProperties: false anywhere in a variant's allOf closes it, and a parent's oneOf that lists the variant declares nothing for it. A variant stays lenient when its keys can't all be known: it is opaque (another document, x-go-type), it or an allOf member has a oneOf or anyOf of its own that isn't only constraints, or it is combined with a union that has such a variant. As<Union> on a type that combines several unions now also leaves out the type's own properties that the union doesn't declare, and a discriminator the merge gave the union that neither its type nor any of its variants declares, so the union's closed variants read what it returns. output-options.lenient-union-accessors turns the check off; v1 and v2 ignore it. Their output doesn't change. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Contributor
|
The keys a variant's As* allows, and the keys From* of a union in an allOf of unions replaces, came from the property name or an x-oapi-codegen-extra-tags json override. With output-options.struct-tags giving a field another json name, such as card_wire, FromCard wrote card_wire but AsCard rejected it, and FromTransfer left an old card_wire in place. propertyKeys now reads a field's keys the way GenFieldsFromProperties writes its json tag: the extra-tags json tag, else none for x-go-json-ignore, else the json template's name, rendered with every combination of the flags it may depend on. A tag without a name is the Go field's name, as encoding/json reads it, where the extra-tags case used the property name before. internal/test/options/struct_tags_unions covers both with a template that renames every field and prefixes optional ones. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The previous commit read a field's keys from the struct-tags json
template rendered with every combination of the flags it may depend on,
so a template like `{{if .IsOptional}}opt_{{end}}{{.FieldName}}` gave a
required Courier.holder the key opt_holder_wire too. In an allOf of
unions that made Card's opt_holder_wire look shared with Delivery, and
FromTransfer kept the old card holder.
A variant's keys now come from the Go type it generates as: its schema
is generated as the type is, following the aliases an allOf or
x-go-type-name leaves, and each field's key is read from the json tag
GenFieldsFromProperties gives it, whose computation moves into
structFieldTags so both share it. A type with a MarshalJSON of its own,
a union or one with additional properties, writes its properties under
their names, which are its keys then. The keys are cached in genContext;
a variant is marked while its keys are read, so a union inside it that
leads back to it doesn't recurse.
The struct_tags_unions fixture gains Greptile's case: Card's optional
holder and Courier's required one.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
mromaszewicz
added a commit
that referenced
this pull request
Sep 26, 2026
v3 has been accepted but undocumented while it was built (#2564 to #2580). This makes it an option like the others, and documents it: - docs/schema-merging.md explains the three versions: v1 embeds an allOf's member types and is very limited, v2 is the default, and v3 is an option that becomes the default after at least one release as one. It shows how v1's embedding differs from v2 and v3's composition, compares v2 and v3 side by side with the code each generates, lists where v3 reads the spec generously with the spelling validators also accept, and says what to check when moving to v3. - The README's anyOf/allOf/oneOf FAQ says there are three ways and links the new page. Its IdentityWithDuplicateField example, which documented v2's last-wins merge that v3 rejects, now refines the property instead, and generates the same code under v2 and v3; so does examples/anyof-allof-oneof, which it mirrors. - SchemaMergingV3 is exported, and v3 is in the configuration schema's enum, the SchemaMergingBehavior doc comment, the unknown-value error and docs/configuration.md, which also lists lenient-union-accessors. - docs/extensions.md and the README's table document x-oapi-codegen-enum-merge. Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Step 5 of the
schema-merging-behavior: v3work, after the four union PRs (#2576 to #2579). It fixes #668 for v3. It changes only v3, which is still opt-in and undocumented. v1 and v2 output doesn't change.What changes
A union's
As*decodes the union data into a variant, and ignores the keys the variant doesn't declare. SoAs*can't tell variants apart. Here is #668's case:AsBase()of{"id": "2", "extra": "more"}succeeds, and dropsextra. In v3, theAs*of a variant withadditionalProperties: false(a closed variant) first reads the top level of the union data into amap[string]json.RawMessage. It returns an error for a key the variant doesn't allow, then decodes as before:ValueByDiscriminator()callsAs*, so it returns the same error. The check applies to oneOf and anyOf alike, since they share the template.Which keys a closed variant allows
Read literally, a closed variant allows only the keys it declares itself: not the union's own properties, and not its discriminator, which then could never appear. v3 reads it the way its allOf merge already reads a closed member: it closes the whole object the variant is part of. So
As*allows:x-oapi-codegen-extra-tags, or theoutput-options.struct-tagstemplate with that field's own flags), or are the property names for a type with aMarshalJSONof its own;A key only the variant's own sibling variants declare, or one nothing declares, is an error. So is a key an additional-properties map on the union would take: the closed variant closes the object.
additionalProperties: falseanywhere in a variant's allOf closes the variant as a whole, as it closes the merged type. So in the example,Extendedis closed too, and allowsid,nameandextra. A child that is an allOf of a parent listing it in a oneOf (#2577) doesn't take its siblings' keys from that oneOf.Because of this reading, a closed variant that doesn't declare the discriminator, or a required property of the union, still reads its own
From*output. So there are no new generation errors.Top level only
The check covers the variant's own keys, not those of nested objects. A closed
Catwith an opencollarobject still takes{"collar": {"size": "S"}}, which its schema allows.json.Decoder.DisallowUnknownFields, the fix #668 proposed, would reject that, since it applies to every nested struct. A variant's customUnmarshalJSONwould also skip it. Nested closed objects aren't checked:As*tells variants apart; it doesn't validate.When As* stays lenient
A variant's
As*stays as it was when its keys can't all be known:$refinto another document, orx-go-type;output-options.lenient-union-accessors: trueturns the check off, and v3 output is then identical to what it was. It's a lasting preference, not only a migration aid: a client built from an older spec shouldn't fail when a closed variant gains a property. v1 and v2 accept the option and ignore it.An allOf of unions
As<Union>on a type that combines several unions (#2578) already left out the keys only the other unions declare. It now also leaves out two more kinds of key the union's own type doesn't know:orderIdnext toPaymentandDelivery;So
AsPayment().AsCard()works for a closedCardin both cases, also on what the combined type's ownFrom*wrote. This changes behavior for open variants too: such a key no longer reaches an open variant's additional-properties map throughAsPayment().A limit:
As<Union>keeps every key one of the union's variants declares. So when a closedCarddoesn't declare a key that its siblingTransferdoes, and that key belongs to the rest of the object here (another union's variant, or the type's own property),AsPayment().AsCard()rejects it. The combined type's ownAsCard()allows it.Tests
TestClosedUnionVariantsV3inpkg/codegen/merge_schemas_v3_test.gocovers:x-go-type, a nested union, and a union combined with one that has anx-go-typevariant;lenient-union-accessorsgenerate no check.TestPlacedDiscriminatorcovers whenAs<Union>leaves out a placed discriminator, and when it keeps it.TestFieldKeyandTestJSONTagKeycover the key a field's json tag gives it.internal/test/options/struct_tags_unionsis a v3 fixture whosestruct-tagsjson template renames every field and prefixes optional ones. Its test checks that a closed variant'sAs*reads what itsFrom*wrote, and thatFrom*in an allOf of unions replaces the renamed keys, also when another union's variant has a required property of the same name, whose key differs.The aggregate matrix gains seven shapes, with v2 cells too except for the option's:
oneof_closed_variants: closed and open$refvariants next to the union's own properties and discriminator;oneof_closed_variants_lenient: the option;oneof_closed_parent_lists_children: feat(v3): a child that is an allOf of its parent isn't a union of its siblings #2577 with closed children;oneof_closed_allof_base: Support additionnalProperties: false in OneOf #668's case;allof_of_unions_closed: closed variants in an allOf of two unions with an own property;allof_of_unions_closed_discriminator: the same with a discriminator next to the allOf, whichAsPayment()leaves out;anyof_closed_inline: closed inline anyOf variants.Every cell round-trips its samples at every position, also on Go 1.25. The v3 cells' hand-written tests check which keys each
As*allows or rejects and the error text, that nested objects aren't checked, thatFrom*output reads back, and that data that isn't an object fails as before.Not in this PR
docs/configuration.mdgetslenient-union-accessorswith the rest of the v3 docs (step 6).oneOf: [$ref X, {type: 'null'}], which v3 collapses to a nullable X, stays lenient even when X is closed: its keys are X's, but the check sees a oneOf. That is safe, and can be relaxed later.Fixtures
make generatechanges one comment in two v3 cells: theAs<Union>doc inallof_of_unionsandallof_of_unions_additional.With
skip-fmt, every v1 and v2 fixture generates byte-identical output to main. So does every v3 fixture without a closed variant, apart from that comment. (The order of the external imports in skip-fmt output varies from run to run, on main too, so two fixtures needed a second look.) Withlenient-union-accessors: true, the lenient cell is byte-identical to main's output for the same spec.Regenerating every non-matrix fixture under v3 changes one type: in
internal/test/schemas/recursive,FilterPredicate's closed variantsFilterPredicateOpandFilterPredicateRangeOpget the check, soAsFilterPredicateOp()of{"$lt": 1}now fails. That is #668's case.🤖 Generated with Claude Code