{"record":{"id":"ac5b23bc6116749f","repo":"pola-rs/polars","slug":"cannot-set-validity-of-a-union-array","errorCode":null,"errorMessage":"cannot set validity of a union array","messagePattern":"cannot set validity of a union array","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-arrow/src/array/union/mod.rs","lineNumber":349,"sourceCode":"    pub unsafe fn value_unchecked(&self, index: usize) -> Box<dyn Scalar> {\n        debug_assert!(index < self.len());\n        let (type_, index) = self.index_unchecked(index);\n        // SAFETY: assumption of the struct\n        debug_assert!(type_ < self.fields.len());\n        let field = self.fields.get_unchecked(type_).as_ref();\n        new_scalar(field, index)\n    }\n}\n\nimpl Array for UnionArray {\n    impl_common_array!();\n\n    fn validity(&self) -> Option<&Bitmap> {\n        None\n    }\n\n    fn with_validity(&self, _: Option<Bitmap>) -> Box<dyn Array> {\n        panic!(\"cannot set validity of a union array\")\n    }\n}\n\nimpl UnionArray {\n    fn try_get_all(dtype: &ArrowDataType) -> PolarsResult<UnionComponents<'_>> {\n        match dtype.to_storage() {\n            ArrowDataType::Union(u) => Ok((&u.fields, u.ids.as_ref().map(|x| x.as_ref()), u.mode)),\n            _ => polars_bail!(ComputeError:\n                \"The UnionArray requires a logical type of DataType::Union\",\n            ),\n        }\n    }\n\n    fn get_all(dtype: &ArrowDataType) -> (&[Field], Option<&[i32]>, UnionMode) {\n        Self::try_get_all(dtype).unwrap()\n    }\n\n    /// Returns all fields from [`ArrowDataType::Union`].","sourceCodeStart":331,"sourceCodeEnd":367,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-arrow/src/array/union/mod.rs#L331-L367","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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.","Type-dispatch before mutating: match the physical type and skip/alter the validity logic for unions.","If you need a nullable union, rebuild the UnionArray with the desired structure rather than patching validity.","Restrict the generic code path to non-union dtypes and reject unions with a clear error."],"exampleFix":"// before\nlet arr = arr.with_validity(Some(validity));\n// after\nlet arr = if matches!(arr.dtype().to_storage(), ArrowDataType::Union(_)) {\n    arr // unions carry nullability in their layout; leave as-is\n} else {\n    arr.with_validity(Some(validity))\n};","handlingStrategy":"type-guard","validationCode":"fn union_supports_validity(dtype: &ArrowDataType) -> bool {\n    !matches!(dtype.to_storage(), ArrowDataType::Union(_))\n}","typeGuard":"fn is_union_array(arr: &dyn Array) -> bool {\n    matches!(arr.dtype().to_storage(), ArrowDataType::Union(_))\n}","tryCatchPattern":"// avoid the panic by dispatching:\nlet out: Box<dyn Array> = if is_union_array(arr.as_ref()) {\n    Box::new(arr.clone()) // unions: nullability lives in the layout\n} else {\n    arr.with_validity(Some(validity))\n};","preventionTips":["Never assume every `dyn Array` supports with_validity; check the physical type first","Model union nullability via a Null child field, not a validity bitmap","Add a debug assertion on dtype in generic validity-mutation helpers"],"tags":["rust","arrow","union","validity","unsupported-operation"],"backgroundTag":"unsupported-operation","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}