From ec345fc3d64e2e34f985d87efb029af1d9adbdfb Mon Sep 17 00:00:00 2001 From: warrenzhu25 Date: Wed, 2 Dec 2026 01:08:39 +0000 Subject: [PATCH] fix(physical-plan): compact List spill chunks when values are not shared across groups --- .../src/spill/spilled_row_sizes.rs | 235 +++++++++++++++++- .../test_files/aggregate_memory_spill.slt | 42 ++++ 2 files changed, 265 insertions(+), 12 deletions(-) diff --git a/datafusion/physical-plan/src/spill/spilled_row_sizes.rs b/datafusion/physical-plan/src/spill/spilled_row_sizes.rs index fe9fc03d1c6c9..3dd8a679d2af3 100644 --- a/datafusion/physical-plan/src/spill/spilled_row_sizes.rs +++ b/datafusion/physical-plan/src/spill/spilled_row_sizes.rs @@ -8,7 +8,7 @@ use arrow::array::{ AnyDictionaryArray, Array, ArrayRef, AsArray, RecordBatch, downcast_integer_array, make_array, }; -use arrow::buffer::{OffsetBuffer, ScalarBuffer}; +use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; use arrow::datatypes::{ArrowNativeType, DataType}; use arrow_data::MAX_INLINE_VIEW_LEN; @@ -112,6 +112,10 @@ enum ColumnSize { /// the key is null. Only dictionaries that are compacted are sized this /// way, the others take the bytes of their keys only. Dictionary(usize, ArrayRef, Box), + /// Per-row byte sizes for a compacted list of dictionary values, counting + /// each row's offset, keys, and each distinct dictionary value referenced + /// by that row once. + CompactedListDictionary(Vec), } impl ColumnSize { @@ -127,20 +131,46 @@ impl ColumnSize { DataType::BinaryView => Self::Views(array.as_binary_view().views().clone()), DataType::List(_) => { let list = array.as_list::(); - Self::List(list.offsets().into(), Box::new(Self::new(list.values()))) + list_column_size( + list.offsets().into(), + list.len(), + list.nulls(), + list.values().as_ref(), + ) } DataType::LargeList(_) => { let list = array.as_list::(); - Self::List(list.offsets().into(), Box::new(Self::new(list.values()))) + list_column_size( + list.offsets().into(), + list.len(), + list.nulls(), + list.values().as_ref(), + ) } DataType::Map(_, _) => { let map = array.as_map(); Self::List(map.offsets().into(), Box::new(Self::new(map.entries()))) } - DataType::FixedSizeList(_, size) => Self::FixedSizeList( - *size as usize, - Box::new(Self::new(array.as_fixed_size_list().values())), - ), + DataType::FixedSizeList(_, size) => { + let list = array.as_fixed_size_list(); + let size = *size as usize; + if matches!(list.values().data_type(), DataType::Dictionary(_, _)) { + let dictionary = list.values().as_any_dictionary(); + let base = list.offset() * size; + list_dictionary_column_size( + 0, + list.len(), + list.nulls(), + |row| (base + row * size, base + (row + 1) * size), + dictionary, + ) + .unwrap_or_else(|key_width| { + Self::FixedSizeList(size, Box::new(Self::Fixed(key_width))) + }) + } else { + Self::FixedSizeList(size, Box::new(Self::new(list.values()))) + } + } DataType::Struct(_) => Self::Struct( array .as_struct() @@ -175,7 +205,7 @@ impl ColumnSize { /// Returns whether this column has a dictionary that is compacted. fn compacted(&self) -> bool { match self { - Self::Dictionary(_, _, _) => true, + Self::Dictionary(_, _, _) | Self::CompactedListDictionary(_) => true, Self::List(_, values) | Self::FixedSizeList(_, values) => values.compacted(), Self::Struct(fields) => fields.iter().any(Self::compacted), Self::Fixed(_) | Self::Bytes(_) | Self::Views(_) => false, @@ -191,7 +221,8 @@ impl ColumnSize { Self::Bytes(_) | Self::Views(_) | Self::List(_, _) - | Self::Dictionary(_, _, _) => None, + | Self::Dictionary(_, _, _) + | Self::CompactedListDictionary(_) => None, } } @@ -214,6 +245,9 @@ impl ColumnSize { .iter() .fold(0, |bytes, field| bytes.saturating_add(field.max_row())), Self::Dictionary(width, _, values) => width.saturating_add(values.max_row()), + Self::CompactedListDictionary(per_row) => { + per_row.iter().copied().max().unwrap_or_default() + } } } @@ -247,10 +281,95 @@ impl ColumnSize { ); num_rows * width + value_bytes } + Self::CompactedListDictionary(per_row) => per_row[start..end].iter().sum(), } } } +fn list_column_size( + offsets: Offsets, + len: usize, + nulls: Option<&NullBuffer>, + values: &dyn Array, +) -> ColumnSize { + if matches!(values.data_type(), DataType::Dictionary(_, _)) { + let dictionary = values.as_any_dictionary(); + list_dictionary_column_size( + offsets.width(), + len, + nulls, + |row| (offsets.get(row), offsets.get(row + 1)), + dictionary, + ) + .unwrap_or_else(|key_width| { + ColumnSize::List(offsets, Box::new(ColumnSize::Fixed(key_width))) + }) + } else { + ColumnSize::List(offsets, Box::new(ColumnSize::new(values))) + } +} + +/// Decides whether a list of dictionary values should be compacted by counting +/// how many list rows reference each dictionary value on average, rather than +/// total keys per value. Values that repeat within one group but are not shared +/// across groups have fewer than two referencing rows per value and are +/// compacted; values shared across many groups stay shared. +/// +/// Returns `Ok(ColumnSize::CompactedListDictionary)` when compacting, or +/// `Err(key_width)` when keeping the dictionary shared. +fn list_dictionary_column_size( + offset_width: usize, + num_rows: usize, + nulls: Option<&NullBuffer>, + range: impl Fn(usize) -> (usize, usize), + dictionary: &dyn AnyDictionaryArray, +) -> Result { + let key_width = match dictionary.data_type() { + DataType::Dictionary(key, _) => key.primitive_width().unwrap_or_default(), + _ => unreachable!(), + }; + let num_values = dictionary.values().len(); + if num_values == 0 || num_rows == 0 || num_rows >= u32::MAX as usize { + return Err(key_width); + } + + let keys = dictionary.keys(); + let values_size = ColumnSize::new(dictionary.values().as_ref()); + let max_refs = 2usize.saturating_mul(num_values); + let mut last_seen = vec![u32::MAX; num_values]; + let mut row_value_refs = 0usize; + let mut per_row = Vec::with_capacity(num_rows); + downcast_integer_array!( + keys => { + for row in 0..num_rows { + let (start, end) = range(row); + let mut bytes = offset_width + (end - start) * key_width; + if nulls.is_some_and(|n| n.is_null(row)) { + per_row.push(bytes); + continue; + } + let tag = row as u32; + for idx in start..end { + if keys.is_valid(idx) { + let v = keys.value(idx).as_usize(); + if last_seen[v] != tag { + last_seen[v] = tag; + row_value_refs += 1; + if row_value_refs >= max_refs { + return Err(key_width); + } + bytes += values_size.rows(v, v + 1); + } + } + } + per_row.push(bytes); + } + }, + data_type => unreachable!("dictionary keys of type {data_type}") + ); + Ok(ColumnSize::CompactedListDictionary(per_row)) +} + /// Returns whether to compact the batches of `dictionary`, which is when fewer /// than two keys reference each of its values on average (see /// [`SpilledRowSizes::compacted_columns`]). @@ -500,16 +619,108 @@ mod tests { Arc::new(values), None, )); - // An offset, plus a key, an offset and the bytes of the value of each - // element. The bound takes two elements of the largest size. + // An offset, plus a key, an offset and the bytes of each distinct value + // referenced by the row. The bound is the largest row. assert_eq!( row_sizes(vec![Arc::clone(&list)]), - (vec![4 + 28 + 13, 4 + 38, 4], 4 + 2 * 38) + (vec![4 + 28 + 13, 4 + 38, 4], 4 + 28 + 13) ); let sizes = SpilledRowSizes::new(&batch(vec![list])); assert_eq!(sizes.compacted_columns(), [0]); } + #[test] + fn nested_dictionary_repeated_within_group_is_compacted() { + // Each dictionary value repeats 4 times within its own list row, but no + // two rows share a value (1 referencing row per value < 2). It must be + // compacted, and each row counts its distinct dictionary value once. + let values = DictionaryArray::new( + Int32Array::from(vec![0, 0, 0, 0, 1, 1, 1, 1]), + Arc::new(StringArray::from(vec!["a".repeat(20), "b".repeat(30)])), + ); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new_list_field(values.data_type().clone(), true)), + OffsetBuffer::new(vec![0, 4, 8].into()), + Arc::new(values), + None, + )); + let row0 = 4 + 4 * 4 + (4 + 20); + let row1 = 4 + 4 * 4 + (4 + 30); + assert_eq!(row_sizes(vec![Arc::clone(&list)]), (vec![row0, row1], row1)); + let sizes = SpilledRowSizes::new(&batch(vec![list])); + assert_eq!(sizes.compacted_columns(), [0]); + } + + #[test] + fn nested_dictionary_shared_across_groups_stays_shared() { + // Two rows both reference every value (2 referencing rows per value), so + // the dictionary stays shared and rows count only list offsets and keys. + let values = DictionaryArray::new( + Int32Array::from(vec![0, 1, 0, 1]), + Arc::new(StringArray::from(vec!["a".repeat(20), "b".repeat(30)])), + ); + let list: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new_list_field(values.data_type().clone(), true)), + OffsetBuffer::new(vec![0, 2, 4].into()), + Arc::new(values), + None, + )); + assert_eq!( + row_sizes(vec![Arc::clone(&list)]), + (vec![4 + 2 * 4, 4 + 2 * 4], 4 + 2 * 4) + ); + let sizes = SpilledRowSizes::new(&batch(vec![list])); + assert!(sizes.compacted_columns().is_empty()); + } + + #[test] + fn sliced_and_nullable_nested_dictionaries() { + // Sliced List with a null list row and a null dictionary key. + let values = DictionaryArray::new( + Int32Array::from(vec![Some(0), None, Some(1), Some(1)]), + Arc::new(StringArray::from(vec!["a".repeat(10), "b".repeat(25)])), + ); + let list = ListArray::new( + Arc::new(Field::new_list_field(values.data_type().clone(), true)), + OffsetBuffer::new(vec![0, 2, 2, 4].into()), + Arc::new(values), + Some(NullBuffer::from(vec![true, false, true])), + ); + let sliced: ArrayRef = Arc::new(list.slice(1, 2)); + let row_null = 4; + let row_val = 4 + 2 * 4 + (4 + 25); + assert_eq!( + row_sizes(vec![Arc::clone(&sliced)]), + (vec![row_null, row_val], row_val) + ); + assert_eq!( + SpilledRowSizes::new(&batch(vec![sliced])).compacted_columns(), + [0] + ); + + // Sliced FixedSizeList: offset must shift into the child dictionary. + let fsl_values = DictionaryArray::new( + Int32Array::from(vec![0, 0, 1, 1]), + Arc::new(StringArray::from(vec!["x".repeat(5), "y".repeat(40)])), + ); + let fsl = arrow::array::FixedSizeListArray::new( + Arc::new(Field::new_list_field(fsl_values.data_type().clone(), true)), + 2, + Arc::new(fsl_values), + None, + ); + let sliced_fsl: ArrayRef = Arc::new(fsl.slice(1, 1)); + let expected = 2 * 4 + (4 + 40); + assert_eq!( + row_sizes(vec![Arc::clone(&sliced_fsl)]), + (vec![expected], expected) + ); + assert_eq!( + SpilledRowSizes::new(&batch(vec![sliced_fsl])).compacted_columns(), + [0] + ); + } + #[test] fn empty_nested_dictionaries_count_nothing() { // The values of null lists are an empty dictionary, without values diff --git a/datafusion/sqllogictest/test_files/aggregate_memory_spill.slt b/datafusion/sqllogictest/test_files/aggregate_memory_spill.slt index e8b9cdae130e8..87f1d34aa0ec9 100644 --- a/datafusion/sqllogictest/test_files/aggregate_memory_spill.slt +++ b/datafusion/sqllogictest/test_files/aggregate_memory_spill.slt @@ -596,6 +596,48 @@ FROM ( 04)------AggregateExec: mode=Single, gby=[__common_expr_1@0 % 32 as t.v / Int64(50) % Int64(32)], aggr=[], metrics=[spilled_bytes= MB, spilled_rows=] 05)--------ProjectionExec: +# Each dictionary value repeats 10 times within one group, with no sharing across +# groups. Spilled chunks must still compact the dictionary so replay fits in 24M. +statement ok +SET datafusion.runtime.memory_limit = '24M' + +query II +SELECT count(*), sum(n) +FROM ( + SELECT (v / 10) % 32 AS k, cardinality(array_agg(arrow_cast(concat(CAST(v / 10 AS VARCHAR), repeat('x', 1000)), 'Dictionary(Int32, Utf8)'))) AS n + FROM generate_series(1, 500000) AS t(v) + GROUP BY (v / 10) % 32 +) +---- +32 500000 + +# Assert spill happened, the `spilled_bytes` metric must be in MB +query TT +EXPLAIN ANALYZE +SELECT count(*), sum(n) +FROM ( + SELECT (v / 10) % 32 AS k, cardinality(array_agg(arrow_cast(concat(CAST(v / 10 AS VARCHAR), repeat('x', 1000)), 'Dictionary(Int32, Utf8)'))) AS n + FROM generate_series(1, 500000) AS t(v) + GROUP BY (v / 10) % 32 +) +---- + +04)------AggregateExec: mode=Single, gby=[__common_expr_1@0 % 32 as t.v / Int64(10) % Int64(32)], aggr=[], metrics=[spilled_bytes= MB, spilled_rows=] +05)--------ProjectionExec: + +statement ok +SET datafusion.execution.target_partitions = 2 + +query II +SELECT count(*), sum(n) +FROM ( + SELECT (v / 10) % 32 AS k, cardinality(array_agg(arrow_cast(concat(CAST(v / 10 AS VARCHAR), repeat('x', 1000)), 'Dictionary(Int32, Utf8)'))) AS n + FROM generate_series(1, 500000) AS t(v) + GROUP BY (v / 10) % 32 +) +---- +32 500000 + # Restore settings to slt runner defaults statement ok RESET datafusion.runtime.memory_limit