Skip to content

AVRO-3646: serde for enum with mixed variants - #1921

Closed
martin-g wants to merge 10 commits into
mainfrom
avro-3646-serde-for-enum-mixed-variants
Closed

martin-g wants to merge 10 commits into
mainfrom
avro-3646-serde-for-enum-mixed-variants

Conversation

@martin-g

Copy link
Copy Markdown
Member

What is the purpose of the change

Verifying this change

This change just adds unit tests

Documentation

  • Does this pull request introduce a new feature? no

@martin-g

Copy link
Copy Markdown
Member Author

@LucasJavaudin Could you please review the new unit tests ? Thanks!

@github-actions github-actions Bot added the Rust label Oct 20, 2022
@martin-g
martin-g force-pushed the avro-3646-serde-for-enum-mixed-variants branch from 8bcf5c4 to 9299438 Compare October 20, 2022 12:30
@martin-g
martin-g marked this pull request as draft October 21, 2022 06:39
@martin-g

Copy link
Copy Markdown
Member Author

Converted to Draft because as the JIRA ticket explains the produced Values cannot be represented using an Avro Schema.
The serialization should produce a Value::Union that wraps each of the currently produced Values.

@LucasJavaudin

Copy link
Copy Markdown
Contributor

@LucasJavaudin Could you please review the new unit tests ? Thanks!

Yes, this is good!

@LucasJavaudin

Copy link
Copy Markdown
Contributor

Can I push to this Draft a test that do not pass but that I think should pass?

@martin-g

Copy link
Copy Markdown
Member Author

Yes, this is good!

Is it ?
IMO the values should always be wrapped in Value::Union, so that it is possible to validate it with a Schema. The union items should be:

  • Value::String for unit_variant
  • Value::Array for newtype_variant and tuple_variant
  • Value::Record for struct_variant

@martin-g

Copy link
Copy Markdown
Member Author

Can I push to this Draft a test that do not pass but that I think should pass?

Only Avro project committers can push to this repository. You will have to open a PR against the branch for this PR.

@LucasJavaudin

Copy link
Copy Markdown
Contributor

Is it ? IMO the values should always be wrapped in Value::Union, so that it is possible to validate it with a Schema. The union items should be:

Sorry, I meant that the test are useful and they currently pass but I agree that they should not pass.

* Value::String for unit_variant

* Value::Array for newtype_variant and tuple_variant

* Value::Record for struct_variant

For unit variant, shouldn't it be Value::Null?

@martin-g

Copy link
Copy Markdown
Member Author

There might be more than one unit variants in the enum. I think it should be Value::String with the name of the variant, to be able to deserialize.

@LucasJavaudin

Copy link
Copy Markdown
Contributor

Consider the following enum:

enum MyEnum {
    Val1,
    Val2,
    Val3(u64),
}

What should be its schema?

I can think of two options.

A record with two fields

  • Field "type" which is an enum with symbols "Val1", "Val2", "Val3".
  • Field "value" which is an union.

The union cannot be ["null", "null", "long"] (or ["string", "string", "long"]) because we cannot have the same type twice. Correct?

Can it be just ["null", "long"] or [enum(["Val1"]), enum(["Val2"]), "long"]? Neither seems intuitive to me.

An union

With the enum [enum(["Val1"]), enum(["Val2"]), "long"], we can know both the variant and the data (if any) but this requires to match the Val3(u64) variant to "long", without using the variant name. (Can we match variants by their order?)

@martin-g
martin-g force-pushed the avro-3646-serde-for-enum-mixed-variants branch 3 times, most recently from 4d2f191 to 806b355 Compare November 8, 2022 19:45
@martin-g
martin-g marked this pull request as ready for review November 8, 2022 21:00
@martin-g

martin-g commented Nov 8, 2022

Copy link
Copy Markdown
Member Author

@LucasJavaudin I think the PR is ready for final review!
I'd be thankful if you can provide more use cases / unit tests!

@martin-g

martin-g commented Nov 8, 2022

Copy link
Copy Markdown
Member Author

The avro_derive tests fail ...
I'll investigate soon!

@LucasJavaudin

Copy link
Copy Markdown
Contributor

@martin-g Thank you for your work! This solves the issue I raised in AVRO-3646.

I pushed two new integration tests in #1949 that try to deserialize and serialize more complex enums. The tests do not pass for multiple reasons. I think that would improve greatly the library if we could (de)serialize arbitrary enums (and even derive a schema for them) but maybe this needs to much work?

Unfortunately, I don't have enough time myself to do more than adding tests and reviewing your changes.

@martin-g martin-g mentioned this pull request Nov 10, 2022
@martin-g

martin-g commented Nov 11, 2022 •

Copy link
Copy Markdown
Member Author

The avro_derive tests fail ...

The problem here is that another user (@jklamer, the contributor of the avro_derive crate) expects that

#[derive(Debug, Deserialize, Serialize, AvroSchema, Clone, PartialEq, Eq)]
enum MyEnum {
    Foo,
    Bar,
    Baz,
}

should map to this Avro schema:

