Skip to content

Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING#23543

Open
jpfinne wants to merge 23 commits intoOpenAPITools:masterfrom
jpfinne:feature/normalizer_REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING
Open

Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING#23543
jpfinne wants to merge 23 commits intoOpenAPITools:masterfrom
jpfinne:feature/normalizer_REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING

Conversation

@jpfinne
Copy link
Copy Markdown
Contributor

@jpfinne jpfinne commented Apr 14, 2026

fixes #19261, #912, #23527, #22013, #23276, #14769, #16391, #19194, #19261, #23577 (and probably others) when using the new REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalizer option.

The goal is to use inheritance when composition or useOneOfInterfaces don't work.

The normalizer converts oneOf with discriminators.
It ensures that:

  • discriminator mappings are created (using x-discriminator-value if present or single enum value).
  • It removes the oneOf.
  • It ensures that the referenced children correctly has an allOf to the parent.
  • it removes the single enum value in the referenced mappings if already present in the parent.

For the java generators, it means that inheritance with a base class class is generated instead of an interface.

Edge cases don't do anything:

  • no discriminator property
  • oneOf with inline schema
  • non matching number of oneOf nodes and number of discriminator mappings (if present)

Warning: the normalizer does not support inline oneOf (as seen in #23276 and in #15 using composed-oneof.yaml). A warning is outputted Inline oneOf schema not supported by REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalization. No transformation is done.
It might be nice to refactor the inline oneOfs in the OpenAPINormalizer, similar to REFACTOR_ALLOF_INLINE_SCHEMAS done in the InlineModelResolver.
ps: it can't be done in InlineModelResolver because it runs after the normalizer.

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @martin-mfg (2023/08)
| @cachescrubber (2022/02) @welshm (2022/02) @MelleD (2022/02) @atextor (2022/02) @manedev79 (2022/02) @javisst (2022/02) @borsch (2022/02) @banlevente (2022/02) @Zomzog (2022/09) @martin-mfg (2023/08)
@wing328

Please review


Summary by cubic

Adds a normalizer that converts oneOf into discriminator.mapping, removes oneOf, and wires allOf inheritance so Java and spring generators emit class hierarchies with correct Jackson annotations.

  • New Features

    • REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING=true: builds discriminator.mapping from oneOf $refs (merges existing mappings), removes oneOf, adds an allOf parent $ref to children and moves child properties under that allOf; removes the discriminator property from children when the base defines it; skips inline or non-$ref oneOf with a warning. Discriminator values prefer x-discriminator-value, else a single enum on the discriminator property (resolving $ref), else the schema name. Docs add a spring CLI example; tests/samples (issues 912, 14769, 19261, 22013, 23527, 23577) validate JsonTypeInfo/JsonSubTypes and assert JsonSubTypes.Type name/value pairs and inheritance.
  • Bug Fixes

    • Replaced fragile parent checks with isParentReferencedInChild to avoid duplicate allOf links and recursion issues; fixed allOf construction and discriminator property lookup via ModelUtils.getReferencedSchema; added warnings for missing discriminator property, mapping/oneOf size mismatch, and unsupported inline cases; after moving child properties under allOf, now also clears leftover child metadata (e.g., type, additionalProperties, and other fields) to prevent duplication in generated models.

Written for commit 0facdf7. Summary will update on new commits.

@winklerm
Copy link
Copy Markdown

Thanks a lot for this quick fix!

I have verified it resolves the issue for our use-case.

@winklerm winklerm mentioned this pull request Apr 15, 2026
6 tasks
@jpfinne
Copy link
Copy Markdown
Contributor Author

jpfinne commented Apr 15, 2026

Thanks a lot for this quick fix!

I have verified it resolves the issue for our use-case.

This bug has bother me for months. I've initially tried to fix it in DefaultCodeGen, but the handling of composition vs inheritance is very complex.

I'll work on the PR. In the meantime you can create a custom normalizer:

NORMALIZER_CLASS: Set to full classname of a class extending the default org.openapitools.codegen.OpenAPINormalizer. It allows customization of the default normalizer

@jpfinne jpfinne changed the title normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING Apr 17, 2026
@jpfinne jpfinne marked this pull request as ready for review April 18, 2026 16:16
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 18 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/customization.md">

<violation number="1" location="docs/customization.md:654">
P3: Malformed Markdown adds a stray backtick to the documented normalizer name, making the docs show/copy the option incorrectly.</violation>
</file>

<file name="pom.xml">

<violation number="1" location="pom.xml:27">
P1: Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.</violation>
</file>

<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1608">
P2: `schema.getOneOf()` is iterated without a null guard after `processSimplifyOneOf()` can clear `oneOf`, causing a potential NPE in discriminator replacement.</violation>

<violation number="2" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1619">
P1: Unconditionally removing `oneOf` can drop subtype metadata when the discriminator mapping is partial or not rebuilt.</violation>

<violation number="3" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1630">
P2: `hasParent()` returns false immediately when it encounters a visited `allOf` branch, so later siblings are never checked and an existing parent ref can be added again.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread pom.xml
@@ -23,6 +23,15 @@
<developerConnection>scm:git:git@github.com:openapitools/openapi-generator.git</developerConnection>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At pom.xml, line 27:

<comment>Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.</comment>

<file context>
@@ -23,6 +23,15 @@
         <url>https://github.com/openapitools/openapi-generator</url>
     </scm>
+    <modules>
+        <module>modules/openapi-generator-core</module>
+        <module>modules/openapi-generator</module>
+        <module>modules/openapi-generator-cli</module>
</file context>
Fix with Cubic

Comment thread docs/customization.md Outdated
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1780">
P1: Regression in `hasParent()`: the new visited check short-circuits recursive traversal, so existing parent refs nested under `allOf` are missed and duplicate parent inheritance refs can be added.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@jpfinne jpfinne marked this pull request as draft April 19, 2026 19:35
@jpfinne jpfinne marked this pull request as ready for review April 20, 2026 08:30
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 18 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:649">
P2: `ensureInheritanceForDiscriminatorMappings()` is invoked on the pre-normalization schema instance, so any normalization path that returns a new Schema object makes the discriminator mapping changes apply to a discarded object.</violation>

<violation number="2" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1776">
P1: Moving `properties` into a nested `allOf` schema without moving `additionalProperties` changes validation semantics and can reject properties that should be allowed.</violation>
</file>

<file name="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/JavaFileAssert.java">

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/JavaFileAssert.java:62">
P2: `extendsClass(...)` does not verify the declaration is a class, so an interface with matching extended types can satisfy the assertion and hide a generator regression.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

schemas.put(schemaName, normalizeSchema(schema, new HashSet<>()));

if (getRule(REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING)) {
ensureInheritanceForDiscriminatorMappings(schema, schemaName);
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 20, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: ensureInheritanceForDiscriminatorMappings() is invoked on the pre-normalization schema instance, so any normalization path that returns a new Schema object makes the discriminator mapping changes apply to a discarded object.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java, line 649:

<comment>`ensureInheritanceForDiscriminatorMappings()` is invoked on the pre-normalization schema instance, so any normalization path that returns a new Schema object makes the discriminator mapping changes apply to a discarded object.</comment>

<file context>
@@ -639,6 +644,10 @@ protected void normalizeComponentsSchemas() {
                 schemas.put(schemaName, normalizeSchema(schema, new HashSet<>()));
+
+                if (getRule(REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING)) {
+                    ensureInheritanceForDiscriminatorMappings(schema, schemaName);
+                }
             }
</file context>
Fix with Cubic

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1758">
P2: Renaming this protected helper is a breaking API change for subclasses; downstream overrides of the old method name will no longer apply.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

/**
* If not already present, add in the child an allOf referencing the parent.
*/
protected void ensureInheritanceForDiscriminatorMapping(Schema parent, Schema child, String parentName, Set<Schema> visitedSchemas) {
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot Apr 20, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Renaming this protected helper is a breaking API change for subclasses; downstream overrides of the old method name will no longer apply.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java, line 1758:

<comment>Renaming this protected helper is a breaking API change for subclasses; downstream overrides of the old method name will no longer apply.</comment>

<file context>
@@ -1755,7 +1755,7 @@ protected void ensureInheritanceForDiscriminatorMappings(Schema parent, String p
      * If not already present, add in the child an allOf referencing the parent.
      */
-    protected void ensureInheritanceForDiscriminatorMappings(Schema parent, Schema child, String parentName, Set<Schema> visitedSchemas) {
+    protected void ensureInheritanceForDiscriminatorMapping(Schema parent, Schema child, String parentName, Set<Schema> visitedSchemas) {
         String reference = "#/components/schemas/" + parentName;
         List<Schema> allOf = child.getAllOf();
</file context>
Fix with Cubic

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][DefaultCodegen] OneOf with discriminator for referenced object with allOf

2 participants