Skip to content

feat(v3): an allOf of unions is one of each union's variants at once - #2578

Merged
mromaszewicz merged 2 commits into
oapi-codegen:mainfrom
mromaszewicz:aggregates/v3-unions-components
Sep 25, 2026
Merged

mromaszewicz merged 2 commits into
oapi-codegen:mainfrom
mromaszewicz:aggregates/v3-unions-components

Conversation

@mromaszewicz

Copy link
Copy Markdown
Member

Step 4 of the schema-merging-behavior: v3 work, third of four PRs after #2576 and #2577. It changes only v3, which is still opt-in and undocumented. v1 and v2 output doesn't change.

  1. a oneOf or anyOf that only adds constraints makes no union (feat(v3): a oneOf or anyOf that only adds constraints makes no union #2576)
  2. a child that is an allOf of its parent isn't a union of its siblings (feat(v3): a child that is an allOf of its parent isn't a union of its siblings #2577)
  3. an allOf of unions is one of each union's variants at once (this PR)
  4. an inline discriminated variant takes the value it pins

What changes

Order:
  allOf:
    - $ref: '#/components/schemas/Payment'    # oneOf: [Card, Transfer]
    - $ref: '#/components/schemas/Delivery'   # oneOf: [Courier, Pickup]

An Order is a Payment and a Delivery at once: a card and a courier, say. v2 concatenates the members' oneOfs into one union of four variants, and every From* replaces the whole value, so setting the delivery loses the payment:

var o Order
o.FromCard(Card{Card: "4111"})
o.FromCourier(Courier{Address: "1 Main St"})
// v2: {"address": "1 Main St"}                   the card is gone
// v3: {"card": "4111", "address": "1 Main St"}
o.FromTransfer(Transfer{Iban: "DE00"})
// v3: {"iban": "DE00", "address": "1 Main St"}   the transfer replaces the card; the delivery stays

v3 keeps each oneOf and anyOf an allOf brings as a union of its own. We decided to keep the storage as it is, one JSON value that each variant's As* parses on demand, rather than a field per union. Only From* changes:

  • From* for a variant replaces the keys its own union owns, the ones only that union's variants declare. It keeps the rest, which is the other unions' data.
  • A key that variants of several unions declare, such as a shared id, is overwritten when the new variant sets it and never removed. The data is commingled: a variant that appears in two unions may be the other union's data too, so removing its keys could lose it.
  • A variant from another document, or with x-go-type, declares no keys, since its fields aren't ours to read. The discriminator's property belongs to its union even when the variants leave it to the stamp.
  • A variant that marshals to null clears its union's keys and keeps the rest. When the variant or the held value is anything else that isn't a JSON object, From* replaces the value whole, as before.
  • Additional properties the caller set are kept. Merge* is unchanged.

Accessors for $ref unions

A member that is a $ref to a union type also gets As* and From* for that type, so the union keeps its identity and methods:

payment, _ := o.AsPayment()   // a Payment, without the keys only Delivery's variants declare
card, _ := payment.AsCard()
o.FromPayment(payment)        // sets the payment, keeps the delivery
o.FromPayment(Payment{})      // clears the payment

AsPayment leaves out the other unions' keys, so setting a Payment back later doesn't bring back an old delivery.

Discriminators

A value has one discriminator, which belongs to one of the unions:

  • It belongs to the union that declares it.
  • One declared next to the allOf, or in a member of its own, belongs to the union whose variants its mapping names. Without a mapping, it belongs to the union whose variants all have the property.
  • It is an error for it to fit several unions or none, or to be declared on two. The merge already rejects two different ones.

Discriminator(), ValueByDiscriminator() and the stamps cover only its own union's variants, and the other unions' variants no longer fail its mapping check. A discriminator next to an anyOf now also survives the allOf.

What stays the same

  • An allOf that brings a single union, however many times, generates exactly as before, and so does a schema with a single oneOf or anyOf.
  • A schema with both an anyOf and a oneOf is two unions this way. That's the allow coexistence of anyOf and oneOf fields in single schema definition #839 shape, and its anyOf and oneOf variants now keep each other's data.
  • A union brought twice is one, with the $ref and the discriminator either copy has. A union of only 3.1 null branches says the value is nullable and isn't a union.
  • A oneOf whose branches only restate a type another member declares only adds constraints (feat(v3): a oneOf or anyOf that only adds constraints makes no union #2576), and makes no union here either.
  • Inline variants of one of several unions are named <path>OneOf<n><index> or <path>AnyOf<n><index>, with <n> only when there are several of a kind. This keeps names stable when variants are added to an earlier union.

Implementation

The allOf merge collects each union as a component instead of concatenating them. When there are several, generateUnionComponentsV3 computes each variant's owned keys. The shared union.tmpl gets a union.keepOtherUnions block and the $ref-union accessors, both driven by new Schema fields that only v3 sets. v1 and v2 render byte-identically, both formatted and with skip-fmt.

Tests

  • pkg/codegen/merge_schemas_v3_test.go covers:
    • owned and shared keys; opaque, x-go-type and inline variants;
    • discriminator placement and its errors, anyOf discriminators, and the discriminator key;
    • duplicate and null-only unions, and unions that collapse to one.
  • The aggregate matrix gains allof_of_unions and allof_of_unions_additional (with additionalProperties), with v1, v2 and v3 cells that round-trip their samples at every position, also on Go 1.25. The v1 cells are marked broken: v1 embeds both unions, whose MarshalJSON and UnmarshalJSON then cancel out.
  • Hand-written v3 tests run the sequences above against generated code:
    • From* keeps the other union's data;
    • As*/From* for the $ref unions, with stale keys and zero values;
    • additional properties the caller changed survive From*.
  • The v3 anyof_oneof cell changes as described.

Fixtures

make generate changes no committed file. Regenerating every fixture under v3 changes one type beyond #2577: internal/test/aggregates/oneof's OneOfObject12, an allOf of two oneOfs, whose inline variants become OneOfObject12OneOf00 and so on.

🤖 Generated with Claude Code

`allOf: [$ref Payment, $ref Delivery]`, where Payment is a card or a
transfer and Delivery a courier or a pickup, describes a value that is
both: a card and a courier, say. v2 concatenates the members' oneOfs
into one union of four variants, so FromCourier replaces the card that
FromCard set.

schema-merging-behavior v3 keeps each oneOf and anyOf an allOf brings
as a union of its own. The type still holds one JSON value, and each
variant's As* parses it as before. From* for a variant now replaces only
the keys its own union owns, those only its union's variants declare,
and keeps the rest: FromCard then FromCourier holds both, and
FromTransfer afterwards swaps the card for the IBAN and keeps the
courier's address. A key several unions' variants declare, such as a
shared id, belongs to all of them and is kept unless the new variant
sets it: a variant in another union too may be that union's data. A
variant from another document or with an x-go-type declares no keys,
since its fields aren't ours to read. A variant that marshals to null
clears its union's keys and keeps the rest; when the variant or the held
value is anything else that isn't a JSON object, From* replaces the
value whole, as it did. Additional properties the caller set are kept.
Merge* is unchanged.

A member that is a $ref to a union type also gets As* and From* for that
type, so `AsPayment()` returns a Payment with its own methods, and
`FromPayment` sets it, keeping the delivery. AsPayment leaves out the
keys only Delivery's variants declare, so setting the Payment back
later doesn't bring back an old delivery; `FromPayment(Payment{})`
clears the payment.

An allOf that brings a single union, however many times, generates as
before, and so does a schema with a single oneOf or anyOf. A schema with
both an anyOf and a oneOf is two unions this way. A union brought twice
is one, with the $ref and discriminator either copy has, and one of only
3.1 null branches says nullable rather than being a union.

A value has one discriminator, which belongs to one of the unions: the
one that declares it, or, for one declared next to the allOf or in a
member of its own, the union whose variants its mapping names or,
without a mapping, the one whose variants all have the property. It is
an error for it to fit several unions or none, or to be declared on two
(the merge already rejects two different ones). It stamps and dispatches
only its own union's variants, and the other unions' variants no longer
fail its mapping check. Its property is one of its union's keys, even
when the variants leave it to the stamp. A discriminator next to an
anyOf keeps working through the allOf too.

An inline variant of one of several unions is named
<path>OneOf<n><index> or <path>AnyOf<n><index> (<n> only when there are
several of a kind).

A oneOf whose branches only restate a type another member declares,
such as `{type: object, required: [email]}` next to `$ref Contact`,
only adds constraints (see oapi-codegen#2576) and makes no union here either.

The matrix gains allof_of_unions and allof_of_unions_additional (with
additionalProperties), with v3 tests of the above and v1 and v2 cells
(v1 is broken: it embeds both unions, whose MarshalJSON and
UnmarshalJSON then cancel out). v3's anyof_oneof cell changes: its
anyOf and oneOf variants now keep each other's data. Generating the
committed fixtures with v3 instead of v2 changes one more type beyond
oapi-codegen#2577, internal/test/aggregates/oneof's OneOfObject12, an allOf of two
oneOfs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@mromaszewicz
mromaszewicz requested a review from a team as a code owner September 25, 2026 02:46
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Adds test cases for a schema merging edge case.

The PR appears safe to merge based on this review; no new actionable finding or outstanding previous finding remains.

Summary

The PR makes v3 treat an allOf of unions as a combination of one variant from each union, preserving other unions’ data when setting a variant.

  • It adds accessors for referenced union members and updates discriminator handling.
  • Since the previous review, it has corrected key collection for renamed and deeply nested fields, shared-variant ownership, and marshaling-error handling, with regenerated v3 fixtures and tests.

Reviews (2) · Last reviewed commit: "fix(v3): union keys by their wire names,..."

Comment thread pkg/codegen/union_v3.go Resolved
Comment thread pkg/codegen/union_v3.go Resolved
Comment thread pkg/codegen/templates/union.tmpl Resolved
Comment thread pkg/codegen/union_v3.go Resolved
Review fixes for allOf of unions:

- A variant in two of the unions, such as Card in both
  `oneOf: [Card, Transfer]` and `oneOf: [Card, Courier]`, only got the
  keys the first union owns, so FromCard after FromCourier kept the
  courier's address and the value matched both of the second union's
  variants. Setting such a variant now replaces what each of its unions
  owns. Setting another variant still never removes the shared
  variant's keys.
- Owned keys used the spec's property names, but a json tag in
  x-oapi-codegen-extra-tags renames a field on the wire and
  x-go-json-ignore takes it off, so FromTransfer could leave a renamed
  card field behind. Keys are now the names the fields marshal as.
- A variant's keys stopped at eight levels of allOf; they now come from
  every level, with a visited set for cycles.
- From* for a variant of several unions, and From* for a $ref union,
  return a marshaling error before touching the union data, instead of
  clearing it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@mromaszewicz
mromaszewicz merged commit a64fa5d into oapi-codegen:main Sep 25, 2026
15 checks passed
@mromaszewicz
mromaszewicz deleted the aggregates/v3-unions-components branch September 25, 2026 03:20
mromaszewicz added a commit that referenced this pull request Sep 25, 2026
)

* feat(v3): an inline discriminated variant takes the value it pins

A discriminator maps its values to schema names: explicitly through its
mapping, or implicitly by each $ref's name. An inline variant has no
name, so v2 fails on a discriminated oneOf of inline variants ("not all
schemas were mapped"), or, next to a mapping, asks for a $ref instead.

An inline variant often says its value anyway:

    oneOf:
      - type: object
        properties:
          petType: {type: string, enum: [cat]}
          meow: {type: string}
      - type: object
        properties:
          petType: {const: dog}
          bark: {type: string}
    discriminator:
      propertyName: petType

schema-merging-behavior v3 maps such a variant to the value that a
const, or an enum of one value besides null, on its discriminator
property pins: on any declaration of the property, in the variant or
its allOf members (so a pinning member after a $ref base counts), or in
an allOf member of the property's own schema. Discriminator(),
ValueByDiscriminator() and the value From* stamps then work as for
mapped variants. A number or boolean value is spelled as encoding/json
writes it, as mapping keys are; and when the property declares no type,
as with 3.1's `const: true`, the pinned values give the discriminator
its JSON type. It is an error when that value is already an explicit
mapping key, another variant's value, or a $ref's implicit name, or when
it holds a quote, backtick, backslash or control character, which the
generated string literals can't hold (the validator checks mapping keys,
but not enum or const values). An inline variant that pins no value has
no discriminator value, with or without a mapping: ValueByDiscriminator
doesn't lead to it and its From* stamps nothing, while its As* and
From* work as for any variant. v2 errors on it next to a mapping and,
without one, maps it to the empty string, which several such variants
can't share.

The matrix gains oneof_discriminator_inline, two pinned variants and
one unpinned, which v1 and v2 reject with their old error, with a v3
test of dispatch and stamping. Generating the committed fixtures with
v3 changes nothing beyond #2578.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(v3): numeric discriminators, per-variant stamps and inexact pins

Review fixes for inline discriminated variants:

- JSON can write one number several ways, such as 1, 1.0 and 1e0, but
  ValueByDiscriminator compared the text, so `{"version": 1.0}` didn't
  reach the variant keyed "1". For an integer or number discriminator,
  v3 now compares the value as encoding/json writes the number, and
  cases spelled differently for one variant are one. Discriminator()
  still returns the text as written. This holds for explicit numeric
  mapping keys too.
- Variants whose typeless pins have different JSON types, such as
  `const: true` and `const: 1`, fell back to a string discriminator
  that stamps "true" and can't read `true`. That is now an error.
- An explicit mapping with two keys for one variant turned off the
  stamps of every variant, as v2 does (#2071), so an inline variant
  pinning `cat` next to them stamped nothing. v3 now stamps each
  variant exactly one value leads to; the aliased one still gets none.
  Under v3, internal/test/aggregates/oneof's ConfigSsh now stamps
  ssh_server next to the aliased ConfigHttp.
- kin-openapi reads numbers as float64, so a pinned integer of
  magnitude 2^53 or more may already be rounded, and From* would write
  a different value than the spec's. That is now an error that suggests
  a $ref variant with an explicit mapping key.

The matrix gains oneof_discriminator_number, a number discriminator
with pinned inline variants, which v1 and v2 reject with their old
error, with a v3 test of dispatch under several spellings.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(v3): reject one discriminator number leading to two variants

A numeric discriminator compares values as encoding/json writes the
number, so mapping keys like 1 and 1.0 are one value. When they lead to
different variants, the generated ValueByDiscriminator had two
`case "1":` labels and didn't compile. That is now a generation error
naming both keys; spellings of one number for the same variant are
still one case.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(v3): stamp a variant whose numeric keys spell one value

With 1 and 1.0 both mapped to one variant of a numeric discriminator,
ValueByDiscriminator has one case for them, but the stamp counted two
keys and gave the variant none, so From* could leave the discriminator
unset. A number's spellings now count as one value for the stamp, which
writes it as encoding/json does. v1 and v2, which don't compare numbers,
are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* refactor(v3): read a numeric discriminator as a number, not as text

An integer or number discriminator was compared as text, normalized by
rounding through float64: 9007199254740993, which an int64 holds and an
explicit mapping key can spell exactly, became 9007199254740992 in both
the switch and the stamp, breaking the workaround the error for large
inline pins suggests.

ValueByDiscriminator now decodes the discriminator property into the
Go type of its JSON kind, int64 for an integer and float64 for a
number, and switches on the mapping values written as literals of that
type. A number's spellings, like 1, 1.0 and 1e0, are one float64
value, as the variant's own field reads them; an integer is read as
encoding/json reads it into an int64, so 1.0 isn't one and is an error.
Stamps write the same literals.

At generation, each mapping value of such a discriminator must be a
JSON number of its kind: an integer's may be written with a zero
fraction or an exponent, like 1.0 or 1e3, when it's exact; 2.5, a value
beyond an int64 or a float64, or text that isn't a JSON number is an
error. Two values that are one number and lead to different variants
are still an error. String and boolean discriminators, and v1 and v2,
are unchanged.

The matrix gains oneof_discriminator_int64, whose mapping includes
2^53+1, with a v3 test that it dispatches and stamps exactly.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* fix(v3): -0 of a number discriminator is 0

A number discriminator's mapping values -0 and 0 became the literals -0
and 0, so the check for one number leading to two variants missed
them, and the generated float64 switch had two equal cases (Go
constants have no negative zero) and didn't compile. Zero is now
written as 0: -0 and 0 leading to different variants is the "same
number" error, and leading to one variant is one case. Incoming -0
already matched, since -0.0 == 0.0.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@mromaszewicz mromaszewicz added the bug Something isn't working label Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant