Skip to content

fix(kotlin): support non-discriminator oneOf/anyOf model and array types with kotlinx_serialization#23007

Open
naokiwakata wants to merge 7 commits intoOpenAPITools:masterfrom
naokiwakata:wakata/fix/kotlin-client-generateOneOfAnyOfWrappers
Open

fix(kotlin): support non-discriminator oneOf/anyOf model and array types with kotlinx_serialization#23007
naokiwakata wants to merge 7 commits intoOpenAPITools:masterfrom
naokiwakata:wakata/fix/kotlin-client-generateOneOfAnyOfWrappers

Conversation

@naokiwakata
Copy link

@naokiwakata naokiwakata commented Feb 19, 2026

Description

This PR builds on the same problem that #22986 addresses, but takes a different approach. While #22986 uses a data class with actualInstance: Any?, this PR uses a type-safe sealed interface with @JvmInline value class variants, which enables compile-time exhaustiveness checks via when and avoids unsafe casts. It also extends coverage to anyOf schemas and array types.

Both PRs modify oneof_class.mustache and KotlinClientCodegenModelTest.java, so they will conflict if both are merged. This PR is intended as an alternative to #22986 — if this one is accepted, #22986 can be closed.

company_id:
  oneOf:
    - type: string
    - type: integer
      format: int64

Before (empty class - no serialization support)

@Serializable
class TestModelCompanyId () {
}

#22986 - data class with actualInstance: Any?

@Serializable(with = TestModelCompanyId.TestModelCompanyIdSerializer::class)
data class TestModelCompanyId(var actualInstance: Any? = null) {
    object TestModelCompanyIdSerializer : KSerializer<TestModelCompanyId> {
        override fun serialize(encoder: Encoder, value: TestModelCompanyId) {
            when (val instance = value.actualInstance) {
                is kotlin.String -> jsonEncoder.encodeString(instance)
                is kotlin.Long -> jsonEncoder.encodeLong(instance)
                // ...
            }
        }
    }
}

After (this PR - type-safe sealed interface)

@Serializable(with = TestModelCompanyIdSerializer::class)
sealed interface TestModelCompanyId {
    @JvmInline
    value class StringValue(val value: kotlin.String) : TestModelCompanyId
    @JvmInline
    value class LongValue(val value: kotlin.Long) : TestModelCompanyId
}

object TestModelCompanyIdSerializer : KSerializer<TestModelCompanyId> {
    override fun serialize(encoder: Encoder, value: TestModelCompanyId) {
        when (value) {
            is TestModelCompanyId.StringValue -> jsonEncoder.encodeString(value.value)
            is TestModelCompanyId.LongValue -> jsonEncoder.encodeLong(value.value)
        }
    }
}

