Repository navigation
Description
Describe the bug
The Union DataType produced by UnionBuilder has non-nullable children Fields after appending nulls in the builder.
To Reproduce
Steps to reproduce the behavior: Try the following code
let mut builder = UnionBuilder::new_dense(4);
builder.append::<Int32Type>("a", 1).unwrap();
builder.append::<Float64Type>("b", 3.0).unwrap();
builder.append_null::<Float64Type>("b").unwrap();
builder.append_null::<Int32Type>("a").unwrap();
let union = builder.build().unwrap();
let schema = Schema::new(vec![
Field::new(
"Teamsters",
DataType::Union(
vec![
Field::new("a", DataType::Int32, true),
Field::new("b", DataType::Float64, true),
],
UnionMode::Dense,
),
false,
),
]);
let batch = RecordBatch::try_new(
Arc::new(schema),
vec![Arc::new(union)]
).unwrap();
This code panics:
InvalidArgumentError("column types must match schema types, expected
Union([
Field { name: "a", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: None },
Field { name: "b", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: None }
], Dense
) but found Union([
Field { name: "a", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: None },
Field { name: "b", data_type: Float64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: None }
], Dense)
at column index 0")
Expected behavior
Depending on the interpretation of the specification, one of 2 things should happen:
A Union's children Fields should inherit its nullabillity (i.e. always be false): Then I think this should error when executing Field::new() with a bad DataType.
A child should be nullable if it is capable of returning None to the parent when unionArray.value(index) is called: This code should run just fine then.
Additional context
I ran into this when working on #1594. I think it's a simple fix: track the nullablility of the UnionBuilder fields rather than always hardcode the child Fields nullability to be false. That being said, I'm not sure if that's the correct understanding of the specification.
Activity
tustvold commentedon May 3, 2022
I think automatically determining the nullability of the field based on if that child contains nulls makes a lot of sense, however, it could cause schema-volatility depending on if the written data happens to contain nulls which seems sub-optimal.
I think the safest thing is probably to do what
GenericListBuilderdoes and always set nullable to true, but it does feel a bit off...Edit: FWIW @jhorstmann reported a similar issue recently with StructArrays - #1611
tustvold commentedon May 5, 2022
Further #1649
gstvg commentedon Aug 29, 2024
I also ran into this on #6303
We probably should care about the generated type_id of each field too.
Currently, the returned union only contains fields appended at least once. So every
build_unioncalls below returns a different set of children with different type_id each.Do you think we should follow
GenericListBuilder, and add a method to specifyUnionFields, or require it as an argument forUnionBuilderconstructors?If the fields are somehow specified, should the returned array contains every child specified, or only those appended at least one time?
I thought about another option, and would like to know what you think
First, we need to add an id argument to the current
append*functions:And then add
And finally, document that nullable fields should only use
append_nullandappend_nullable, while non nullable ones should only useappend, and return an error if the same field is appended with mixed callspepijnve commentedon Jun 28, 2026
I was going through old issues and this one piqued my interest. I had a look at the current state of
UnionBuilderand it seems like there is quite some room for improvement. TheBTreeMap<String, FieldData>and the wayFieldDataseems to be removed and reinserted on each append in particular seems rather problematic from a performance point of view. An API where the possible fields are specified up front seems more sensible.I can have a go at implementing this, but integrating that in the existing implementation seems like it's more hassle than it's worth. In particular, being forced to pass the field name on each append (and as a consequence being forced to verify it in the implementation) doesn't seem desirable.
What would the best solution be here? Create a new parallel 'statically defined union type' implementation or break compatibility of the existing implementation?
Jefffrey commentedon Jul 2, 2026
Maybe this would be the least surprising option for users too 🤔
If they had to contend with a single
UnionBuilderwhich could either be static or dynamic but might have different behaviour if trying to dynamically add a new field that wasnt statically defined, could be confusingpepijnve commentedon Jul 2, 2026
I started prototyping something and it turned out to be an interesting challenge to make an ergonomic API for this. The current
UnionBuildergets away with some things because it only actually supports primitive types. If we extend this to arbitrary types, thenappend_valuebecomes a challenge. For sparse unions you need a way to fill in a null value for all the other types. TheArrayBuildertrait doesn't provide that capability though. Not sure how to solve that.We can extend
ArrayBuilder, but that's a backwards incompatible change.Or I can make a big
matchon all the existingArrayBuildertypes, but that's no longer extensible then.I also struggled a bit with extending
to arbitrary types since I don't think there's a common base trait you can use here to abstract over primitives, strings, structs, lists, other unions...

I got something working using the builder as generic type parameter which resulted in code like this. Not quite happy with it yet.
The alternative seems to be something like the approach
StructBuildertakes where you expose the individual builders, and it's then the caller's responsibility to make sure they do everything right before callingStructBuilder::append. That works, but feels a bit error prone.This just to say it's not as easy as I thought it would be at first. I'll mull on it some more. Any ides/suggestions are appreciated of course.