Skip to content

feat(v3): a oneOf or anyOf that only adds constraints makes no union - #2576

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

mromaszewicz merged 3 commits into
oapi-codegen:mainfrom
mromaszewicz:aggregates/v3-unions-constraints

Conversation

@mromaszewicz

Copy link
Copy Markdown
Member

Step 4 of the schema-merging-behavior: v3 work, after #2564, #2568, #2572 and #2574. It changes only v3, which is still opt-in and undocumented. v1 and v2 output doesn't change.

Step 4 covers unions and lands as four PRs, one after another. This one is the first:

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

What changes

A oneOf or anyOf is often used to say which of an object's properties must be present, not to list alternative types:

Contact:
  type: object
  properties:
    email: {type: string}
    phone: {type: string}
  oneOf:
    - required: [email]
    - required: [phone]

v2 generates a union for it anyway: a union json.RawMessage field, a variant of type any per branch, and As*/From*/Merge* for each. The type becomes harder to use without describing the data any better. v3 generates no union for such a list, wherever it appears:

Schema v2 v3
object with oneOf: [{required: [email]}, {required: [phone]}] struct with union json.RawMessage, type Contact0 = any, type Contact1 = any, and As/From/Merge for each type Contact struct { Email *string; Phone *string }
#839's spec: anyOf and oneOf of required lists on one object union with four any variants and twelve methods plain struct
component allOf: [$ref Contact, {oneOf: [{required: [email]}, …]}] a copy of Contact with union storage type Subject = Contact (the member only annotates, see #2574)
property or items schema with such a list a union type the plain struct

Which lists count as constraints

  • Every branch declares nothing that shapes a Go type except required and a boolean additionalProperties. Validation keywords such as minProperties are fine.
  • A branch may restate the type of the schema it constrains, as in {type: object, required: [email]}. That type is the schema's own, or, when it has none, the type its allOf members declare. So such branches next to or inside an allOf over an object count too.
  • A local $ref branch is judged by the schema it refers to. A $ref into another document, or a branch with x-go-type, is a type, so the union stays.
  • A 3.1 {type: 'null'} branch is passed over, since nullability is read where the schema is used. A list of nothing but null branches isn't one of constraints.
  • A branch with a type or format of its own is a type: oneOf: [{type: string, format: date}, {type: string, format: date-time}] is still a union.
  • A discriminator next to a list that only adds constraints is dropped along with it.

A validator still enforces these constraints. The Go type only stops pretending they are types.

External variants

The plan also called for treating external oneOf/anyOf variants as opaque in this step. It turned out union generation already uses them only as type names. The only things it reads from them are their property names, which keep those keys out of a union's additionalProperties, and their discriminator property's JSON type, which decides whether the discriminator is written as a string or a number. Both stay: forcing a string would break an integer discriminator whose variants are external.

Tests

  • pkg/codegen/merge_schemas_v3_test.go: TestConstraintOnlyUnionV3 covers which lists count, including null branches, additionalProperties, local and external $refs, x-go-type, and owners typed through allOf. TestConstraintOnlyUnionEndToEndV3 and TestConstraintOnlyUnionRestatedTypeV3 cover generated code for objects, properties, nested allOfs, sibling and member positions, and a real union that is kept.
  • The aggregate matrix gains oneof_constraints, anyof_oneof_constraints (allow coexistence of anyOf and oneOf fields in single schema definition #839's spec) and allof_member_constraints, with v1, v2 and v3 cells that round-trip their samples through the client and strict server at every position, also on Go 1.25. Hand-written v3 tests pin the Go types. No existing cell changes.

Fixtures

make generate changes no committed file, since the fixtures are generated with v2. Regenerating every fixture under v3 changes one type beyond #2574: internal/test/aggregates/oneof's OneOfObject10, an object whose oneOf only lists required properties, becomes a plain struct.

Refs #839

🤖 Generated with Claude Code

`oneOf: [{required: [email]}, {required: [phone]}]` says which of an
object's properties must be present; its branches aren't alternative
types. v2 generates a union for it anyway, with a variant of type `any`
per branch and As/From/Merge methods for each (issue oapi-codegen#839's spec gets
four), except when the list sits next to an allOf, where it was already
dropped.

schema-merging-behavior v3 generates no union for such a list anywhere:
on an object of its own, on a property, or in an allOf member. There it
also no longer counts as shaping the type, so `allOf: [$ref Contact,
{oneOf: [{required: [email]}, ...]}]` is Contact, an alias.

A list only adds constraints when every branch declares nothing that
shapes a Go type but `required` and a boolean `additionalProperties`,
and at most restates the type of the schema it constrains. That type is
the schema's own, or, when it has none, the type its allOf members
declare, so a oneOf of `{type: object, required: [...]}` branches next
to or inside an allOf over an object is also only constraints. A branch
that is a $ref into another document is a type; a local $ref is judged
by the schema it refers to. A 3.1 `{type: "null"}` branch is passed
over, since nullability is read from the schema where it is used, but a
list of nothing else isn't one of constraints.

External oneOf/anyOf variants were meant to become opaque in this step,
but union generation already only uses them as type names. What it
still reads from them is metadata: their property names, which keep
those keys out of a union's additionalProperties, and their
discriminator property's type, which decides whether the discriminator
is written as a string or a number. Both stay: forcing a string, as
planned, would break an integer discriminator whose variants are
external.

The matrix gains oneof_constraints, anyof_oneof_constraints (oapi-codegen#839's
spec) and allof_member_constraints, with new v1 and v2 cells; no
existing cell changes. The committed fixtures don't change either: they
are generated with v2. Generating them with v3 instead changes only
internal/test/aggregates/oneof's OneOfObject10, which becomes a plain
struct.

Refs oapi-codegen#839

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:08
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Low risk] Test fixtures for schema constraint handling.

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

Summary

This PR makes v3 omit unions when oneOf or anyOf branches only constrain an existing type, and adds code-generation and aggregate-matrix coverage for the behavior.

Reviews (3) · Last reviewed commit: "fix(v3): narrow an allOf's declared type..."

Comment thread pkg/codegen/merge_schemas_v3.go Resolved
Comment thread pkg/codegen/merge_schemas_v3.go Resolved
A member of an allOf whose oneOf branches restate the type another
member declares, like `{oneOf: [{type: object, required: [email]}, ...]}`
next to `{type: object, properties: ...}`, was judged against itself,
which declares no type. Alone, the list was still dropped when the
merged schema was judged again; next to another member's real union,
it joined that union as `map[string]any` variants. The list is now
judged against the member when it declares a type, and otherwise
against the composition.

A branch with x-go-type-name asks for a named Go type, as v2 generates
(`type EmailContact = any`), so it is a type, like one with x-go-type.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread pkg/codegen/merge_schemas_v3.go Resolved
declaredTypes took the type of the first allOf member that declares
one, so in `allOf: [{type: [object, string]}, {type: object, ...},
{oneOf: [{type: object, required: [email]}, ...]}]` the oneOf's
branches were checked against [object, string] and didn't count as
restating the type. Next to another member's real union they joined it
as `map[string]any` variants. declaredTypes now intersects the types
the schema and its members declare, as the merge does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@mromaszewicz
mromaszewicz merged commit d2689f0 into oapi-codegen:main Sep 25, 2026
15 checks passed
mromaszewicz added a commit that referenced this pull request Sep 25, 2026
…2578)

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

`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 #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
#2577, internal/test/aggregates/oneof's OneOfObject12, an allOf of two
oneOfs.

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

* fix(v3): union keys by their wire names, for every union a variant is in

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]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@mromaszewicz
mromaszewicz deleted the aggregates/v3-unions-constraints branch September 26, 2026 00:46
@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.

1 participant