Repository navigation
feat(codegen): fold OpenAPI 3.1 const-based oneOf without outer type into enums - #2520
Conversation
…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.
Greptile SummaryThis follow-up adds safe handling for large integer constants while retaining typeless OpenAPI 3.1
Confidence Score: 5/5The pull request appears safe to merge. No blocking failure remains.
|
| 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
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.
|
Hi maintainers — could someone approve running the CI workflow on this PR? It's currently stuck at the fork-PR approval gate (the For context: the automated review note about integer inference permitting overflowing constants has already been addressed in code — commit Local verification passes: Summary of the change: OpenAPI 3.1 expresses scalar enums as Thanks for taking a look. |
|
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
|
I'm resolving the conflicts with main and pushing an update to your branch. |
…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]>
|
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 |
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]>
Summary
OpenAPI 3.1 expresses string/integer enums as a
oneOfwhose branches each carry a scalarconst. When the outer schema omitstype(the common idiom, since the consts imply the family),detectEnumViaOneOfpreviously required an explicit outer scalartypeand fell through to the union generator, emitting:losing the enum values and names entirely.
This change lets the scalar family be inferred from the per-branch
constvalues when the outertypeis absent:now produces a typed enum:
The integer variant (
Portwith whole-number consts) likewise emitsPort int+ numeric constants.Behaviour
typepresent — unchanged (must bestring/integerto be treated as an enum).typeabsent — family inferred from theconstvalues; 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.oapiSchemaToGoTypeyieldsstring/intinstead of falling into the genericinterface{}branch.SkipEnumViaOneOfescape hatch and the negative paths (missingtitle/const, object/mixedoneOf) still fall through to the union generator.Tests
TestEnumViaOneOfConstType— unit coverage of the new inference helper (string / whole-number / fractional / bool / object / array / mixed).PetStatus(string, no type) andPort(integer, no type) added tointernal/test/openapi31/spec.yaml, with named-constant + JSON round-trip assertions.Severity,Color) and the negativeMixedOneOfcase still pass.Verification
all green.