Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(rust): Reduce size of ArrowDataType by boxing heavy variants #20588

Merged
merged 4 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions crates/polars-arrow/src/array/union/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,14 @@ impl UnionArray {

/// Creates a new null [`UnionArray`].
pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {
if let ArrowDataType::Union(f, _, mode) = &dtype {
let fields = f
if let ArrowDataType::Union(u) = &dtype {
let fields = u
.fields
.iter()
.map(|x| new_null_array(x.dtype().clone(), length))
.collect();

let offsets = if mode.is_sparse() {
let offsets = if u.mode.is_sparse() {
None
} else {
Some((0..length as i32).collect::<Vec<_>>().into())
Expand All @@ -194,13 +195,14 @@ impl UnionArray {

/// Creates a new empty [`UnionArray`].
pub fn new_empty(dtype: ArrowDataType) -> Self {
if let ArrowDataType::Union(f, _, mode) = dtype.to_logical_type() {
let fields = f
if let ArrowDataType::Union(u) = dtype.to_logical_type() {
let fields = u
.fields
.iter()
.map(|x| new_empty_array(x.dtype().clone()))
.collect();

let offsets = if mode.is_sparse() {
let offsets = if u.mode.is_sparse() {
None
} else {
Some(Buffer::default())
Expand Down Expand Up @@ -351,9 +353,7 @@ impl Array for UnionArray {
impl UnionArray {
fn try_get_all(dtype: &ArrowDataType) -> PolarsResult<UnionComponents> {
match dtype.to_logical_type() {
ArrowDataType::Union(fields, ids, mode) => {
Ok((fields, ids.as_ref().map(|x| x.as_ref()), *mode))
},
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",
),
Expand Down
43 changes: 27 additions & 16 deletions crates/polars-arrow/src/datatypes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,7 @@ pub enum ArrowDataType {
/// Decimal backed by 256 bits
Decimal256(usize, usize),
/// Extension type.
/// - name
/// - physical type
/// - metadata
Extension(PlSmallStr, Box<ArrowDataType>, Option<PlSmallStr>),
Extension(Box<ExtensionType>),
/// A binary type that inlines small values
/// and can intern bytes.
BinaryView,
Expand All @@ -175,7 +172,22 @@ pub enum ArrowDataType {
/// A nested datatype that can represent slots of differing types.
/// Third argument represents mode
#[cfg_attr(feature = "serde", serde(skip))]
Union(Vec<Field>, Option<Vec<i32>>, UnionMode),
Union(Box<UnionType>),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ExtensionType {
pub name: PlSmallStr,
pub inner: ArrowDataType,
pub metadata: Option<PlSmallStr>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnionType {
pub fields: Vec<Field>,
pub ids: Option<Vec<i32>>,
pub mode: UnionMode,
}

/// Mode of [`ArrowDataType::Union`]
Expand Down Expand Up @@ -277,10 +289,10 @@ impl ArrowDataType {
FixedSizeList(_, _) => PhysicalType::FixedSizeList,
LargeList(_) => PhysicalType::LargeList,
Struct(_) => PhysicalType::Struct,
Union(_, _, _) => PhysicalType::Union,
Union(_) => PhysicalType::Union,
Map(_, _) => PhysicalType::Map,
Dictionary(key, _, _) => PhysicalType::Dictionary(*key),
Extension(_, key, _) => key.to_physical_type(),
Extension(ext) => ext.inner.to_physical_type(),
Unknown => unimplemented!(),
}
}
Expand Down Expand Up @@ -322,9 +334,9 @@ impl ArrowDataType {
.collect(),
),
Dictionary(keys, _, _) => (*keys).into(),
Union(_, _, _) => unimplemented!(),
Union(_) => unimplemented!(),
Map(_, _) => unimplemented!(),
Extension(_, inner, _) => inner.underlying_physical_type(),
Extension(ext) => ext.inner.underlying_physical_type(),
_ => self.clone(),
}
}
Expand All @@ -335,7 +347,7 @@ impl ArrowDataType {
pub fn to_logical_type(&self) -> &ArrowDataType {
use ArrowDataType::*;
match self {
Extension(_, key, _) => key.to_logical_type(),
Extension(ext) => ext.inner.to_logical_type(),
_ => self,
}
}
Expand All @@ -358,10 +370,10 @@ impl ArrowDataType {
| D::LargeList(_)
| D::FixedSizeList(_, _)
| D::Struct(_)
| D::Union(_, _, _)
| D::Union(_)
| D::Map(_, _)
| D::Dictionary(_, _, _)
| D::Extension(_, _, _)
| D::Extension(_)
)
}

Expand Down Expand Up @@ -439,11 +451,10 @@ impl ArrowDataType {
| D::FixedSizeList(field, _)
| D::Map(field, _)
| D::LargeList(field) => field.dtype().contains_dictionary(),
D::Struct(fields) | D::Union(fields, _, _) => {
fields.iter().any(|f| f.dtype().contains_dictionary())
},
D::Struct(fields) => fields.iter().any(|f| f.dtype().contains_dictionary()),
D::Union(union) => union.fields.iter().any(|f| f.dtype().contains_dictionary()),
D::Dictionary(_, _, _) => true,
D::Extension(_, dtype, _) => dtype.contains_dictionary(),
D::Extension(ext) => ext.inner.contains_dictionary(),
}
}
}
Expand Down
65 changes: 39 additions & 26 deletions crates/polars-arrow/src/ffi/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use polars_utils::pl_str::PlSmallStr;

use super::ArrowSchema;
use crate::datatypes::{
ArrowDataType, Extension, Field, IntegerType, IntervalUnit, Metadata, TimeUnit, UnionMode,
ArrowDataType, Extension, ExtensionType, Field, IntegerType, IntervalUnit, Metadata, TimeUnit,
UnionMode, UnionType,
};

#[allow(dead_code)]
Expand Down Expand Up @@ -50,11 +51,16 @@ fn schema_children(dtype: &ArrowDataType, flags: &mut i64) -> Box<[*mut ArrowSch
*flags += (*is_sorted as i64) * 4;
Box::new([Box::into_raw(Box::new(ArrowSchema::new(field.as_ref())))])
},
ArrowDataType::Struct(fields) | ArrowDataType::Union(fields, _, _) => fields
ArrowDataType::Struct(fields) => fields
.iter()
.map(|field| Box::into_raw(Box::new(ArrowSchema::new(field))))
.collect::<Box<[_]>>(),
ArrowDataType::Extension(_, inner, _) => schema_children(inner, flags),
ArrowDataType::Union(u) => u
.fields
.iter()
.map(|field| Box::into_raw(Box::new(ArrowSchema::new(field))))
.collect::<Box<[_]>>(),
ArrowDataType::Extension(ext) => schema_children(&ext.inner, flags),
_ => Box::new([]),
}
}
Expand Down Expand Up @@ -86,13 +92,12 @@ impl ArrowSchema {
.map(|inner| (**inner).clone())
.unwrap_or_default();

let metadata = if let ArrowDataType::Extension(name, _, extension_metadata) = field.dtype()
{
let metadata = if let ArrowDataType::Extension(ext) = field.dtype() {
// append extension information.
let mut metadata = metadata.clone();

// metadata
if let Some(extension_metadata) = extension_metadata {
if let Some(extension_metadata) = &ext.metadata {
metadata.insert(
PlSmallStr::from_static("ARROW:extension:metadata"),
extension_metadata.clone(),
Expand All @@ -101,7 +106,7 @@ impl ArrowSchema {

metadata.insert(
PlSmallStr::from_static("ARROW:extension:name"),
name.clone(),
ext.name.clone(),
);

Some(metadata_to_bytes(&metadata))
Expand Down Expand Up @@ -218,7 +223,11 @@ pub(crate) unsafe fn to_field(schema: &ArrowSchema) -> PolarsResult<Field> {
let (metadata, extension) = unsafe { metadata_from_bytes(schema.metadata) };

let dtype = if let Some((name, extension_metadata)) = extension {
ArrowDataType::Extension(name, Box::new(dtype), extension_metadata)
ArrowDataType::Extension(Box::new(ExtensionType {
name,
inner: dtype,
metadata: extension_metadata,
}))
} else {
dtype
};
Expand Down Expand Up @@ -404,7 +413,11 @@ unsafe fn to_dtype(schema: &ArrowSchema) -> PolarsResult<ArrowDataType> {
let fields = (0..schema.n_children as usize)
.map(|x| to_field(schema.child(x)))
.collect::<PolarsResult<Vec<_>>>()?;
ArrowDataType::Union(fields, Some(type_ids), mode)
ArrowDataType::Union(Box::new(UnionType {
fields,
ids: Some(type_ids),
mode,
}))
},
_ => {
polars_bail!(ComputeError:
Expand Down Expand Up @@ -481,22 +494,22 @@ fn to_format(dtype: &ArrowDataType) -> String {
ArrowDataType::Struct(_) => "+s".to_string(),
ArrowDataType::FixedSizeBinary(size) => format!("w:{size}"),
ArrowDataType::FixedSizeList(_, size) => format!("+w:{size}"),
ArrowDataType::Union(f, ids, mode) => {
let sparsness = if mode.is_sparse() { 's' } else { 'd' };
ArrowDataType::Union(u) => {
let sparsness = if u.mode.is_sparse() { 's' } else { 'd' };
let mut r = format!("+u{sparsness}:");
let ids = if let Some(ids) = ids {
let ids = if let Some(ids) = &u.ids {
ids.iter()
.fold(String::new(), |a, b| a + b.to_string().as_str() + ",")
} else {
(0..f.len()).fold(String::new(), |a, b| a + b.to_string().as_str() + ",")
(0..u.fields.len()).fold(String::new(), |a, b| a + b.to_string().as_str() + ",")
};
let ids = &ids[..ids.len() - 1]; // take away last ","
r.push_str(ids);
r
},
ArrowDataType::Map(_, _) => "+m".to_string(),
ArrowDataType::Dictionary(index, _, _) => to_format(&(*index).into()),
ArrowDataType::Extension(_, inner, _) => to_format(inner.as_ref()),
ArrowDataType::Extension(ext) => to_format(&ext.inner),
ArrowDataType::Unknown => unimplemented!(),
}
}
Expand All @@ -508,8 +521,8 @@ pub(super) fn get_child(dtype: &ArrowDataType, index: usize) -> PolarsResult<Arr
(0, ArrowDataType::LargeList(field)) => Ok(field.dtype().clone()),
(0, ArrowDataType::Map(field, _)) => Ok(field.dtype().clone()),
(index, ArrowDataType::Struct(fields)) => Ok(fields[index].dtype().clone()),
(index, ArrowDataType::Union(fields, _, _)) => Ok(fields[index].dtype().clone()),
(index, ArrowDataType::Extension(_, subtype, _)) => get_child(subtype, index),
(index, ArrowDataType::Union(u)) => Ok(u.fields[index].dtype().clone()),
(index, ArrowDataType::Extension(ext)) => get_child(&ext.inner, index),
(child, dtype) => polars_bail!(ComputeError:
"Requested child {child} to type {dtype:?} that has no such child",
),
Expand Down Expand Up @@ -642,8 +655,8 @@ mod tests {
)),
true,
),
ArrowDataType::Union(
vec![
ArrowDataType::Union(Box::new(UnionType {
fields: vec![
Field::new(PlSmallStr::from_static("a"), ArrowDataType::Int64, true),
Field::new(
PlSmallStr::from_static("b"),
Expand All @@ -655,11 +668,11 @@ mod tests {
true,
),
],
Some(vec![1, 2]),
UnionMode::Dense,
),
ArrowDataType::Union(
vec![
ids: Some(vec![1, 2]),
mode: UnionMode::Dense,
})),
ArrowDataType::Union(Box::new(UnionType {
fields: vec![
Field::new(PlSmallStr::from_static("a"), ArrowDataType::Int64, true),
Field::new(
PlSmallStr::from_static("b"),
Expand All @@ -671,9 +684,9 @@ mod tests {
true,
),
],
Some(vec![0, 1]),
UnionMode::Sparse,
),
ids: Some(vec![0, 1]),
mode: UnionMode::Sparse,
})),
];
for time_unit in [
TimeUnit::Second,
Expand Down
6 changes: 5 additions & 1 deletion crates/polars-arrow/src/io/avro/read/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ fn schema_to_field(
.iter()
.map(|s| schema_to_field(s, None, Metadata::default()))
.collect::<PolarsResult<Vec<Field>>>()?;
ArrowDataType::Union(fields, None, UnionMode::Dense)
ArrowDataType::Union(Box::new(UnionType {
fields,
ids: None,
mode: UnionMode::Dense,
}))
}
},
AvroSchema::Record(Record { fields, .. }) => {
Expand Down
10 changes: 5 additions & 5 deletions crates/polars-arrow/src/io/ipc/read/array/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ use super::super::deserialize::{read, skip};
use super::super::read_basic::*;
use super::super::{Compression, Dictionaries, IpcBuffer, Node, Version};
use crate::array::UnionArray;
use crate::datatypes::ArrowDataType;
use crate::datatypes::UnionMode::Dense;
use crate::datatypes::{ArrowDataType, UnionMode};
use crate::io::ipc::read::array::{try_get_array_length, try_get_field_node};

#[allow(clippy::too_many_arguments)]
Expand Down Expand Up @@ -48,8 +47,8 @@ pub fn read_union<R: Read + Seek>(
scratch,
)?;

let offsets = if let ArrowDataType::Union(_, _, mode) = dtype {
if !mode.is_sparse() {
let offsets = if let ArrowDataType::Union(u) = &dtype {
if !u.mode.is_sparse() {
Some(read_buffer(
buffers,
length,
Expand Down Expand Up @@ -108,7 +107,8 @@ pub fn skip_union(
let _ = buffers
.pop_front()
.ok_or_else(|| polars_err!(oos = "IPC: missing validity buffer."))?;
if let ArrowDataType::Union(_, _, Dense) = dtype {
if let ArrowDataType::Union(u) = dtype {
assert!(u.mode == UnionMode::Dense);
let _ = buffers
.pop_front()
.ok_or_else(|| polars_err!(oos = "IPC: missing offsets buffer."))?;
Expand Down
10 changes: 9 additions & 1 deletion crates/polars-arrow/src/io/ipc/read/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,22 @@ fn find_first_dict_field_d<'a>(
List(field) | LargeList(field) | FixedSizeList(field, ..) | Map(field, ..) => {
find_first_dict_field(id, field.as_ref(), &ipc_field.fields[0])
},
Union(fields, ..) | Struct(fields) => {
Struct(fields) => {
for (field, ipc_field) in fields.iter().zip(ipc_field.fields.iter()) {
if let Some(f) = find_first_dict_field(id, field, ipc_field) {
return Some(f);
}
}
None
},
Union(u) => {
for (field, ipc_field) in u.fields.iter().zip(ipc_field.fields.iter()) {
if let Some(f) = find_first_dict_field(id, field, ipc_field) {
return Some(f);
}
}
None
},
_ => None,
}
}
Expand Down
Loading
Loading