{
  "name":"myenum",
  "type":{
    "type":"enum",
     "name":"MyEnum",
     "symbols":["Foo", "Bar", "Baz"]
   },
   "default":"Foo"
}

Which is really nice! But unfortunately does not work anymore with the new way of supporting complex Rust enums (ones with non-null tuple/newtype/struct variants).

The only way to still support the above I see is to introduce a second Serializer impl, e.g. UnitEnumSerializer and let the user decide which one to use. But the problem is that a Writer could use either the complex Serializer or the UnitEnumSerializer. There won't be a way to use one serializer for a given RecordField and another serializer for another field.

Also CC @spiegela

@jklamer

jklamer commented Nov 11, 2022

Copy link
Copy Markdown
Contributor

Yeah, this conversation is split over a couple different PR's, threads, and e-mails. But I'll respond here. With avro_derive I was very intentional about only tackling cases that I could make work automatically with serde and the normal serializer for the best new user experience. Modeling a Rust enum as some Avro entity opened too many cans of worms to handle automatically, having something opt in would be the only way to go but would also make it harder to mix Rust enums and Avro enums clearly (as mentioned above), to say nothing of the ambiguity of the deserialization process.

My bias would be to create a Macro that creates an intermediate form that is unambiguously convertible between Rust Enum and an Avro compatible entity and do the conversion before serialization and after deserialization (don't try to make serde process work outside the avro spec) (and could point to macro in the AvroSchema derive error), but I personally haven't been able to think of a solution that works for every case. Rust's type system is just most expansive that Avro's, so the ambiguity is inevitable at some level.

That being said, I LOVE Rust enums, with a passion, and when I realized I couldn't automatically serde them... I started something that could. <-- me shaving the yak.

TLDR: I think it's impossible to do automatically without creating ambiguity that I would like to shield most users from. I think doing it as an opt in with clearly defined restrictions (and good error messages) would be a good to go for advanced users.

CC @spiegela
CC @LucasJavaudin

@github-actions github-actions Bot added the build label Nov 11, 2022
@martin-g

martin-g commented Nov 11, 2022 •

Copy link
Copy Markdown
Member Author

I wonder whether we can use https://serde.rs/enum-representations.html#untagged to give a hint to apache_avro (de)serialization process to keep the old behavior.
I am looking into serde's source code to see how impls like apache_avro can know that this attribute is being used.

@martin-g

martin-g commented Nov 11, 2022 •

Copy link
Copy Markdown
Member Author

Actually it doesn't need to be #serde(untagged). It could be even #avro(something).
I miss Java annotations + reflection APIs :-)

@jklamer

jklamer commented Nov 11, 2022

Copy link
Copy Markdown
Contributor

@martin-g hahaha agreed. And now with Java Sealed classes, a pretty clear Rust Enum 1-1 could be made too!

@martin-g

Copy link
Copy Markdown
Member Author

Another user asked for the same functionality at serde-rs/serde#2309

@spiegela

spiegela commented Nov 14, 2022 •

Copy link
Copy Markdown

To make sure I understand the status of change, is the remaining question here how the AvroSchema derive should ”choose” which enum format to use when constructing the schema?

If so, I was thinking that the AvroSchema derive could infer the correct behavior based on the variant characteristics:

  • All unit variants, create an enum schema as we do today.
  • 1+ non-unit variants with either named fields, or single-field unnamed fields, use the Record-style (as in this PR) as the schema.

That leaves the case of non-unit, multi-field, unnamed fields 😅. For those, we should return a compile error, I think, and let the dev implement AvroSchemaComponent themselves — otherwise, could add Record fields named 0, 1, …

@martin-g

Copy link
Copy Markdown
Member Author

The actual problem in ser.rs and de.rs.
This PR changes the way apache_avro serializes objects/instances into apache_avro::types::Value.
For now I see no way to make the serde logic more dynamic, i.e. depending on the enum variants' types or on container/field's attribute to decide what kind of Value to construct.

The new serde logic is powerful enough to handle complex kinds of Rust enums (by using Schema::Record([Schema::Enum, Schema::Union])). But it does not support the old representation (Schema::Enum) because all variants are mapped to Value::Null and there could be at most one null in an Avro Union.

