You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Issue with schema generation using T::get_schema() #435
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).
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
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)]pubenumColor{G,R,I}#[derive(Deserialize,Serialize,AvroSchema)]pubstructA{pubtime:f64,pubcolor:Color,}#[derive(Deserialize,Serialize,AvroSchema)]pubstructB{pubtime:f64,pubcolor:Option<Color>,}#[derive(Deserialize,Serialize,AvroSchema)]pubstructC{#[serde(flatten)]puba:A,}#[derive(Deserialize,Serialize,AvroSchema)]pubstructTestStruct{pubb:B,pubvec_c:Vec<C>,}fnmain(){let test = TestStruct{b:B{time:42.0,color:Some(Color::R)},vec_c:vec![],};let schema = TestStruct::get_schema();letmut 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. }.
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:
pubtraitAvroSchemaComponent{// If transparent is `true` then don't insert the schema into `named_schemas`fnget_schema_in_ctxt(named_schemas:&mutHashMap<Name,Schema>,enclosing_namespace:&Namespace,transparent:bool);}
fnserialize_unit_variant_with_schema(&mutself,name:&'staticstr,variant_index:u32,variant:&'staticstr,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 asusize >= enum_schema.symbols.len(){returnErr(create_error(format!("Variant index out of bounds: {}. The Enum schema has '{}' symbols",
variant_index,
enum_schema.symbols.len())));}encode_int(variant_index asi32,&mutself.writer)}Schema::Union(union_schema) => {if variant_index asusize >= union_schema.schemas.len(){returnErr(create_error(format!("Variant index out of bounds: {}. The union schema has '{}' schemas",
variant_index,
union_schema.schemas.len())));}encode_int(variant_index asi32,&mutself.writer)?;// It goes wrong hereself.serialize_unit_struct_with_schema(
name,&union_schema.schemas[variant_index asusize],)}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:
fnserialize_some_with_schema<T>(&mutself,value:&T,schema:&Schema) -> Result<usize,Error>whereT: ?Sized + ser::Serialize,{println!("serialize_some_with_schema: {schema}");letmut 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.
@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.
Activity
[-]Issue with schema generation with `T::get_schema()`[/-][+]Issue with schema generation using `T::get_schema()`[/+]martin-g commentedon Jan 24, 2026
Please try current main branch.
If it still doesn't work then please provide a failing test case!
Theodlz commentedon Jan 24, 2026
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.
Theodlz commentedon Jan 24, 2026
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
Theodlz commentedon Jan 24, 2026
Ok, so here is the original bug mentioned in this issue, reproduced:
So here, the problem is that this
Colortype is occurring twice in the generated schema, which yields:Error { details: Two named schema defined for same fullname: Color. }.Theodlz commentedon Jan 24, 2026
HOWEVER, here is another bug that's probably related, and much easier to reproduce:
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
Theodlz commentedon Jan 24, 2026
BTW this optional vs non optional issue only happens with enums. If I replace the
Colorenum with a struct, then that all goes away.Kriskras99 commentedon Jan 25, 2026
The first issue can be reduced to this:
The problem is that when the
transparentattribute is used, that schema is called using a newnamed_schemasbecause we don't want to insert the schema forAin case it's used in another field because then it would be a ref to a schema that does not exist:I think the solution would be changing to trait to this:
This would of course be a breaking change.
Kriskras99 commentedon Jan 25, 2026
For your second issue, I can reproduce it but don't yet understand why the enum causes a
serialize_unit_structinstead ofserialize_unit_variant.Kriskras99 commentedon Jan 25, 2026
The second problem happens at
ser_schema.rs:1455:But the actual problem is caused by
serialize_some_with_schema:The root cause is that the serializer is too lenient. It allows serializing an
Option<i64>to along, instead of only allowing serializing anOption<i64>to an["null", "long"].@martin-g I think we should make
SchemaAwareStructSerializera lot more strict in what it accepts, that would also help with supporting enums with struct variants.Kriskras99 commentedon Jan 31, 2026
@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!