pola-rs/polars · error

cannot set validity of a union array

Error message

cannot set validity of a union array

What it means

Union arrays in polars-arrow have no validity bitmap of their own — nullability is expressed through the union's type/offset layout (e.g. a null child field), so `Array::with_validity` is intentionally unimplemented for `UnionArray` and panics on any call.

Solutions

  1. Don't call `with_validity` on union arrays; instead encode nulls via the union's child field (e.g. a Null-typed field) per the union layout.
  2. Type-dispatch before mutating: match the physical type and skip/alter the validity logic for unions.
  3. If you need a nullable union, rebuild the UnionArray with the desired structure rather than patching validity.
  4. Restrict the generic code path to non-union dtypes and reject unions with a clear error.

Example fix

// before
let arr = arr.with_validity(Some(validity));
// after
let arr = if matches!(arr.dtype().to_storage(), ArrowDataType::Union(_)) {
    arr // unions carry nullability in their layout; leave as-is
} else {
    arr.with_validity(Some(validity))
};
Defensive patterns

Strategy: type-guard

Validate before calling

fn union_supports_validity(dtype: &ArrowDataType) -> bool {
    !matches!(dtype.to_storage(), ArrowDataType::Union(_))
}

Type guard

fn is_union_array(arr: &dyn Array) -> bool {
    matches!(arr.dtype().to_storage(), ArrowDataType::Union(_))
}

Try / catch

// avoid the panic by dispatching:
let out: Box<dyn Array> = if is_union_array(arr.as_ref()) {
    Box::new(arr.clone()) // unions: nullability lives in the layout
} else {
    arr.with_validity(Some(validity))
};

Prevention

When it happens

Trigger: Calling `with_validity(Some(bitmap))` (or `None`) on a value statically typed as `Box<dyn Array>`/`&dyn Array` that is actually a UnionArray — e.g. generic code that sets a validity mask on any array, or `array.with_validity(...)` after slicing/concatenation pipelines.

Common situations: Generic column transformation code applying null masks uniformly across dtypes; migrating code that worked on Struct/List arrays to Union columns; feature work where a union column enters a code path written for regular arrays.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/ac5b23bc6116749f. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-arrow/src/array/union/mod.rs:349

    pub unsafe fn value_unchecked(&self, index: usize) -> Box<dyn Scalar> {
        debug_assert!(index < self.len());
        let (type_, index) = self.index_unchecked(index);
        // SAFETY: assumption of the struct
        debug_assert!(type_ < self.fields.len());
        let field = self.fields.get_unchecked(type_).as_ref();
        new_scalar(field, index)
    }
}

impl Array for UnionArray {
    impl_common_array!();

    fn validity(&self) -> Option<&Bitmap> {
        None
    }

    fn with_validity(&self, _: Option<Bitmap>) -> Box<dyn Array> {
        panic!("cannot set validity of a union array")
    }
}

impl UnionArray {
    fn try_get_all(dtype: &ArrowDataType) -> PolarsResult<UnionComponents<'_>> {
        match dtype.to_storage() {
            ArrowDataType::Union(u) => Ok((&u.fields, u.ids.as_ref().map(|x| x.as_ref()), u.mode)),
            _ => polars_bail!(ComputeError:
                "The UnionArray requires a logical type of DataType::Union",
            ),
        }
    }

    fn get_all(dtype: &ArrowDataType) -> (&[Field], Option<&[i32]>, UnionMode) {
        Self::try_get_all(dtype).unwrap()
    }

    /// Returns all fields from [`ArrowDataType::Union`].

View on GitHub (pinned to fe841f959e)