The logic what schema to derive looks like a simpler task (although I haven't tried it yet, so I might be wrong).

martin-g added a commit that referenced this pull request Feb 9, 2023
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of #1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
martin-g added a commit that referenced this pull request Feb 9, 2023
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of #1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
martin-g added a commit that referenced this pull request Feb 9, 2023
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of #1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
(cherry picked from commit 0ea0dcc)
martin-g and others added 10 commits February 9, 2023 15:46
…ent variants

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
Also do schema validation on the produced avro values

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
…ith nullable struct_variant

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
…ariants (#1949)

* AVRO-3646: Add a test that (de)serialize a enum with mixed variants

* AVRO-3646: Add a test that (de)serialize a enum w/ duplicates variants

* Enable PR checks for all PRs, not just the ones against master

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

* AVRO-3646: Fix a clippy error about enum variant being postfixed with 'Variant'

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

* AVRO-3646: Fix the serialization (X -> types::Value) for enum tuple variants

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

* AVRO-3646: Fix the name of the enum variants in the Avro schema

Rename the test method to be different than the one in serde_enum.rs IT
tests.

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

* AVRO-3646: Remove the duplicates to conform to Avro specification

A Union could have at most one item for a primitive type

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

* AVRO-3646: Remove dbg!() statement. Fix clippy errors

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
Co-authored-by: LucasJavaudin <[email protected]>
Co-authored-by: Martin Tzvetanov Grigorov <[email protected]>
@martin-g
martin-g force-pushed the avro-3646-serde-for-enum-mixed-variants branch from d61f529 to c17bddb Compare February 9, 2023 13:54
a0x8o added a commit to a0x8o/avro that referenced this pull request Feb 11, 2023
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of apache/avro#1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
@markfarnan

markfarnan commented Mar 13, 2023 •

Copy link
Copy Markdown

Seems like AVRO-3695 should be addressed in this issue. (see #2035)

However I just tested it against Master + AVRO-3631 and it does not address the problem.

This is my last blocking issue for using Rust for our industry protocol, so hoping it can be looked at. @martin-g ?

I've created what is probably a 'Hack' fix that addresses the issue for me. But honestly I'm not sure what i'm doing here, so it likley breaks other stuff. (So I havn't made a PR, just added here for your info)

ser.rs. line # 260 or so

fn serialize_newtype_variant<T: ?Sized>(
        self,
        _enum_name: &'static str,
        index: u32,
        _variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        let serialized = value.serialize(self)?;
        let _idx = match serialized {
            // assumes that the Null variant is always the first one, as in Avro's Union
            Value::Null => 0,
            _ => index,
        };
        // Ok(Value::Record(vec![
        //     ("type".to_owned(), Value::Enum(index, variant.to_owned())),
        //     ("value".to_owned(), Value::Union(idx, Box::new(serialized))),
        // ]))

        Ok(Value::Union(index, Box::new(serialized)))
    }

martin-g added a commit to apache/avro-rs that referenced this pull request Sep 23, 2024
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of apache/avro#1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
@mati865

mati865 commented Nov 22, 2024

Copy link
Copy Markdown

Hi @martin-g
Are there any blockers for this change? Can I somehow help to push this forward?

@KalleOlaviNiemitalo

Copy link
Copy Markdown
Contributor

@mati865

mati865 commented Nov 22, 2024

Copy link
Copy Markdown

@KalleOlaviNiemitalo I'm aware of that, but it would be impolite to copy changes from someone's branch without asking first.

@martin-g

Copy link
Copy Markdown
Member Author

Any help is welcome!
The problem with the enums is the same as in Serde itself - I.e. there are many problems.

@mati865

mati865 commented Dec 2, 2024

Copy link
Copy Markdown

I've played with this code for a few hours now, and I think I finally understand at least some problems.

When it comes to simple vs complex enums handling, Serde is too generic and doesn't allow distinguishing between Enum variants with or without values. But for Avro the difference is quite significant.

If we take this code:

enum One {
	A,
	B
}

enum Two {
	A,
	B(String)
}

enum Three {
	A(i32),
	B(String)
}
// And all other gazillion variations

Serde will straight call serialize_unit_variant on each variant, so the code will always output simple or complex enums.

An obvious way to solve it, although not very convenient, would be to create an attribute or derive proc-macro that generates serializer and deserializer for enums since proc-macros can get all the required information.

Maybe Serde feature that would help here could be requested from, but I don't know if it's even possible to introduce such a significant change at this point.


I think the other issues like the ones mentioned in #1921 (comment) are at least in some part caused by this "simple vs complex enums handling".

@martin-g

martin-g commented Dec 2, 2024

Copy link
Copy Markdown
Member Author

Maybe Serde feature that would help here could be requested from, but I don't know if it's even possible to introduce such a significant change at this point.

I am pretty sure that such additions to serde(**) would be rejected!

@martin-g

martin-g commented Dec 2, 2024

Copy link
Copy Markdown
Member Author

An obvious way to solve it, although not very convenient, would be to create an attribute or derive proc-macro that generates serializer and deserializer for enums since proc-macros can get all the required information.

Feel free to experiment and send a PR for discussion!

@mati865

mati865 commented Jan 1, 2025

Copy link
Copy Markdown

Sorry for the late reply.
I had tried a few ideas, but you are right. Serde seems just not fit for this use case.

All my attempts eventually more or less resulted in rewriting serde, or parts of it.

The most reasonable solution seems to be what Borsh did by creating their own serialization framework: https://github.com/near/borsh-rs/tree/master/borsh-derive
Another solution is what serde_avro_fast does: creating a state with information how to (de)serialize the nodes and looking it up during that process.

They both require enormous implementation effort, though. I won't be able to dedicate so much time to it.

@martin-g martin-g closed this Oct 23, 2025
StitchMl pushed a commit to StitchMl/avro that referenced this pull request Jul 13, 2026
These improvements were identified while working on AVRO-3646 but they
are not related to the changes related to this ticket.

This commit was part of apache#1921

Signed-off-by: Martin Tzvetanov Grigorov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants