fix(kotlin): support non-discriminator oneOf/anyOf model and array types with kotlinx_serialization#23007
Conversation
…n kotlinx_serialization
There was a problem hiding this comment.
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-aiwith guidance or docs links (includingllms.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.
samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/PetApi.md
Outdated
Show resolved
Hide resolved
...tlin-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/OAuth.kt
Outdated
Show resolved
Hide resolved
| if (jsonElement is JsonArray) { | ||
| try { | ||
| val instance = jsonDecoder.json.decodeFromJsonElement<{{{dataType}}}>(jsonElement) | ||
| return {{classname}}.{{#fnToValueClassName}}{{{dataType}}}{{/fnToValueClassName}}(instance) |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
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.
...in-oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/apis/FakeApi.kt
Outdated
Show resolved
Hide resolved
...oneOf-anyOf-kotlinx-serialization/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt
Outdated
Show resolved
Hide resolved
modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache
Show resolved
Hide resolved
samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/UserApi.md
Outdated
Show resolved
Hide resolved
samples/client/others/kotlin-oneOf-anyOf-kotlinx-serialization/docs/FakeApi.md
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
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.
...tlinx-serialization/src/main/kotlin/org/openapitools/client/models/UserOrPetOrArrayString.kt
Show resolved
Hide resolved
| import {{roomModelPackage}}.{{classname}}RoomModel | ||
| import {{packageName}}.infrastructure.ITransformForStorage | ||
| {{/generateRoomModels}} | ||
| {{^kotlinx_serialization}} |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
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.
modules/openapi-generator/src/main/resources/kotlin-client/anyof_class.mustache
Show resolved
Hide resolved
There was a problem hiding this comment.
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.
… 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.
|
Thank you very much! |
Description
This PR builds on the same problem that #22986 addresses, but takes a different approach. While #22986 uses a
data classwithactualInstance: Any?, this PR uses a type-safesealed interfacewith@JvmInline value classvariants, which enables compile-time exhaustiveness checks viawhenand avoids unsafe casts. It also extends coverage toanyOfschemas and array types.Both PRs modify
oneof_class.mustacheandKotlinClientCodegenModelTest.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.Before (empty class - no serialization support)
#22986 -
data classwithactualInstance: Any?After (this PR - type-safe
sealed interface)Changes:
oneof_class.mustacheandanyof_class.mustachethat generates a sealed interface with@JvmInline value classvariants and a customKSerializerToValueClassNamecustom lambda inKotlinClientCodegen.javato generate value class names fromdataType, handling generic types (e.g.List<String>→ListStringValue){{#isArray}}branches for proper array serialization/deserializationPR checklist
mastercc @karismann @Zomzog @andrewemery @4brunu @yutaka0m @stefankoppier @e5l @dennisameling @wing328