Changes:

  • Add non-discriminator path in oneof_class.mustache and anyof_class.mustache that generates a sealed interface with @JvmInline value class variants and a custom KSerializer
  • Add ToValueClassName custom lambda in KotlinClientCodegen.java to generate value class names from dataType, handling generic types (e.g. List<String>ListStringValue)
  • Add {{#isArray}} branches for proper array serialization/deserialization
  • Add unit tests and new sample with CI config for validation

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.
  • 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
    
    Commit all changed files.
  • File the PR against the correct branch: master
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

cc @karismann @Zomzog @andrewemery @4brunu @yutaka0m @stefankoppier @e5l @dennisameling @wing328

@naokiwakata naokiwakata marked this pull request as ready for review February 19, 2026 04:06
Copy link
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.

8 issues found across 84 files

Note: This PR contains a large number of files. cubic only reviews up to 75 files per PR, so some files may not have been reviewed.

Prompt for AI agents (all 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="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/PetApi.md">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/PetApi.md:75">
P2: Parameter table rows appear before the header/separator lines, which breaks Markdown table rendering and can hide parameter documentation in the generated docs.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/UserApi.md">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/UserApi.md:223">
P3: Markdown table header is placed after the first data row in the loginUser parameters section, which breaks table rendering.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/OAuth.kt">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/OAuth.kt:59">
P2: OAuthFlow.implicit is mapped to AUTHORIZATION_CODE and still triggers token endpoint requests, but implicit flow should receive the access token from the authorization endpoint (no /token call). With accessToken private and no setter, implicit flow is effectively unusable.</violation>
</file>

<file name="modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/kotlin-client/oneof_class.mustache:235">
P2: The new non-discriminator kotlinx-serialization deserializer returns on the first successful schema match without verifying that exactly one oneOf schema matches. This relaxes oneOf validation compared to the existing Gson implementation and can silently accept ambiguous JSON by selecting an arbitrary first match.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt:40">
P2: @Path("petId") has no matching `{petId}` placeholder in the @PUT URL, which causes Retrofit to throw an IllegalArgumentException at runtime or drop the parameter.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/FakeApi.md">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/FakeApi.md:69">
P3: Malformed Markdown table: parameters rows appear before the header/separator, so the table for updatePetWithFormNumber will not render correctly.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt:22">
P2: Query-based API key is appended without URL-encoding and uses a decoded query string, which can corrupt existing query parameters or throw URISyntaxException for keys with reserved characters.</violation>
</file>

<file name="modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache:108">
P2: kotlinx_serialization anyOf sealed interface/value class generation lacks the duplicate data type guard (x-duplicated-data-type). If multiple anyOf schemas resolve to the same Kotlin dataType, this emits duplicate value class names and duplicate when-branches, causing compilation errors. The Gson branch already guards duplicates, so this is a regression.</violation>
</file>

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Add one-off context when rerunning by tagging @cubic-dev-ai with guidance or docs links (including llms.txt)
  • Ask questions if you need clarification on any suggestion

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

if (jsonElement is JsonArray) {
try {
val instance = jsonDecoder.json.decodeFromJsonElement<{{{dataType}}}>(jsonElement)
return {{classname}}.{{#fnToValueClassName}}{{{dataType}}}{{/fnToValueClassName}}(instance)
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Feb 19, 2026

Choose a reason for hiding this comment

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

P2: The new non-discriminator kotlinx-serialization deserializer returns on the first successful schema match without verifying that exactly one oneOf schema matches. This relaxes oneOf validation compared to the existing Gson implementation and can silently accept ambiguous JSON by selecting an arbitrary first match.

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/resources/kotlin-client/oneof_class.mustache, line 235:

<comment>The new non-discriminator kotlinx-serialization deserializer returns on the first successful schema match without verifying that exactly one oneOf schema matches. This relaxes oneOf validation compared to the existing Gson implementation and can silently accept ambiguous JSON by selecting an arbitrary first match.</comment>

<file context>
@@ -150,6 +162,123 @@ import java.io.IOException
+        if (jsonElement is JsonArray) {
+            try {
+                val instance = jsonDecoder.json.decodeFromJsonElement<{{{dataType}}}>(jsonElement)
+                return {{classname}}.{{#fnToValueClassName}}{{{dataType}}}{{/fnToValueClassName}}(instance)
+            } catch (e: Exception) {
+                errorMessages.add("Failed to deserialize as {{{dataType}}}: ${e.message}")
</file context>
Fix with Cubic

Copy link
Author

Choose a reason for hiding this comment

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

This is the same first-match approach used in #22986 and the multiplatform template. Strict oneOf validation (ensuring exactly one match) would be a separate enhancement across all serialization paths.

@naokiwakata naokiwakata marked this pull request as draft February 19, 2026 04:27
@naokiwakata naokiwakata marked this pull request as ready for review February 19, 2026 04:35
Copy link
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.

4 issues found across 63 files

Prompt for AI agents (all 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=".github/workflows/samples-kotlin-client.yaml">

<violation number="1" location=".github/workflows/samples-kotlin-client.yaml:73">
P2: New sample added to the build matrix is not included in pull_request/push path filters, so changes limited to that sample won’t trigger this workflow.</violation>
</file>

<file name="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/models/UserOrPetOrArrayString.kt">

<violation number="1" location="samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/models/UserOrPetOrArrayString.kt:79">
P2: OneOf exclusivity isn’t enforced: the deserializer returns the first successful parse (User/Pet/List) without checking if multiple schemas match. With ignoreUnknownKeys/isLenient enabled, a JSON object can satisfy both User and Pet, so ambiguous payloads are silently classified as the first type instead of raising an error.</violation>
</file>

<file name="modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache:79">
P2: When `kotlinx_serialization` is enabled and `generateOneOfAnyOfWrappers` is false, the template emits no class definition, leaving the generated model file empty.</violation>

<violation number="2" location="modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache:109">
P2: Inner value class names are derived solely from dataType without duplicate-type guards. If multiple anyOf schemas map to the same Kotlin type, the template will emit duplicate inner class names (e.g., two `StringValue` classes), causing compilation errors.</violation>
</file>

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

import {{roomModelPackage}}.{{classname}}RoomModel
import {{packageName}}.infrastructure.ITransformForStorage
{{/generateRoomModels}}
{{^kotlinx_serialization}}
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Feb 19, 2026

Choose a reason for hiding this comment

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

P2: When kotlinx_serialization is enabled and generateOneOfAnyOfWrappers is false, the template emits no class definition, leaving the generated model file empty.

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/resources/kotlin-client/anyof_class.mustache, line 79:

<comment>When `kotlinx_serialization` is enabled and `generateOneOfAnyOfWrappers` is false, the template emits no class definition, leaving the generated model file empty.</comment>

<file context>
@@ -57,7 +76,9 @@ import java.io.Serializable
 import {{roomModelPackage}}.{{classname}}RoomModel
 import {{packageName}}.infrastructure.ITransformForStorage
 {{/generateRoomModels}}
+{{^kotlinx_serialization}}
 import java.io.IOException
+{{/kotlinx_serialization}}
</file context>
Fix with Cubic

Copy link
Author

Choose a reason for hiding this comment

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

This is a pre-existing limitation that exists before this PR — the kotlinx_serialization + generateOneOfAnyOfWrappers=false combination for anyOf was already unsupported. This PR only adds the generateOneOfAnyOfWrappers=true path, so addressing this is out of scope here.

Copy link
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 (all 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=".github/workflows/samples-kotlin-client.yaml">

<violation number="1" location=".github/workflows/samples-kotlin-client.yaml:9">
P2: `push.branches` only matches branch names, not file paths. The added sample directory pattern under `branches` will never trigger on pushes that change those files. Use `paths` under `push` if you want path-based triggering.</violation>
</file>

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

wakata_sansan added 3 commits February 19, 2026 14:40
… templates

The Gson path already uses {{^vendorExtensions.x-duplicated-data-type}} to skip
duplicate data types, but the new kotlinx_serialization path was missing this
guard. Without it, duplicate value class names would be generated if multiple
schemas resolve to the same Kotlin dataType, causing compilation errors.
push.branches filters by branch name, not file paths. The sample directory
pattern added here had no effect. The pull_request.paths filter remains and
correctly triggers CI for this sample.
@pvcresin
Copy link

Thank you very much!

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.

2 participants

Comments