Skip to content

fix: resolve Go field name collisions when JSON keys differ only by separator (#2495) - #2550

Merged
mromaszewicz merged 5 commits into
oapi-codegen:mainfrom
rifkir23:fix/field-name-collision-hyphen-underscore
Nov 15, 2026
Merged

mromaszewicz merged 5 commits into
oapi-codegen:mainfrom
rifkir23:fix/field-name-collision-hyphen-underscore

Conversation

@rifkir23

@rifkir23 rifkir23 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Problem

When two JSON properties in the same object differ only by their separator — e.g. host-fqdn and host_fqdn — both normalize to the same Go field name HostFqdn, producing a redeclared in this block compile error in the generated code. - is not a valid Go identifier character so stripping it is unavoidable, and _ folds to the same PascalCase, so the two collide.

This is reproducible against real specs (the issue references the Tenable Vulnerability Management API, whose info object contains both host-fqdn and host_fqdn).

Fixes #2495

Fix

Resolve Go field-name collisions within a struct in GenFieldsFromProperties. The first property to claim a name keeps it; each later property that would collide gets an incrementing numeric suffix (HostFqdn, HostFqdn2, HostFqdn3, ...), re-checked so a suffixed name cannot itself collide. This matches the direction suggested in the issue ("suffix numbers on colliding fields") and is consistent with the collision-resolution the codebase already does elsewhere (enum constants, type names).

Only the Go identifier changes — the JSON struct tag still uses the original JsonFieldName, so the wire format is unchanged and round-trips exactly as before. Explicit x-go-name overrides continue to work and take precedence.

Tests

Added TestGenFieldsFromProperties_ResolvesGoFieldNameCollisions: two properties (host-fqdn, host_fqdn) now generate HostFqdn and HostFqdn2 with their original JSON tags preserved. Verified the test FAILS without the fix (both fields render as HostFqdn, matching the reported compile error) and PASSES with it. Full pkg/codegen suite passes; gofmt and go vet are clean.

@rifkir23
rifkir23 requested a review from a team as a code owner September 3, 2026 13:21
@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the repeated-blank-field regression is fixed.

Summary

Adds optional fixes for colliding Go field names while preserving JSON names and explicit x-go-name overrides.

  • The generator gives colliding JSON properties distinct Go field names.

Reviews (4) · Last reviewed commit: "Don't treat blank fields as a name colli..." · Reviewed by Greptile

Comment thread pkg/codegen/schema.go Resolved
Comment thread pkg/codegen/schema.go Resolved
…eparator (oapi-codegen#2495)

Move collision resolution from GenFieldsFromProperties to a single-source
resolver (ResolvePropertyGoFieldNameCollisions) that populates an unexported
resolvedGoFieldName on each Property. GoFieldName() now returns the resolved
name, so the struct declaration AND the generated marshal/unmarshal boilerplate
(union, additional-properties templates) all share the same disambiguated
field name. Also reserves the synthetic AdditionalProperties field name so a
real property named 'additionalProperties' does not collide with it.

Fixes oapi-codegen#2495
@rifkir23
rifkir23 force-pushed the fix/field-name-collision-hyphen-underscore branch from ba4b9de to c1eb68a Compare September 3, 2026 15:35
@rifkir23

rifkir23 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

thanks for the careful review, both points were valid. i reworked the fix so it is a single source of truth instead of only touching the struct declaration:

  • collision resolution now runs once per schema (ResolvePropertyGoFieldNameCollisions) and stores the disambiguated name on the property. GoFieldName() returns it, so the struct declaration and the generated marshal/unmarshal boilerplate (union and additional-properties templates, which all read GoFieldName) now use the same name. this fixes the "boilerplate reads the wrong field" case.
  • the resolver reserves the synthetic AdditionalProperties field name first, so a real property named additionalProperties (or one using x-go-name: AdditionalProperties) is suffixed instead of producing a duplicate declaration.

added a test for the additional-properties reservation case as well. full pkg/codegen suite and the rest of ./... pass, gofmt and vet clean.

…ision-hyphen-underscore

Conflicts in pkg/codegen/schema.go and schema_test.go were adjacent
additions; both sides are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@mromaszewicz

Copy link
Copy Markdown
Member

Thanks for the rework — the marshal/unmarshal boilerplate and the synthetic AdditionalProperties field are both handled correctly now. I merged main into the branch and tested it against a set of collision specs. Regenerating all the committed fixtures produces no diff, so this only changes output that failed to compile before.

Two problems with the naming scheme itself mean this can't merge as it stands.

1. Names are not stable as a spec evolves

Names are handed out in sorted property order, and the first property keeps the bare name. - sorts before _, so:

# before
properties:
  host_fqdn: {type: string}     # -> HostFqdn

# after the API adds a property
properties:
  host-fqdn: {type: string}     # -> HostFqdn
  host_fqdn: {type: string}     # -> HostFqdn2

HostFqdn now refers to a different JSON key. Both fields have the same type, so consumer code keeps compiling and silently reads and writes the wrong property. That is worse than the compile error we have today.

A suffixed name can also take another property's natural name:

properties:
  host-fqdn:  {type: string}    # -> HostFqdn
  host_fqdn:  {type: string}    # -> HostFqdn2
  host_fqdn2: {type: integer}   # -> HostFqdn22

host_fqdn2 would have been HostFqdn2 on its own, and it loses that name to a sibling.

2. An explicit x-go-name gets rewritten

The description says x-go-name overrides take precedence, but they go through the same first-come pass:

properties:
  zed: {type: string}                      # -> Zed
  zzz: {type: integer, x-go-name: Zed}     # -> Zed2

The user asked for Zed and silently got Zed2. A name the user chose explicitly should never be changed by the generator; if it collides, the auto-derived name should give way, and two explicit names colliding should be an error.

Also

  • Colliding query parameters (host-fqdn and host_fqdn as in: query) still produce a duplicate field in the Params struct; that struct is built on a separate path that doesn't go through the resolver.
  • ResolvePropertyGoFieldNameCollisions should be unexported.

The underlying requirement is that a field's name depends only on that property, not on which siblings happen to exist or how they sort. I'm still thinking about the right scheme for that and will follow up here.

@mromaszewicz mromaszewicz added the enhancement New feature or request label Nov 15, 2026
mromaszewicz and others added 2 commits November 15, 2026 08:15
Numbering the fields of colliding properties made a field's name depend
on its siblings. Properties are named in sorted order and the first kept
the bare name, so adding "host-fqdn" to a schema which had "host_fqdn"
handed HostFqdn to the new property, and code using it went on compiling
against a different JSON property. A numbered name could also take the
name another property derives on its own, and a name given with
x-go-name was renumbered like any other.

A collision is now handled the way colliding type names are. Without
output-options.resolve-type-name-collisions it is an error which names
the properties and points at x-go-name and at the option. With the
option, every colliding property is renamed to its derived name and a
short hash of its JSON name, such as HostFqdn_cea8c90, the scheme shared
path parameters already use. No property keeps the bare name, so a name
depends on nothing but its own property. A name given with x-go-name is
never changed, nor is the AdditionalProperties field, and two of those
colliding is an error.

The option keeps its name, so that existing configurations keep working,
and its documentation now says that it covers field names too.

Only output which did not compile changes: regenerating every fixture
changes nothing but the cases added to internal/test/naming/conflicts.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Explain, next to x-go-name, why two properties can get the same Go field
name, the error that reports it, and the two ways to resolve it: naming
a field with x-go-name, or resolve-type-name-collisions.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@mromaszewicz

Copy link
Copy Markdown
Member

Following up on my earlier comment: I've pushed two commits on top of your branch that replace the numeric suffixes. Your approach of storing the resolved name on the Property, so the struct and the marshaling code agree, is kept as is. What changed is how names are chosen.

Behaviour now

We already have an opt-in resolver for colliding type names (output-options.resolve-type-name-collisions), and field names now follow it.

Option off (the default): a collision fails generation with an error that names the properties and both fixes:

schema 'Info': property 'host-fqdn', property 'host_fqdn' would all be the Go field 'HostFqdn'; please use x-go-name to rename them, or set output-options.resolve-type-name-collisions to have them renamed automatically

Option on: every colliding property is renamed to its derived name plus a short hash of its JSON name:

type FieldCollisions struct {
	HostFqdn_cea8c90 *string `json:"host-fqdn,omitempty"`
	HostFqdn_bcac5e8 *string `json:"host_fqdn,omitempty"`
	HostFqdn2        *int    `json:"host_fqdn2,omitempty"`
	Zed_ce5c161      *string `json:"zed,omitempty"`
	Zed              *int    `json:"zzz,omitempty"` // x-go-name: Zed
}

Why

  • No property keeps the bare name. The generator can't tell which property was there first, so giving one of them HostFqdn is what allowed a later spec change to silently repoint it. With every collider renamed, the first collision breaks consumer code loudly, and after that each name depends only on its own property.
  • The hash is of the JSON property name, so the same property gets the same field name in every schema it is merged into, and host_fqdn2 keeps HostFqdn2.
  • x-go-name is never rewritten, and neither is the synthetic AdditionalProperties field. The derived name gives way; two explicit names colliding is an error.
  • It reuses an existing scheme. Shared path-item parameters (anyOf in parameters is not well supported #2090) already disambiguate with a short FNV hash applied to every collider, and this uses the same helper.

Also in these commits

  • The resolver is unexported and returns an error.
  • The unit tests are replaced with ones for the behaviour above, and internal/test/naming/conflicts gains two schemas with JSON round-trip tests, one through the generated additional-properties marshaling.
  • The option's documentation now says it covers struct field names and kept its name for backwards compatibility, and docs/extensions.md has a new section next to x-go-name describing the collision and both ways to resolve it.

Regenerating all fixtures changes nothing except the cases added here, so only output that failed to compile is affected. Colliding query parameters are out of scope for this PR.

The PR title and description still describe numeric suffixes; I'll write the squash commit message to match what is merged.

Comment thread pkg/codegen/schema.go Resolved
A struct may declare the blank identifier any number of times, so two
properties named "_" with x-go-name, under
allow-unexported-struct-field-names and
x-oapi-codegen-only-honour-go-name, generated code which compiled. The
collision check reported them as one field declared twice, and
resolve-type-name-collisions could not help, since both names are
explicit.

Leave "_" out of the collision check.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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.

oapi-codegen v2 produces duplicate Go field names when JSON keys differ only by separator (hyphen vs underscore)

3 participants