Skip to content

Issue with schema generation using T::get_schema() #435

Closed

Description

@Theodlz

Hi! I have a a top-level struct, for which a couple of its fields are structs themselves, of the same type. When using get_schema(), it looks like the result is a schema for that top-level struct, it contains multiple instances of a type definition (generated by these multiple fields of the same struct type), i.e. an invalid schema. Thereafter, the writer fails to serializes (I am using append_ser, with the newly added serde API).

In other - perhaps simpler words - I think there is some issue where the schema inferred from structs that derive AvroSchema don't do a great job at figuring out that a type is defined multiple times (in which case it should remove all but the first instance of that type definition).

Activity

  1. changed the title [-]Issue with schema generation with `T::get_schema()`[/-] [+]Issue with schema generation using `T::get_schema()`[/+] on Jan 24, 2026
  2. martin-g commented on Jan 24, 2026

    @martin-g
    Member

    Please try current main branch.

    If it still doesn't work then please provide a failing test case!

  3. Theodlz commented on Jan 24, 2026

    @Theodlz
    Author

    that's what I'm on already! Ok let me try to replace that error without the gazillion structs we have in our actual app.

  4. Theodlz commented on Jan 24, 2026

    @Theodlz
    Author

    Ok I managed to reproduce it, and also found another bug (which I think cascaded into this one). Will share once I clean up the structs to make it as simple as possible

  5. Theodlz commented on Jan 24, 2026

    @Theodlz
    Author

    Ok, so here is the original bug mentioned in this issue, reproduced:

    use apache_avro::{AvroSchema, Writer};
    use serde::{Deserialize, Serialize};
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub enum Color { G, R, I }
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub struct A {
        pub time: f64,
        pub color: Color,
    }
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub struct B {
        pub time: f64,
        pub color: Option<Color>,
    }
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub struct C {
        #[serde(flatten)]
        pub a: A,
    }
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub struct TestStruct {
        pub b: B,
        pub vec_c: Vec<C>,
    }
    
    fn main() {
        let test = TestStruct {
            b: B { time: 42.0, color: Some(Color::R) },
            vec_c: vec![],
        };
    
        let schema = TestStruct::get_schema();
    
        let mut writer = Writer::with_codec(
            &schema,
            Vec::new(),
            apache_avro::Codec::Snappy,
        )
        .unwrap();
    
        writer.append_ser(test).unwrap();
    }

    So here, the problem is that this Color type is occurring twice in the generated schema, which yields: Error { details: Two named schema defined for same fullname: Color. }.

  6. Theodlz commented on Jan 24, 2026

    @Theodlz
    Author

    HOWEVER, here is another bug that's probably related, and much easier to reproduce:

    use apache_avro::{AvroSchema, Writer};
    use serde::{Deserialize, Serialize};
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub enum Color { G, R, I }
    
    #[derive(Deserialize, Serialize, AvroSchema)]
    pub struct A {
        pub time: f64,
        pub color: Option<Color>,
    }
    
    fn main() {
        let test = A {
            time: 123.0,
            color: Some(Color::R),
        };
    
        let schema = A::get_schema();
    
        let mut writer = Writer::with_codec(
            &schema,
            Vec::new(),
            apache_avro::Codec::Snappy,
        )
        .unwrap();
    
        writer.append_ser(test).unwrap();
    }

    Here, it shows that it can't generate a proper Avro definition for an option of an enum (Option<Color> in this example), as it fails with the error:
    Error { details: Failed to serialize field 'color' for record Record(RecordSchema { name: Name { name: "A", namespace: None }, aliases: None, doc: None, fields: [RecordField { name: "time", doc: None, aliases: None, default: None, schema: Double, order: Ascending, position: 0, custom_attributes: {} }, RecordField { name: "color", doc: None, aliases: None, default: None, schema: Union(UnionSchema { schemas: [Null, Enum(EnumSchema { name: Name { name: "Color", namespace: None }, aliases: None, doc: None, symbols: ["G", "R", "I"], default: None, attributes: {} })], variant_index: {Null: 0, Enum: 1} }), order: Ascending, position: 1, custom_attributes: {} }], lookup: {"color": 1, "time": 0}, attributes: {} }): Failed to serialize value of type unit struct using schema Enum(EnumSchema { name: Name { name: "Color", namespace: None }, aliases: None, doc: None, symbols: ["G", "R", "I"], default: None, attributes: {} }): Color. Cause: Expected Null or Union schema. Got: Enum }

    So here, it clearly mixes up optional and non optional field

  7. Theodlz commented on Jan 24, 2026

    @Theodlz
    Author

    BTW this optional vs non optional issue only happens with enums. If I replace the Color enum with a struct, then that all goes away.

  8. Kriskras99 commented on Jan 25, 2026

    @Kriskras99
    Contributor

    The first issue can be reduced to this:

    #[derive(AvroSchema)]
    pub enum Color { G }
    
    #[derive(AvroSchema)]
    pub struct A {
        pub color: Color,
    }
    
    #[derive(AvroSchema)]
    pub struct C {
        #[serde(flatten)]
        pub a: A,
    }
    
    #[derive(AvroSchema)]
    pub struct TestStruct {
        pub a: Color,
        pub c: C,
    }

    The problem is that when the transparent attribute is used, that schema is called using a new named_schemas because we don't want to insert the schema for A in case it's used in another field because then it would be a ref to a schema that does not exist:

    #[derive(AvroSchema)]
    pub struct TestStruct {
        pub a: Color,
        pub c: C,
        // This would fail if `transparent` forwards the `named_schemas`
        pub b: A,
    }
    

    I think the solution would be changing to trait to this:

    pub trait AvroSchemaComponent {
        // If transparent is `true` then don't insert the schema into `named_schemas`
        fn get_schema_in_ctxt(named_schemas: &mut HashMap<Name, Schema>, enclosing_namespace: &Namespace, transparent: bool);
    }

    This would of course be a breaking change.

  9. Kriskras99 commented on Jan 25, 2026

    @Kriskras99
    Contributor

    For your second issue, I can reproduce it but don't yet understand why the enum causes a serialize_unit_struct instead of serialize_unit_variant.

  10. Kriskras99 commented on Jan 25, 2026

    @Kriskras99
    Contributor

    The second problem happens at ser_schema.rs:1455:

        fn serialize_unit_variant_with_schema(
            &mut self,
            name: &'static str,
            variant_index: u32,
            variant: &'static str,
            schema: &Schema,
        ) -> Result<usize, Error> {
            let create_error = |cause: String| {
                Error::new(Details::SerializeValueWithSchema {
                    value_type: "unit variant",
                    value: format!("{name}::{variant} (index={variant_index}). Cause: {cause}"),
                    schema: schema.clone(),
                })
            };
    
            match schema {
                Schema::Enum(enum_schema) => {
                    if variant_index as usize >= enum_schema.symbols.len() {
                        return Err(create_error(format!(
                            "Variant index out of bounds: {}. The Enum schema has '{}' symbols",
                            variant_index,
                            enum_schema.symbols.len()
                        )));
                    }
    
                    encode_int(variant_index as i32, &mut self.writer)
                }
                Schema::Union(union_schema) => {
                    if variant_index as usize >= union_schema.schemas.len() {
                        return Err(create_error(format!(
                            "Variant index out of bounds: {}. The union schema has '{}' schemas",
                            variant_index,
                            union_schema.schemas.len()
                        )));
                    }
    
                    encode_int(variant_index as i32, &mut self.writer)?;
    // It goes wrong here
                    self.serialize_unit_struct_with_schema(
                        name,
                        &union_schema.schemas[variant_index as usize],
                    )
                }
                Schema::Ref { name: ref_name } => {
                    let ref_schema = self.get_ref_schema(ref_name)?;
                    self.serialize_unit_variant_with_schema(name, variant_index, variant, ref_schema)
                }
                unsupported => Err(create_error(format!(
                    "Unsupported schema: {unsupported:?}. Expected: Enum, Union or Ref"
                ))),
            }
        }

    But the actual problem is caused by serialize_some_with_schema:

        fn serialize_some_with_schema<T>(&mut self, value: &T, schema: &Schema) -> Result<usize, Error>
        where
            T: ?Sized + ser::Serialize,
        {
            println!("serialize_some_with_schema: {schema}");
            let mut inner_ser = SchemaAwareWriteSerializer::new(
                &mut *self.writer,
                schema,
                self.names,
                self.enclosing_namespace.clone(),
            );
    // This should peel the schema but doesn't
            value.serialize(&mut inner_ser)
        }

    The root cause is that the serializer is too lenient. It allows serializing an Option<i64> to a long, instead of only allowing serializing an Option<i64> to an ["null", "long"].

    @martin-g I think we should make SchemaAwareStructSerializer a lot more strict in what it accepts, that would also help with supporting enums with struct variants.

  11. self-assigned this
    on Jan 27, 2026
  12. Kriskras99 commented on Jan 31, 2026

    @Kriskras99
    Contributor

    @Theodlz your first issue has been fixed in #448. Your second issue is related to the unreliable enum support in this crate, so I'll close this issue and keep tracking it in #365.

    Thank you for reporting the issues!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions