Skip to content

feat(v3): As* of a closed union variant rejects another variant's data - #2580

Merged
mromaszewicz merged 3 commits into
oapi-codegen:mainfrom
mromaszewicz:aggregates/v3-strict-as
Sep 26, 2026
Merged

mromaszewicz merged 3 commits into
oapi-codegen:mainfrom
mromaszewicz:aggregates/v3-strict-as

Conversation

@mromaszewicz

@mromaszewicz mromaszewicz commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Step 5 of the schema-merging-behavior: v3 work, 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. So As* can't tell variants apart. Here is #668's case:

Subject:
  oneOf:
    - $ref: '#/components/schemas/Base'
    - $ref: '#/components/schemas/Extended'
Base:
  type: object
  additionalProperties: false
  required: [id]
  properties:
    id: {type: string}
    name: {type: string}
Extended:
  allOf:
    - $ref: '#/components/schemas/Base'
    - type: object
      required: [extra]
      properties:
        extra: {type: string}

AsBase() of {"id": "2", "extra": "more"} succeeds, and drops extra. In v3, the As* of a variant with additionalProperties: false (a closed variant) first reads the top level of the union data into a map[string]json.RawMessage. It returns an error for a key the variant doesn't allow, then decodes as before:

// AsBase returns the union data inside the Subject as a Base. Base allows no
// additional properties: a property that neither it nor the rest of Subject
// declares is an error.
func (t Subject) AsBase() (Base, error) {
	var body Base
	var object map[string]json.RawMessage
	if json.Unmarshal(t.union, &object) == nil {
		// The first unknown key in sorted order, so the error is always the same.
		unknown, found := "", false
		for key := range object {
			switch key {
			case "id", "name":
			default:
				if !found || key < unknown {
					unknown, found = key, true
				}
			}
		}
		if found {
			return body, fmt.Errorf("Base doesn't allow the property %q", unknown)
		}
	}
	err := json.Unmarshal(t.union, &body)
	return body, err
}

ValueByDiscriminator() calls As*, 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:

  • the keys the variant declares, in itself and in its allOf members however deep: their property names, and the keys the fields of the variant's Go type marshal as. Those come from each field's json tag as the generator writes it (x-oapi-codegen-extra-tags, or the output-options.struct-tags template with that field's own flags), or are the property names for a type with a MarshalJSON of its own;
  • the union's own properties and its discriminator;
  • in a type that combines several unions, such as an allOf of unions (feat(v3): an allOf of unions is one of each union's variants at once #2578), the keys the other unions' variants declare.

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: false anywhere in a variant's allOf closes the variant as a whole, as it closes the merged type. So in the example, Extended is closed too, and allows id, name and extra. 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 Cat with an open collar object 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 custom UnmarshalJSON would 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:

output-options.lenient-union-accessors: true turns 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:

  • the type's own properties that the union doesn't declare, such as an orderId next to Payment and Delivery;
  • a discriminator the merge gave that union, declared next to the allOf or in a member of its own, when neither the union's type nor any of its variants declares the property. An opaque variant might declare it, so then the key is kept.

So AsPayment().AsCard() works for a closed Card in both cases, also on what the combined type's own From* wrote. This changes behavior for open variants too: such a key no longer reaches an open variant's additional-properties map through AsPayment().

A limit: As<Union> keeps every key one of the union's variants declares. So when a closed Card doesn't declare a key that its sibling Transfer does, 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 own AsCard() allows it.

Tests

  • TestClosedUnionVariantsV3 in pkg/codegen/merge_schemas_v3_test.go covers:

    • renamed and json-ignored keys, and a oneOf of constraints;
    • a type-less member whose oneOf restates the variant's type;
    • closing through a deep allOf member, and a closed variant with no properties;
    • variants that stay lenient: open, x-go-type, a nested union, and a union combined with one that has an x-go-type variant;
    • that v2 and lenient-union-accessors generate no check.
  • TestPlacedDiscriminator covers when As<Union> leaves out a placed discriminator, and when it keeps it.

  • TestFieldKey and TestJSONTagKey cover the key a field's json tag gives it.

  • internal/test/options/struct_tags_unions is a v3 fixture whose struct-tags json template renames every field and prefixes optional ones. Its test checks that a closed variant's As* reads what its From* wrote, and that From* 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:

    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, that From* output reads back, and that data that isn't an object fails as before.

Not in this PR

  • docs/configuration.md gets lenient-union-accessors with the rest of the v3 docs (step 6).
  • A variant that is only 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 generate changes one comment in two v3 cells: the As<Union> doc in allof_of_unions and allof_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.) With lenient-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 variants FilterPredicateOp and FilterPredicateRangeOp get the check, so AsFilterPredicateOp() of {"$lt": 1} now fails. That is #668's case.

🤖 Generated with Claude Code

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]>
@mromaszewicz
mromaszewicz requested a review from a team as a code owner September 26, 2026 00:34
@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Adds union validation behavior for closed schema variants.

The PR appears safe to merge; no new actionable failure was established.

Summary

The PR makes v3 accessors for closed union variants reject undeclared top-level keys, adds a lenient opt-out, and updates combined-union key handling and regression fixtures.

Reviews (3) · Last reviewed commit: "fix(v3): union keys are the variant type..."

Comment thread pkg/codegen/union_v3.go Resolved
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]>
Comment thread pkg/codegen/structtags.go Resolved
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
mromaszewicz merged commit 5c06d0a into oapi-codegen:main Sep 26, 2026
15 checks passed
@mromaszewicz
mromaszewicz deleted the aggregates/v3-strict-as branch September 26, 2026 04:18
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]>
@mromaszewicz mromaszewicz added the enhancement New feature or request label Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support additionnalProperties: false in OneOf

1 participant