Skip to content

feat(codegen): fold OpenAPI 3.1 const-based oneOf without outer type into enums - #2520

Merged
mromaszewicz merged 8 commits into
oapi-codegen:mainfrom
sorochinssky:fix/enum-to-oneof-no-type
Aug 17, 2026
Merged

mromaszewicz merged 8 commits into
oapi-codegen:mainfrom
sorochinssky:fix/enum-to-oneof-no-type

Conversation

@sorochinssky

Copy link
Copy Markdown
Contributor

Summary

OpenAPI 3.1 expresses string/integer enums as a oneOf whose branches each carry a scalar const. When the outer schema omits type (the common idiom, since the consts imply the family), detectEnumViaOneOf previously required an explicit outer scalar type and fell through to the union generator, emitting:

type PetStatus struct {
    union json.RawMessage
}
type PetStatus0 = interface{}

losing the enum values and names entirely.

This change lets the scalar family be inferred from the per-branch const values when the outer type is absent:

PetStatus:
  oneOf:
    - const: available
      title: Available
    - const: pending
      title: Pending
    - const: sold
      title: Sold

now produces a typed enum:

type PetStatus string
const (
    Available PetStatus = "available"
    Pending   PetStatus = "pending"
    Sold      PetStatus = "sold"
)

The integer variant (Port with whole-number consts) likewise emits Port int + numeric constants.

