Skip to content

[csharp][generichost] Write the selected member of an anyOf with a discriminator - #25260

Open
Arthur031221 wants to merge 1 commit into
OpenAPITools:masterfrom
Arthur031221:fix-csharp-generichost-anyof-discriminator-write
Open

Arthur031221 wants to merge 1 commit into
OpenAPITools:masterfrom
Arthur031221:fix-csharp-generichost-anyof-discriminator-write

Conversation

@Arthur031221

@Arthur031221 Arthur031221 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

With the C# generichost library, a model with anyOf and a discriminator is read into the right member but written as {}, so request bodies built from it go out empty. In JsonConverter.mustache the anyOf writer was skipped for every model with a discriminator, and the discriminator branch of Write only handled oneOf.

I removed the ^model.discriminator guard around the anyOf writer. Read fills only the member the discriminator picks, so Write now emits that member's properties, same as oneOf.

Tested with the schema from the issue in a .NET 9 container, both subtypes serialize back to the original JSON. Added testAnyOfDiscriminatorWritesSelectedSubtype to CSharpClientCodegenTest. Regenerating the generichost sample configs changes no files.

Fixes #25154

cc @devhl-labs @mandrean @shibayan @Blackclaws @lucamazzanti

Assisted by Claude/Codex.


Summary by cubic

Adds a regression test for C# generichost serialization of anyOf models with a discriminator.

The JsonConverter.mustache template on master already writes the selected member of such models, so this PR only keeps the test that pins down the behavior.

Written for commit 804ba66. Summary will update on new commits.

View guided diff

@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.

No issues found across 2 files

View guided diff | Re-trigger cubic

@wing328

wing328 commented Oct 15, 2026

Copy link
Copy Markdown
Member

Thanks for the PR

cc @devhl-labs

SpenserJ added a commit to SpenserJ/openapi-generator that referenced this pull request Oct 30, 2026
…cted member

Brings over the codegen test from OpenAPITools#25260.

Co-authored-by: Arthur031221 <levi74108520963@gmail.com>
@Arthur031221

Copy link
Copy Markdown
Contributor Author

Is there anything else you need from me to move this forward?

@devhl-labs

Copy link
Copy Markdown
Contributor

There are two other competing PRs. Id like to merge this one first and see if the problem this fixes is addressed. I really appreciate all the help trying to improve composed schemas.
#25486

wing328 pushed a commit that referenced this pull request Nov 9, 2026
…ects (#25486)

* [csharp][generichost] Serialize union members that are not merged objects

The composed-schema converter assumed every oneOf/anyOf value is a JSON
object whose members' properties get merged. Scalar, enum and array
members could not be read or written, and object members of a oneOf
without a discriminator or an anyOf with one were never written.

- Read string, number, boolean, enum and array tokens into the members
  that can hold them instead of throwing.
- Write enum, primitive and container members as the value itself.
- Merge object members for every oneOf and anyOf shape, keeping the
  union's own properties.
- Keep rejecting scalars that no anyOf member accepts.

Fixes #23261, #23529, #23693, #25154

* Update csharp generichost samples

* [csharp][generichost] Test that a discriminated anyOf writes its selected member

Brings over the codegen test from #25260.

Co-authored-by: Arthur031221 <levi74108520963@gmail.com>

* [csharp][generichost] Read union members only from matching JSON tokens

Skip a duplicated last member without skipping the object loop, restore
the fast-fail for discriminated unions, keep arrays and scalars out of
free-form object members, and throw when no anyOf member matches.

* [csharp][generichost] Read object union members once from the object token

Replace the per-property probe loop with one read per object member, so
an empty object reads and value members are no longer tried against
objects. Emit isScalarToken only for unions without a discriminator.

* [csharp][generichost] Delegate union members that are unions to their converter

Mark oneOf/anyOf members whose type is itself a union with x-is-union, so
they are read on any token and written by their own converter instead of
being merged as objects. Throw when no anyOf member matches, including
for objects.

* Move union member serialization tests to a manual test project

The workflow regenerates every non-Manual generichost sample from
scratch, which deletes hand-written tests.

* Update csharp generichost samples

---------

Co-authored-by: Arthur031221 <levi74108520963@gmail.com>
@wing328

wing328 commented Nov 17, 2026

Copy link
Copy Markdown
Member

please resolve the merge conflicts when you've time and i'll try to get it merged before the upcoming release which is due later this week

@wing328 wing328 added this to the 7.28.0 milestone Nov 17, 2026

@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.

5 issues found across 2 files (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. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache:125">
P1: This generated call does not compile because generichost `ClientUtils` has no `GetDiscriminatorValue` implementation. Add that helper to `ClientUtils.mustache` or replace this call with an existing helper that accepts the reader’s current token.</violation>

<violation number="2" location="modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache:151">
P0: These partial references have no template files, so compiling `JsonConverter.mustache` fails with `TemplateNotFoundException` before any generichost model is generated. Add the referenced partial templates or keep the union implementations inline.</violation>
</file>

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

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java:787">
P1: This test references a fixture that is not included in the PR, so it fails before generation with a missing-resource error. Add `src/test/resources/3_1/csharp/union-members.yaml` or remove the test until the fixture is available.</violation>

<violation number="2" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java:1231">
P1: Both model-collision tests reference a fixture missing from the PR, so the suite fails while loading the OpenAPI document. Add `src/test/resources/3_0/csharp/model-name-collisions.yaml` or remove these tests until the fixture is included.</violation>

<violation number="3" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java:1304">
P1: This webhook regression test references a fixture that is not included, so it fails during setup rather than testing constructor generation. Add `src/test/resources/3_1/csharp/webhook-only-model.yaml` or remove the test until the fixture is available.</violation>
</file>

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

View guided diff | Re-trigger cubic


{{#oneOf}}
{{^vendorExtensions.x-duplicated-data-type}}
{{>ReadUnionMember}}

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.

P0: These partial references have no template files, so compiling JsonConverter.mustache fails with TemplateNotFoundException before any generichost model is generated. Add the referenced partial templates or keep the union implementations inline.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache, line 151:

<comment>These partial references have no template files, so compiling `JsonConverter.mustache` fails with `TemplateNotFoundException` before any generichost model is generated. Add the referenced partial templates or keep the union implementations inline.</comment>

<file context>
@@ -117,62 +143,37 @@
-
+            {{#oneOf}}
+            {{^vendorExtensions.x-duplicated-data-type}}
+{{>ReadUnionMember}}
+            {{/vendorExtensions.x-duplicated-data-type}}
+            {{/oneOf}}
</file context>

if (localVarJsonPropertyName{{nrt?}}.Equals("{{propertyBaseName}}"){{#nrt}} ?? false{{/nrt}})
{
string{{nrt?}} discriminator = utf8JsonReaderDiscriminator.GetString();
string{{nrt?}} discriminator = ClientUtils.GetDiscriminatorValue(utf8JsonReaderDiscriminator, "{{propertyBaseName}}");

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.

P1: This generated call does not compile because generichost ClientUtils has no GetDiscriminatorValue implementation. Add that helper to ClientUtils.mustache or replace this call with an existing helper that accepts the reader’s current token.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache, line 125:

<comment>This generated call does not compile because generichost `ClientUtils` has no `GetDiscriminatorValue` implementation. Add that helper to `ClientUtils.mustache` or replace this call with an existing helper that accepts the reader’s current token.</comment>

<file context>
@@ -96,7 +122,7 @@
                     if (localVarJsonPropertyName{{nrt?}}.Equals("{{propertyBaseName}}"){{#nrt}} ?? false{{/nrt}})
                     {
-                        string{{nrt?}} discriminator = utf8JsonReaderDiscriminator.GetString();
+                        string{{nrt?}} discriminator = ClientUtils.GetDiscriminatorValue(utf8JsonReaderDiscriminator, "{{propertyBaseName}}");
                         {{#mappedModels}}
                         if (discriminator{{nrt?}}.Equals("{{mappingName}}"){{#nrt}} ?? false{{/nrt}})
</file context>

File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
final OpenAPI openAPI = TestUtils.parseFlattenSpec(
"src/test/resources/3_1/csharp/webhook-only-model.yaml");

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.

P1: This webhook regression test references a fixture that is not included, so it fails during setup rather than testing constructor generation. Add src/test/resources/3_1/csharp/webhook-only-model.yaml or remove the test until the fixture is available.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java, line 1304:

<comment>This webhook regression test references a fixture that is not included, so it fails during setup rather than testing constructor generation. Add `src/test/resources/3_1/csharp/webhook-only-model.yaml` or remove the test until the fixture is available.</comment>

<file context>
@@ -980,4 +1292,38 @@ private File getGeneratedModel(Map<String, File> files, File output, String mode
+        File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
+        output.deleteOnExit();
+        final OpenAPI openAPI = TestUtils.parseFlattenSpec(
+            "src/test/resources/3_1/csharp/webhook-only-model.yaml");
+        // the fixture omits `paths` entirely (a webhooks-only 3.1 document),
+        // so this test also covers the getPaths() == null branch
</file context>

private Map<String, File> generateModelNameCollisions() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/csharp/model-name-collisions.yaml");

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.

P1: Both model-collision tests reference a fixture missing from the PR, so the suite fails while loading the OpenAPI document. Add src/test/resources/3_0/csharp/model-name-collisions.yaml or remove these tests until the fixture is included.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java, line 1231:

<comment>Both model-collision tests reference a fixture missing from the PR, so the suite fails while loading the OpenAPI document. Add `src/test/resources/3_0/csharp/model-name-collisions.yaml` or remove these tests until the fixture is included.</comment>

<file context>
@@ -930,6 +1203,45 @@ public void testValueTypeConstructorUnchangedWithoutConditionalSerialization() t
+    private Map<String, File> generateModelNameCollisions() throws IOException {
+        File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
+        output.deleteOnExit();
+        final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/csharp/model-name-collisions.yaml");
+        final DefaultGenerator defaultGenerator = new DefaultGenerator();
+        final ClientOptInput clientOptInput = new ClientOptInput();
</file context>

public void testUnionMemberThatIsAUnionUsesItsOwnConverter() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_1/csharp/union-members.yaml");

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.

P1: This test references a fixture that is not included in the PR, so it fails before generation with a missing-resource error. Add src/test/resources/3_1/csharp/union-members.yaml or remove the test until the fixture is available.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpClientCodegenTest.java, line 787:

<comment>This test references a fixture that is not included in the PR, so it fails before generation with a missing-resource error. Add `src/test/resources/3_1/csharp/union-members.yaml` or remove the test until the fixture is available.</comment>

<file context>
@@ -529,6 +696,112 @@ public void testAnyOfDiscriminatorCreatesCompilableCode() throws IOException {
+    public void testUnionMemberThatIsAUnionUsesItsOwnConverter() throws IOException {
+        File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
+        output.deleteOnExit();
+        final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_1/csharp/union-members.yaml");
+        final DefaultGenerator defaultGenerator = new DefaultGenerator();
+        final ClientOptInput clientOptInput = new ClientOptInput();
</file context>

…a discriminator is written

The JsonConverter template on master already writes the anyOf members of a
model that has a discriminator. This keeps the regression test for it.

Signed-off-by: Arthur031221 <levi74108520963@gmail.com>
@Arthur031221
Arthur031221 force-pushed the fix-csharp-generichost-anyof-discriminator-write branch from 79c9f56 to 804ba66 Compare November 18, 2026 14:37
@Arthur031221

Copy link
Copy Markdown
Contributor Author

Resolved the conflict. The anyOf block in JsonConverter.mustache on master is no longer inside the discriminator guard, so I dropped my template change and took the file from master as is. The PR is now just the regression test, and I updated the commit message to say so. If you'd rather not carry a test-only change, tell me and I'll close it.

@Arthur031221

Copy link
Copy Markdown
Contributor Author

#25486 already fixed #25154, and master now has testAnyOfDiscriminatorWritesSelectedSubtype with the same body as the one here. This branch only adds a second copy of that method, so CSharpClientCodegenTest no longer compiles. Closing this since the fix is already in.

This branch has not been deployed

No deployments
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][csharp][generichost] anyOf with discriminator serializes to {}

3 participants