openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG] [Rust] Conflicting type fields for discriminator unions, causing deserialization failures.

Open InfinityByTen opened this issue 3 months ago • 1 comments

Bug Report Checklist

  • [yes ] Have you provided a full/minimal spec to reproduce the issue?
  • [ yes] Have you validated the input using an OpenAPI validator?
  • [ checked on 7.15.0] Have you tested with the latest master to confirm the issue still exists?
  • [ yes] Have you searched for related issues/PRs?
Description

Generates conflicting Rust code for discriminated unions, causing deserialization failures.

openapi-generator version

v7.15.0

OpenAPI declaration file content or url

Minimal API spec: https://gist.github.com/InfinityByTen/29d554b9dcde1fe08ff6a399cb05b205

Generation Details

Generated using:

java -jar openapi-generator-cli.jar generate \
  -g rust \
  --library reqwest \
  -i openapi.yaml \
  -o generated \
  --additional-properties=supportAsync=true,packageName=discriminator_demo
Steps to reproduce

Create src/main.rs with the following code:

#[path = "../generated/src/models/mod.rs"]
mod models;

use models::Shape;

fn main() {
    let circle_json = r#"{"type": "circle", "radius": 5.0}"#;
    let rectangle_json = r#"{"type": "rectangle", "width": 10.0, "height": 20.0}"#;

    println!("Testing Circle: {}", circle_json);
    match serde_json::from_str::<Shape>(circle_json) {
        Ok(_) => println!("SUCCESS"),
        Err(e) => println!("ERROR: {}", e),
    }

    println!("Testing Rectangle: {}", rectangle_json);
    match serde_json::from_str::<Shape>(rectangle_json) {
        Ok(_) => println!("SUCCESS"),
        Err(e) => println!("ERROR: {}", e),
    }
}

And invoke with cago run to see that the serialization fails with the error "ERROR: missing field type", while the type is clearly in the input json string.

Suggested Fix

Generated code should not create discriminator fields in structs when using #[serde(tag = "discriminator")] on the enum.

Current (incorrect):

pub struct Circle {
    #[serde(rename = "type")]
    pub r#type: Type,  // ← This conflicts with enum tag!
    pub radius: f64,
}

Should be:

pub struct Circle {
    // No type field - enum handles discriminator automatically
    pub radius: f64,
}
Side Note

The generated code creates unused imports and code that fails linting done by standard clippy tool. It should ideally have annotations to disable warnings considering that not all of the generated code may be used at all times.

InfinityByTen avatar Sep 24 '25 08:09 InfinityByTen

@InfinityByTen Did you find a solution or a workaround to this bug? I opened a similar issue here: https://github.com/OpenAPITools/openapi-generator/issues/22344.

ThomasVille avatar Nov 28 '25 08:11 ThomasVille