Behaviour

  • Outer type present — unchanged (must be string/integer to be treated as an enum).
  • Outer type absent — family inferred from the const values; every branch must agree and each const must be a plain scalar (string, or whole-number integer). Mixed/fractional/bool/object/array → falls through to the standard union path.
  • The detected type drives the Go base-type mapping via a shallow copy of the schema (the caller's schema is never mutated), so oapiSchemaToGoType yields string/int instead of falling into the generic interface{} branch.
  • SkipEnumViaOneOf escape hatch and the negative paths (missing title/const, object/mixed oneOf) still fall through to the union generator.

Tests

  • TestEnumViaOneOfConstType — unit coverage of the new inference helper (string / whole-number / fractional / bool / object / array / mixed).
  • Integration: PetStatus (string, no type) and Port (integer, no type) added to internal/test/openapi31/spec.yaml, with named-constant + JSON round-trip assertions.
  • Confirmed the existing with-type enums (Severity, Color) and the negative MixedOneOf case still pass.

Verification

go build ./...
go vet ./...
go test ./pkg/codegen/ -run TestEnumViaOneOfConstType
go test ./internal/test/openapi31/   # (run from internal/test module)

all green.

…into enums

OpenAPI 3.1 can express string/integer enums as a `oneOf` whose branches
each carry a scalar `const`, with the top-level schema omitting `type`
entirely (the consts imply the family). Previously detectEnumViaOneOf
required an explicit outer scalar `type`, so such schemas fell through to
the generic union path and emitted `type PetStatus struct { union
json.RawMessage }` plus a `PetStatus0 = interface{}` — losing the enum
values and names.

Now, when the outer `type` is absent, the scalar family is inferred from
the per-branch `const` values (string, or whole-number integer). Every
branch must agree and every const must be a plain scalar; otherwise the
union path is preserved. The detected type drives the Go base-type mapping
via a shallow schema copy, so a no-type const oneOf now emits e.g.
`type PetStatus string` with the named constants, instead of interface{}.

When the outer `type` is present, behaviour is unchanged (must be
string/integer to be treated as an enum). The SkipEnumViaOneOf escape
hatch and the negative paths (missing `title`/`const`, object/mixed
oneOf) continue to fall through to the union generator.

Adds a focused unit test for the inference helper and integration coverage
(PetStatus string no-type, Port integer no-type) with constants +
JSON round-trip, plus guards that the existing with-type enums still pass.
@sorochinssky
sorochinssky requested a review from a team as a code owner August 14, 2026 11:51
@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This follow-up adds safe handling for large integer constants while retaining typeless OpenAPI 3.1 oneOf enum inference.

  • Infers string or integer enum types from branch-level scalar constants.
  • Widens inferred integer enums to int64 when values exceed the portable int32 range.
  • Rejects parsed integer constants at or beyond the ambiguous float64 precision boundary.
  • Adds unit and OpenAPI 3.1 integration coverage for inferred enums, widening, JSON round trips, and invalid inputs.

Confidence Score: 5/5

The pull request appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
pkg/codegen/schema.go Implements typeless enum inference, integer-width selection, exactness validation, and propagation of inferred type information without mutating the input schema.
pkg/codegen/schema_test.go Covers scalar-family inference, integer precision boundaries, widening, fallback behavior, and schema immutability.
internal/test/openapi31/spec.yaml Adds representative OpenAPI 3.1 string and integer const-based oneOf schemas.
internal/test/openapi31/openapi31.gen.go Generated output consistently reflects the new typed enums and widened FileSize representation.
internal/test/openapi31/openapi31_test.go Verifies generated constants, underlying integer widths, and JSON serialization behavior.

Reviews (2): Last reviewed commit: "feat(codegen): fail on enum-via-oneOf co..." | Re-trigger Greptile

Comment thread pkg/codegen/schema.go Resolved
When the outer schema omits `type`, the scalar family is inferred from the
per-branch `const` values. A whole-number const that exceeds the Go int64
range (e.g. 2^63 or larger) was still classified as an integer and emitted
verbatim into a typed Go enum constant. Such a constant does not fit the
target integer type, so formatting the generated source failed.

Now the int64 bounds are enforced when inferring the integer family:

- float64 numbers must be whole AND in [-2^63, 2^63) (the high end is
  strict because math.MaxInt64 rounds up to 2^63 when widened to float64).
- integral defensive types (uint/uint64) are range-checked against int64.

Out-of-range consts fall through (ok=false) to the union generator instead
of producing an invalid typed enum. Adds unit coverage for the boundary
values and a detectEnumViaOneOf case proving an overflowing const falls
through.
@sorochinssky

Copy link
Copy Markdown
Contributor Author

Hi maintainers — could someone approve running the CI workflow on this PR? It's currently stuck at the fork-PR approval gate (the CI run shows action_required before any jobs are dispatched).

For context: the automated review note about integer inference permitting overflowing constants has already been addressed in code — commit bcf47f0d ("fix(codegen): reject enum-via-oneOf consts outside the int64 range") adds a toInt64 guard, and the TestEnumViaOneOfOverflowFallsThrough unit test covers the overflow case.

Local verification passes: go build ./..., go vet ./pkg/codegen/, gofmt on the touched files, the full pkg/codegen suite, and the openapi31 integration tests are all green.

Summary of the change: OpenAPI 3.1 expresses scalar enums as oneOf of const values. Without an outer type, the model generator previously fell back to a generic union / interface{}, so enum constants were never emitted. This PR folds that shape into a proper typed enum (respecting the reflection that a oneOf whose variants are all scalar consts is an enum), emits the EnumValues/Valid() helpers, and guards against emitting integer constants that overflow int64.

Thanks for taking a look.

@mromaszewicz

Copy link
Copy Markdown
Member

I've actually been playing with your PR this morning on my own. I found a few edge cases (which is why my code that you fixed has a type declaration, and doesn't infer type). I'll comment in full later, busy right now. This will get merged, we just need to make some small fixes.

…o-type

# Conflicts:
#	internal/test/openapi31/spec.yaml
#	pkg/codegen/schema_test.go
@mromaszewicz

Copy link
Copy Markdown
Member

I'm resolving the conflicts with main and pushing an update to your branch.

mromaszewicz and others added 3 commits August 16, 2026 20:52
…rough

The test mutated the package-level globalState (is31, SkipEnumViaOneOf)
without restoring it, leaking that state into every test that ran after
it. Adopt the save/restore pattern the surrounding tests already use.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The type inference for a typeless enum-via-oneOf ran inside the branch
loop, interleaved with the shape checks, and the caller had to splice the
result back into a copy of the schema afterwards. Hoist it: resolve the
outer type once, before the loop, so the loop returns to collecting titles
and consts and the caller goes back to a single call.

detectEnumViaOneOf now hands back the schema that drives the Go base-type
mapping -- the input as-is when it declares a type, or a shallow copy
carrying the inferred one -- which keeps the copy next to the inference
that motivates it.

