Skip to content

Merge properties when combining schemas with allOf #2107

Closed

Description

@skomorokh

Currently oapi-codegen doesn't merge property definitions when combining schemas with allOf and instead takes the complete property from the last one it sees:

// TODO: detect conflicts

This means we can't create a schema for a JSON Merge Patch endpoint that inherits types and everything else from a base schema and just makes some of them nullable (as sending null is how one clears a value in RFC 7396). This approach is described here: https://blog.stoplight.io/reuse-openapi-descriptions Instead we have to maintain redundant types/formats/descriptions/etc. for the properties.

From this doc in the spec it does seem like properties are expected to be inherited: https://swagger.io/docs/specification/v3_0/data-models/inheritance-and-polymorphism/

And other implementations seem to merge them: https://github.com/Redocly/redoc/blob/34623575ce4741280df4c960f926c3751022b026/src/services/OpenAPIParser.ts#L276

Understandably a full merge would be an undertaking, reflection is not ideal, and something like mergo would be a somewhat heavy extra dep. However, even a shallow merge of a subset of Schema properties would enable this PATCH use case and presumably many others.

Activity

  1. mromaszewicz commented on Jun 22, 2026

    @mromaszewicz
    Member

    This is an interesting one, because it's difficult to do in Go's type system.

    I guess what we want is an additive merge of all the different properties.

    I commonly use the pattern in my own code of using an allOf which adds a required property with a list of fields, which merges cleanly at the top level, but I never considered that field merges would do this recursively.

    It's a bit of functionality that's been missing a long time.

  2. bendrucker commented on Aug 14, 2026

    @bendrucker
    Contributor

    Still present on main (6768b63). Two things to add: a second spec shape that reaches the same overwrite, and evidence that the symptom is silent type loss rather than missing constraints.

    Sibling properties Next to allOf

    The original report is about two allOf members. The same defect hits a schema whose properties sit as a sibling of allOf, which is the idiomatic way to mark an inherited field readOnly:

    components:
      schemas:
        CreateWidget:
          type: object
          required: [name, sku]
          properties:
            name:
              type: string
              description: Name of the widget.
              minLength: 1
            sku:
              type: string
            size:
              type: integer
        Widget:
          allOf:
            - $ref: '#/components/schemas/CreateWidget'
          properties:
            name:
              readOnly: true

    Generated with generate: {models: true}:

    type CreateWidget struct {
    	// Name Name of the widget.
    	Name string `json:"name"`
    	Size *int   `json:"size,omitempty"`
    	Sku  string `json:"sku"`
    }
    
    type Widget struct {
    	Name any    `json:"name,omitempty"`
    	Size *int   `json:"size,omitempty"`
    	Sku  string `json:"sku"`
    }

    Widget.Name should be string. It loses the inherited type, the description, minLength, and its place in required. Sku and Size are untouched, so the damage is confined to the overridden property.

    This shape reaches the same code by a newer route. hasStructuralSiblings in pkg/codegen/schema.go injects the parent as the final allOf member so its siblings aren't discarded. That makes the bare {readOnly: true} the last member, so it becomes s2 in the left fold and wins outright at merge_schemas.go:403:

    result.Properties = make(map[string]*openapi3.SchemaRef, len(s1.Properties)+len(s2.Properties))
    maps.Copy(result.Properties, s1.Properties)
    // TODO: detect conflicts
    maps.Copy(result.Properties, s2.Properties)

    The sibling-merging work fixed the outer level (the parent's properties survive at all) without changing what happens when a key collides.

    Related

    #1883 was closed as fixed, and its closing comment reports this output:

    type UpdateIdentityJSONBody struct {
    	IdentityId interface{} `json:"identity_id,omitempty"`
    }

    identity_id is $ref: IdentityId, a string with minLength/maxLength. The error merging schemas for AllOf: merging two schemas with different ReadOnly abort is gone, and the output compiles. But interface{} there is this issue. Generation completing and the result compiling is what makes it easy to miss: nothing errors, and the type is wrong.

    Importance

    The original motivation was JSON Merge Patch. The readOnly override is the more common trigger, and it degrades the type to any, which propagates into every client call site. We hit it in a real spec (Honeycomb's) where Column is allOf: [CreateColumn] with a sibling key_name: {readOnly: true}, and had to add an OpenAPI overlay action restoring type: string to keep the generated client usable.

    A shallow merge of the colliding property schemas, rather than a wholesale replace, would cover this and the PATCH case. Taking the union field-by-field and letting the later member override only what it actually sets would be enough. That is the same rule already applied one level up.

  3. mromaszewicz commented on Sep 26, 2026

    @mromaszewicz
    Member

    This is now supported on main, with the new schema-merging-behavior: v3 (#2572). When several allOf members declare a property, v3 merges the declarations instead of taking the last one, so a member can refine a property and keep the rest of it. Your JSON Merge Patch case:

    Patch:
      allOf:
        - $ref: '#/components/schemas/Base'   # name: {type: string}, required
        - properties:
            name: {nullable: true}

    v3 generates Name *string: Base's type, made nullable by the second member. v2 generates Name any. The declarations are merged like an allOf of their own, so nested objects merge their properties too, and descriptions and field-level extensions such as x-go-name are kept. Declarations no value could match, such as type: integer and type: string, are an error that names both members.

    To try it, set this in your configuration:

    compatibility:
      schema-merging-behavior: v3

    There's no release with v3 yet, so you'll need the latest main, for example go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@main --config=config.yaml spec.yaml. docs/schema-merging.md describes how v3 differs from v2. v3 is an option for now, and we plan to make it the default once it has been tested for a while, so we're eager to hear your feedback: whether it works with your specs, and anything it generates that you didn't expect.


    This message was generated by AI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions