pola-rs/polars · error

MutableUtf8ValuesArray can only be initialized with…

Error message

MutableUtf8ValuesArray can only be initialized with DataType::Utf8 or DataType::LargeUtf8

What it means

`MutableUtf8ValuesArray` only supports `DataType::Utf8` and `DataType::LargeUtf8` physical types; its dtype parameter is validated right after the offset bounds check. Passing any other dtype (Binary, List, etc.) would make subsequent typed value access unsound, so the constructor panics.

Solutions

  1. Pass `DataType::Utf8` or `DataType::LargeUtf8` (match `O`: u32→Utf8, u64→LargeUtf8).
  2. For binary data use `MutableBinaryValuesArray` instead.
  3. Dispatch on the dtype before constructing so only UTF8 dtypes reach this builder.
  4. If dtype comes from metadata, validate it upfront and return an error for non-UTF8 variants.

Example fix

// before
let arr = unsafe { MutableUtf8ValuesArray::new_unchecked(dtype.clone(), offsets, values) };
// after
let arr = match dtype {
    ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 =>
        unsafe { MutableUtf8ValuesArray::new_unchecked(dtype.clone(), offsets, values) },
    ArrowDataType::Binary | ArrowDataType::LargeBinary =>
        MutableBinaryValuesArray::new_unchecked(dtype.clone(), offsets, values).into_boxed(),
    _ => return Err(PolarsError::InvalidOperation("unsupported dtype".into())),
};
Defensive patterns

Strategy: type-guard

Validate before calling

fn is_utf8_dtype(dtype: &ArrowDataType) -> bool {
    matches!(dtype.to_storage(), ArrowDataType::Utf8 | ArrowDataType::LargeUtf8)
}

Type guard

fn utf8_dtype_for<O: NativeOffset>() -> ArrowDataType {
    if size_of::<O>() == 4 { ArrowDataType::Utf8 } else { ArrowDataType::LargeUtf8 }
}

Prevention

When it happens

Trigger: Calling `MutableUtf8ValuesArray::new_unchecked(dtype, offsets, values)` with a dtype whose physical type differs from Utf8/LargeUtf8 — e.g. `Binary`, `FixedSizeBinary`, or a custom dtype.

Common situations: Generic mutable-array builders parameterized by dtype that route binary data into the UTF8 builder by mistake; dtype read from external metadata (schema files, IPC) mapping to the wrong variant; copy-paste of Utf8 code for a Binary column.

Related errors


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

Appendix: source

Thrown at crates/polars-arrow/src/array/utf8/mutable_values.rs:113

    /// * `offsets.last()` is greater than `values.len()`
    /// * The `dtype`'s [`crate::datatypes::PhysicalType`] is equal to either `Utf8` or `LargeUtf8`.
    ///
    /// # Safety
    /// This function is safe iff:
    /// * the offsets are monotonically increasing
    /// * The `values` between two consecutive `offsets` are not valid utf8
    /// # Implementation
    /// This function is `O(1)`
    pub unsafe fn new_unchecked(
        dtype: ArrowDataType,
        offsets: Offsets<O>,
        values: Vec<u8>,
    ) -> Self {
        try_check_offsets_bounds(&offsets, values.len())
            .expect("The length of the values must be equal to the last offset value");

        if dtype.to_physical_type() != Self::default_dtype().to_physical_type() {
            panic!(
                "MutableUtf8ValuesArray can only be initialized with DataType::Utf8 or DataType::LargeUtf8"
            )
        }

        Self {
            dtype,
            offsets,
            values,
        }
    }

    /// Returns the default [`ArrowDataType`] of this container: [`ArrowDataType::Utf8`] or [`ArrowDataType::LargeUtf8`]
    /// depending on the generic [`Offset`].
    pub fn default_dtype() -> ArrowDataType {
        Utf8Array::<O>::default_dtype()
    }

    /// Initializes a new [`MutableUtf8ValuesArray`] with a pre-allocated capacity of items.

View on GitHub (pinned to fe841f959e)