Classification runs narrowest-first, following the JSON value kinds:
boolean, then number split into integer/number by whether the value is
whole, then string last, since string is the family that can spell
anything. Families are reported honestly rather than pre-filtered; the
existing scalar gate is what turns away booleans and fractions.

Integer width is chosen against the values. Plain int is the natural Go
enum type and covers the int32 range, which is also the range that stays
correct on a 32-bit build; one value past it widens the enum to int64 via
format.

There is no rung above int64, and no uint64 rung. kin-openapi decodes
every JSON number into a float64, so an integer above 2^53 has already
been rounded before we see it -- uint64 max arrives as
1.8446744073709552e19. Emitting that would bake a wrong number into a
constant, so it now falls through to the union generator. The bound moves
from 2^63 to 2^53 for the same reason: 2^63 only asked whether the value
fit int64, not whether it was still the value the document wrote.

This also drops toInt64 and the defensive integral cases it served. Const
is populated by kin-openapi's JSON decode, which yields only nil, bool,
float64, string, []any and map[string]any.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Integer consts arrive as float64 and were rendered with %v, which writes
round values in exponent form: a const of 5000000000 generated

    SizeHuge FileSize = 5e+09

Go accepts that as an integer constant, but nobody writes a port number
or a byte count that way. Format whole numbers with strconv instead.

Only the spelling changes, never the value, and only for consts large
enough that %v reached for an exponent. This applies to the enums that
declare an outer type as well, which had the same rendering.

Also adds FileSize to the openapi31 fixture: one const past the 32-bit
range, so the widening to int64 is covered end to end rather than only in
the unit tests.

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

Copy link
Copy Markdown
Member

kin-openapi parses all those values in the const using float64, so it's pointless to deal with uints. I'm going to use just int and int64 for scalars, where appropriate.

mromaszewicz and others added 2 commits August 16, 2026 21:43
The exactness guard tested the wrong side of the bound. 2^53 is itself
representable, so it passed -- but 2^53+1 is not, and rounds to exactly
2^53 on the way in. A spec writing 9007199254740993 therefore reached the
enum path as 9007199254740992 and generated

    BigOneTooBig BigOne = 9007199254740992

which compiles, matches nothing the document declared, and warns about
nothing. The value must be rejected from 2^53 up: at the boundary the
float64 no longer identifies a single integer, which is the same reason
the larger ones were already rejected.

The unit tests probed 2^53+2 and -2^53-2, stepping over the only values
that actually round, and asserted the bad accept at 2^53. They now cover
both boundary directions and the largest value that stays unambiguous.

Also strengthens TestFileSizeWidensToInt64, which passed whether or not
the widening happened: int64(SizeHuge) compares equal on any 64-bit build,
so only a 32-bit build could have caught a regression and nothing in
`make test` runs one. It now asserts the underlying reflect.Kind, with a
matching test that a small-valued enum stays int.

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

An integer const at 2^53 or beyond reaches the generator already rounded,
because kin-openapi decodes every JSON number into a float64. Until now
the two spellings handled that differently and both badly: the inferred
one quietly fell through to the union generator, and the declared one
emitted a constant that would not compile.

Neither serves the author. Every branch carrying title + const says
plainly that an enum was intended, so substituting a shapeless union hides
the problem, and a compile error names the generated file rather than the
schema. Report it instead, from one check covering both spellings, naming
the branch, the value as it actually arrived, and the two ways out.

The check runs only once the schema is confirmed to be the idiom, so a
oneOf that is not an enum -- disagreeing families, an object const, a
branch without a title -- still falls through silently as before. That
distinction is why classification no longer rejects large values:
constScalarFamily answers "what family is this", which stays a question
about shape, and exactness became a separate question with a separate
answer.

skip-enum-via-oneof needs no special handling. It returns before any of
this, so opting out of the idiom opts out of failing over it, and the
error message points at the flag for anyone who wants the old union.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mromaszewicz mromaszewicz added enhancement New feature or request notable changes Used for release notes to highlight these more highly labels Aug 17, 2026
@mromaszewicz
mromaszewicz merged commit ae2ec8a into oapi-codegen:main Aug 17, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request notable changes Used for release notes to highlight these more highly

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants