Skip to content

fix(java): don't emit unqualified enum default for discriminator ref-to-property - #24934

Merged
wing328 merged 4 commits into
OpenAPITools:masterfrom
seonwooj0810:fix/issue-24874-discriminator-property-ref-enum-default
Nov 3, 2026
Merged

wing328 merged 4 commits into
OpenAPITools:masterfrom
seonwooj0810:fix/issue-24874-discriminator-property-ref-enum-default

Conversation

@seonwooj0810

@seonwooj0810 seonwooj0810 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #24874.

The Java okhttp-gson generator emits uncompilable this.category = String.ARCHIVE; when a discriminator references another schema's inline enum property. That use site has no enum class to qualify the mapping value with.

updateCodegenPropertyEnum now checks the original property $ref. For a reference into another schema's property that is not itself an inline enum, it drops the synthesized discriminator default and preserves the literal for ordinary properties. Inline and named enum defaults retain their existing handling, including PHP's namespace-qualified enum types. This avoids treating mapped scalar types such as Date, UUID and BigDecimal as enum classes.

The constructor template and #19614's named-enum discriminator behavior remain unchanged.

Validation (JDK 21):

  • Generated-code regression for [BUG][java] Discriminator default for direct property enum $ref generates String.<value> #24874, plus an ordinary inline enum default in the same fixture.
  • Focused CodegenProperty regressions for String/Date/UUID/BigDecimal; reverting the follow-up reproduces four failures for the mapped scalar and ordinary String cases.
  • Existing [csharp][java] Fix enum discriminator default value #19614 discriminator and PHP Symfony named-enum regression tests.
  • 684 tests, 0 failures/errors, 3 skips across JavaClientCodegenTest, JavaModelEnumTest, DefaultCodegenTest, PhpSymfonyServerCodegenTest, GoClientCodegenTest, DartClientCodegenTest, KotlinClientCodegenModelTest, KotlinClientCodegenApiTest, PythonClientCodegenTest, ConfluenceWikiTest and OpenApiEvaluatorTest.

…to-property

A discriminator property that is a `$ref` to another schema's inline
enum property (rather than a ref to a named enum schema, or an inline
enum itself) still has its allowableValues/default resolved by
updateCodegenPropertyEnum, but there is no enum type at this property's
own use site to qualify the value with. toEnumDefaultValue was called
regardless, falling back to the raw (non-enum) datatype, producing
uninitializable code such as `this.category = String.ARCHIVE;` in the
okhttp-gson library's generated subtype constructor.

Only call toEnumDefaultValue when the property is actually an inline
enum (var.isEnum) or resolves to a named enum schema (referencedSchema);
otherwise drop the default rather than emit an unqualified token.

Verified the full java-* sample set (bin/configs/java-*.yaml, 136
generators) regenerates with zero model/pojo diffs, so no existing
sample exercises this edge case.

Fixes OpenAPITools#24874

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 issue found across 3 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/DefaultCodegen.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java:7168">
P3: The else branch sets `var.defaultValue = null` for every non-enum, non-ref property with an enum constraint and matching default, not just the discriminator case it targets (#24874). For a non-discriminator String property that `$ref`s another schema's inline enum with a default, the field's default is silently dropped instead of emitting the still-valid raw literal (e.g. `this.category = "ARCHIVE";`), leaving the field uninitialized. Consider restoring the raw literal for `var.isString` when the intention is solely to avoid the bare `String.X` token.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

// allowableValues/enum matching still ran, but there's no enum constant to
// qualify the value with. Drop the default rather than emit a bare,
// unqualified token that would not compile (see #24874).
var.defaultValue = null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: The else branch sets var.defaultValue = null for every non-enum, non-ref property with an enum constraint and matching default, not just the discriminator case it targets (#24874). For a non-discriminator String property that $refs another schema's inline enum with a default, the field's default is silently dropped instead of emitting the still-valid raw literal (e.g. this.category = "ARCHIVE";), leaving the field uninitialized. Consider restoring the raw literal for var.isString when the intention is solely to avoid the bare String.X token.

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/DefaultCodegen.java, line 7168:

<comment>The else branch sets `var.defaultValue = null` for every non-enum, non-ref property with an enum constraint and matching default, not just the discriminator case it targets (#24874). For a non-discriminator String property that `$ref`s another schema's inline enum with a default, the field's default is silently dropped instead of emitting the still-valid raw literal (e.g. `this.category = "ARCHIVE";`), leaving the field uninitialized. Consider restoring the raw literal for `var.isString` when the intention is solely to avoid the bare `String.X` token.</comment>

<file context>
@@ -7155,7 +7155,18 @@ public void updateCodegenPropertyEnum(CodegenProperty var) {
+                    // allowableValues/enum matching still ran, but there's no enum constant to
+                    // qualify the value with. Drop the default rather than emit a bare,
+                    // unqualified token that would not compile (see #24874).
+                    var.defaultValue = null;
+                }
             }
</file context>

@wing328

wing328 commented Sep 15, 2026

Copy link
Copy Markdown
Member

thanks for the pr

please review the build failure when you've time

[ERROR] Failures:
[ERROR] org.openapitools.codegen.php.PhpSymfonyServerCodegenTest.testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen
[ERROR]   Run 1: PhpSymfonyServerCodegenTest.testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen:430 Enum ref + OpenAPI default should set CodegenProperty.defaultValue (see AbstractPhpCodegen.toDefaultValue ref+default handling and updateCodegenPropertyEnum) expected object to not be null
[ERROR]   Run 2: PhpSymfonyServerCodegenTest.testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen:430 Enum ref + OpenAPI default should set CodegenProperty.defaultValue (see AbstractPhpCodegen.toDefaultValue ref+default handling and updateCodegenPropertyEnum) expected object to not be null
[ERROR]   Run 3: PhpSymfonyServerCodegenTest.testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen:430 Enum ref + OpenAPI default should set CodegenProperty.defaultValue (see AbstractPhpCodegen.toDefaultValue ref+default handling and updateCodegenPropertyEnum) expected object to not be null

cc @OpenAPITools/generator-core-team

…Schema presence

referencedSchema's name match against the raw dataType string is brittle
for codegens whose dataType is namespace/package-qualified (e.g. PHP's
OpenAPI\Server\Model\Foo), which never matched toModelName(...) and
incorrectly dropped valid enum defaults for genuine named-enum refs
(PhpSymfonyServerCodegenTest#testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen
was failing CI). Switch the else-branch guard to check
languageSpecificPrimitives instead, which is a more direct test for
"is there no enum class at this use site to qualify the value with".

Addresses CI failure reported at
OpenAPITools#24934 (comment)
@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Thanks for the heads up — the PHP Symfony test failure was caused by the referencedSchema.isPresent() check in the else-branch guard: for PHP, the resolved model name is namespace-qualified (e.g. OpenAPI\\Server\\Model\\Foo), so it never matched toModelName(...) and the guard incorrectly fell into the "drop the default" branch for a genuine named-enum ref.

Pushed 2f8a35f, which swaps that check for !languageSpecificPrimitives.contains(varDataType) instead — a more direct test for "is there no enum class at this use site to qualify the value with", independent of per-language model-name formatting. Verified locally (JDK21):

  • PhpSymfonyServerCodegenTest#testModelPropertyEnumRefWithDefaultUsesNativeEnumCaseInCodegen — now passes
  • JavaClientCodegenTest#testDiscriminatorPropertyRefToEnumDoesNotEmitInvalidDefault_issue24874 (the original [BUG][java] Discriminator default for direct property enum $ref generates String.<value> #24874 regression test) — still passes
  • JavaModelEnumTest, DefaultCodegenTest, GoClientCodegenTest, DartClientCodegenTest, KotlinClientCodegenModelTest, KotlinClientCodegenApiTest, PythonClientCodegenTest, ConfluenceWikiTest, OpenApiEvaluatorTest — all green, no regressions

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

Copy link
Copy Markdown
Contributor

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/DefaultCodegen.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java:7158">
P2: When a referenced inline enum resolves to a mapped scalar such as Java `Date`, `UUID`, or `BigDecimal`, this condition treats it as a named enum and emits invalid defaults like `Date.CASE`. Determine named-enum status from the resolved schema/reference rather than primitive-set membership.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

}
if (enumName != null) {
var.defaultValue = toEnumDefaultValue(var, enumName);
if (var.isEnum || !languageSpecificPrimitives.contains(varDataType)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: When a referenced inline enum resolves to a mapped scalar such as Java Date, UUID, or BigDecimal, this condition treats it as a named enum and emits invalid defaults like Date.CASE. Determine named-enum status from the resolved schema/reference rather than primitive-set membership.

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/DefaultCodegen.java, line 7158:

<comment>When a referenced inline enum resolves to a mapped scalar such as Java `Date`, `UUID`, or `BigDecimal`, this condition treats it as a named enum and emits invalid defaults like `Date.CASE`. Determine named-enum status from the resolved schema/reference rather than primitive-set membership.</comment>

<file context>
@@ -7155,16 +7155,23 @@ public void updateCodegenPropertyEnum(CodegenProperty var) {
             }
             if (enumName != null) {
-                if (var.isEnum || referencedSchema.isPresent()) {
+                if (var.isEnum || !languageSpecificPrimitives.contains(varDataType)) {
                     var.defaultValue = toEnumDefaultValue(var, enumName);
                 } else {
</file context>

}

@Test
public void testDiscriminatorPropertyRefToEnumDoesNotEmitInvalidDefault_issue24874() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Make it easier to write/review:

        Map<String, File> files = generateFromContract("src/test/resources/bugs/issue_24874.yaml", OKHTTP_GSON,
                Map.of(MODEL_NAME_PREFIX, "Stock"));
        JavaFileAssert.assertThat(files.get("StockArchiveCategoryEvent.java"))
                .fileDoesNotContain("String.ARCHIVE");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, will switch this to generateFromContract + JavaFileAssert matching the other bugs/tests in this file, and push it in the next commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 77718a3 — refactored to use generateFromContract + JavaFileAssert, matching the other bugs/tests in this file. Verified locally (JDK21, -pl modules/openapi-generator -am test) — passes.

@jpfinne jpfinne left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

updating DefaultCodegen is risky.

Just change the template

}
}
if (enumName != null) {
var.defaultValue = toEnumDefaultValue(var, enumName);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Just update the invalid pojo.mustache.

Remove the line in

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I checked the git history on this line — it was added in #19614 (merged) specifically to fix enum-typed discriminators, and that PR closed five separate issues (#12412, #16073, #16672, #19194, #19261). Removing it unconditionally would regress that: any model where the discriminator property is genuinely typed as an enum would stop getting its default assigned in the subclass constructor.

#24874 is a narrower case — the discriminator is a $ref into another schema's property, not a genuinely-enum-typed discriminator — so I'd rather keep the DefaultCodegen-level guard and tighten it instead of removing the template line.

That said, your earlier concern was valid and exposed a real gap: the current languageSpecificPrimitives check doesn't cover mapped scalars like Date/UUID/BigDecimal, so a $ref into a property of one of those types would still emit an invalid qualified default (e.g. Date.CASE). I'll fix the check to key off whether the resolved schema is an actual named enum rather than primitive-set membership, which should also address cubic's P2 comment above.

Addresses review feedback from jpfinne: use the existing generateFromContract
test helper instead of manually building CodegenConfigurator/DefaultGenerator
boilerplate, and specify the okhttp-gson library explicitly.
@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Pushed 77718a3 for the test-style feedback (generateFromContract + JavaFileAssert, matching the rest of the file).

Re: "just update pojo.mustache" / "updating DefaultCodegen is risky" — I actually tried that route (drop the this.{{name}} = {{defaultValue}}; line in okhttp-gson's pojo.mustache and let DefaultCodegen unconditionally compute the enum-qualified default) to see if it was lower-risk than tightening the DefaultCodegen guard. It isn't safe as a standalone change: that constructor line is what #19614 added so each discriminator subtype gets its own enum value initialized (e.g. this.carType = CarType.SUV;), and removing it unconditionally breaks testEnumDiscriminatorDefaultValueIsNotString — all 9 subtypes in that test stop getting their discriminator default assigned. So a template-only fix isn't actually simpler/safer here; happy to look at a version that keeps #19614 green, but the straightforward one doesn't.

Still outstanding from my earlier reply: tightening the DefaultCodegen check to key off the resolved schema being an actual named enum (rather than languageSpecificPrimitives membership), which should also close the mapped-scalar gap (Date/UUID/BigDecimal) cubic flagged. That's not in this push — I want to verify it against the #19614 fixture set (Cat/Dog/Gecko/Chameleon/MiniVan/CargoVan/SUV/Truck/Sedan) before landing it, will follow up separately rather than guess.

@jpfinne

jpfinne commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

@seonwooj0810 you don't need to assign a value to the discriminator. The annotation @JsonSubTypes is enough for correct serialization by Jackson. All the other java libraries don't assign a value to the discriminator.

I think a good fix would be to add an import like import org.openapi.model.CategorySource.CategoryEnum for inline enums.
That would solve several generation issues. For example
src/test/resources/3_0/oneOfDiscriminator.yaml used in SpringCodegenTest.testOneOfWithInheritedEnumDiscriminator()
-> PetResponseEnumDisc.java misses an import on PetEnumDisc.PetTypeEnum
-> public PetTypeEnum getPetType() does not compile

Then the defaultValue could be set even for inline enums. The current template would generate this.category = CategoryEnum.ARCHIVE;

That fix is complex! It requires changes in DiscriminatorCodegen, DiscriminationUtils, DiscriminatorData...

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Thanks for the context. To be precise about what this PR actually does today: it only drops the default for the ref-to-property/primitive case that #24874 is about (e.g. a String discriminator that $refs another schema's inline enum) — that's the var.defaultValue = null branch. For genuine named-enum discriminators (the #19614 fixture set — Cat/Dog/Gecko/Chameleon/SUV/Truck/Sedan/etc.) this PR still assigns the default, e.g. this.carType = CarType.SUV;, same as before.

If I'm reading your comment right, you're saying that assignment is unnecessary everywhere, not just in the broken ref-to-property case — since @JsonSubTypes handles serialization on its own and other java libraries don't assign it either. That's a bigger behavior change than what #24874 asked for: it would mean removing the this.{{name}} = {{defaultValue}}; line from pojo.mustache unconditionally and updating testEnumDiscriminatorDefaultValueIsNotString (which currently asserts all 9 subtypes get that assignment) to match. That's the exact template-only route I held off on earlier, precisely because it changes #19614's behavior rather than just fixing the broken case.

Do you want me to go ahead and make that broader change (drop the assignment unconditionally + update the #19614 test), or keep this PR scoped to just the ref-to-property fix and treat "stop assigning discriminator defaults everywhere" as separate follow-up? Happy to do either, just want to confirm scope before changing #19614's established behavior.

Re: the import-based fix for inline enums (CategorySource.CategoryEnum etc.) — agreed that's a different, larger piece of work (DiscriminatorCodegen/DiscriminationUtils/DiscriminatorData) than this PR's scope. I'd rather not guess at that here; happy to see it filed as a separate issue if you'd like to track it.

@seonwooj0810

Copy link
Copy Markdown
Contributor Author

Pushed 2d17372 to address the two remaining default-value findings. The guard now checks the original property $ref, rather than primitive-type membership or a generated class-name match. Property refs with scalar types no longer get enum-qualified defaults; ordinary String defaults retain their quoted literal. Named enum defaults, including PHP's qualified enum types, keep the existing path.

Added focused CodegenProperty tests: reverting the fix reproduces the Date/UUID/BigDecimal invalid constants and String-default loss. These are unit-level cases; the generation fixture separately checks #24874 and preserves an ordinary inline enum default. The existing #19614 discriminator and PHP regression tests pass.

Validation on JDK 21: 684 tests, 0 failures/errors, 3 skips, across the Java, PHP, DefaultCodegen, Go, Dart, Kotlin, Python, Confluence and OpenAPI evaluator suites.

I kept this follow-up scoped to the default computation. It does not remove constructor assignments or change inline-enum imports.

@wing328

wing328 commented Nov 3, 2026

Copy link
Copy Markdown
Member

tested locally to confirm the fix. thanks for the PR

@wing328
wing328 merged commit b419790 into OpenAPITools:master Nov 3, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][java] Discriminator default for direct property enum $ref generates String.<value>

3 participants