Skip to content

Why does AvroSchemaComponent::get_schema_in_ctxt take a Names? #400

Closed

Description

@Kriskras99

AvroSchemaComponent looks like this:

pub trait AvroSchemaComponent {
    fn get_schema_in_ctxt(named_schemas: &mut Names, enclosing_namespace: &Namespace) -> Schema;
}

but looking at the code generated by #[derive(AvroSchema)] we only insert Schema::Refs into that map:

impl #impl_generics apache_avro::AvroSchemaComponent for #ident #ty_generics #where_clause {
    fn get_schema_in_ctxt(named_schemas: &mut std::collections::HashMap<apache_avro::schema::Name, apache_avro::schema::Schema>, enclosing_namespace: &Option<String>) -> apache_avro::schema::Schema {
        let name =  apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse schema name {}", #full_schema_name)[..]).fully_qualified_name(enclosing_namespace);
        let enclosing_namespace = &name.namespace;
        if named_schemas.contains_key(&name) {
            apache_avro::schema::Schema::Ref{name: name.clone()}
        } else {
            named_schemas.insert(name.clone(), apache_avro::schema::Schema::Ref{name: name.clone()});
            #schema_def
        }
    }
}

As the key is the name, we could also just use a HashSet instead:

impl #impl_generics apache_avro::AvroSchemaComponent for #ident #ty_generics #where_clause {
    fn get_schema_in_ctxt(named_schemas: &mut std::collections::HashSet<apache_avro::schema::Name, enclosing_namespace: &Option<String>) -> apache_avro::schema::Schema {
        let name =  apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse schema name {}", #full_schema_name)[..]).fully_qualified_name(enclosing_namespace);
        let enclosing_namespace = &name.namespace;
        if named_schemas.get(&name).is_some() {
            apache_avro::schema::Schema::Ref{name}
        } else {
            named_schemas.insert(name.clone());
            #schema_def
        }
    }
}

If we are supposed to put actual schemas in there, then we are generating the wrong code and should be generating something like this instead:

impl #impl_generics apache_avro::AvroSchemaComponent for #ident #ty_generics #where_clause {
    fn get_schema_in_ctxt(named_schemas: &mut std::collections::HashMap<apache_avro::schema::Name, apache_avro::schema::Schema>, enclosing_namespace: &Option<String>) -> apache_avro::schema::Schema {
        let name =  apache_avro::schema::Name::new(#full_schema_name).expect(&format!("Unable to parse schema name {}", #full_schema_name)[..]).fully_qualified_name(enclosing_namespace);
        let enclosing_namespace = &name.namespace;
        if named_schemas.contains_key(&name) {
            apache_avro::schema::Schema::Ref{name: name.clone()}
        } else {
            let schema = #schema_def
            named_schemas.insert(name, schema.clone())
            schema
        }
    }
}

Activity

  1. martin-g commented on Jan 13, 2026

    @martin-g
    Member

    @jklamer Do you want to join the workstream here as the original author ? :-)

    I haven't checked the code but I think we have to change it to the last suggestion, i.e. named_schemas.insert(name, schema.clone())

  2. Kriskras99 commented on Jan 15, 2026

    @Kriskras99
    ContributorAuthor

    I've figured out why it is inserted before the schema definition is created. If a type is recursive:

    struct ConsList {
        value: i32,
        next: Option<Box<ConsList>>,
    }

    and you don't insert the name into named_schemas, then it will loop forever and eventually cause a stack overflow.
    I've 'fixed' it in the derive code (#397) by doing this:

    let name = apache_avro::schema::Name::new(#full_schema_name).expect(concat!("Unable to parse schema name ", #full_schema_name)).fully_qualified_name(enclosing_namespace);
    if named_schemas.contains_key(&name) {
        apache_avro::schema::Schema::Ref{name}
    } else {
        let enclosing_namespace = &name.namespace;
        // This is needed because otherwise recursive types will recurse forever and cause a stack overflow
        // TODO: Breaking change to AvroSchemaComponent, have named_schemas be a set instead
        named_schemas.insert(name.clone(), apache_avro::schema::Schema::Ref{name: name.clone()});
        let schema = #schema_def;
        named_schemas.insert(name, schema.clone());
        schema
    }

    I really think we should change it from a HashMap to a HashSet:

    1. The old behaviour is useless, it just inserts Schema::Ref which you can get from the name
    2. The new behavior is wastefull, as in 99% of usecases named_schemas is discarded after the schema is generated
    3. It won't break that much code, as most users will be using the #[derive(AvroSchema)] and AvroSchema::get_schema instead of interacting with AvroSchemaComponent. Fixing the breakage is also really easy for users.
  3. martin-g commented on Jan 16, 2026

    @martin-g
    Member

    named_schemas.insert(name.clone(), apache_avro::schema::Schema::Ref{name: name.clone()});
    let schema = #schema_def;
    named_schemas.insert(name, schema.clone());

    I don't understand this.
    What let schema = #schema_def; does that requires the Ref entry in named_schemas ?

  4. Kriskras99 commented on Jan 16, 2026

    @Kriskras99
    ContributorAuthor

    Sorry, that's my fault. #schema_def is something from the avro_derive code. Here's a type expanded, so you can see what's going on:

    pub struct Recursive {
        field: Option<Box<Recursive>>,
    }
    impl AvroSchemaComponent for Recursive {
        fn get_schema_in_ctxt(
            named_schemas: &mut Names,
            enclosing_namespace: &Option<String>,
        ) -> Schema {
            let name = Name::new("Recursive")
                .expect("Unable to parse schema name Recursive")
                .fully_qualified_name(enclosing_namespace);
            if named_schemas.contains_key(&name) {
                Schema::Ref { name }
            } else {
                let enclosing_namespace = &name.namespace;
                // Without this, this function would recurse forever and cause a stackoverflow
                named_schemas.insert(name.clone(), Schema::Ref { name: name.clone() });
                let schema = {
                    let schema_fields = vec![
                        RecordField::builder()
                            .name("field".to_string())
                            // This is the recursive call
                            .schema(<Option<Box<Recursive>>>::get_schema_in_ctxt(
                                named_schemas,
                                enclosing_namespace,
                            ))
                            .build(),
                    ];
                    Schema::Record(
                        RecordSchema::builder()
                            .name(name.clone())
                            .lookup(
                                schema_fields
                                    .iter()
                                    .map(|field| (field.name.clone(), field.position))
                                    .collect(),
                            )
                            .fields(schema_fields)
                            .build(),
                    )
                };
                named_schemas.insert(name, schema.clone());
                schema
            }
        }
    }

    Note: it does not matter what is inserted into named_schemas the first time, instead of a Schema::Ref it could also be a Schema::Null. The reason that I insert a Schema::Ref, is that user implementations of AvroSchemaComponent may depend on the type that is in named_schemas.

  5. self-assigned this
    on Jan 27, 2026
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