kosiew commented on code in PR #27047:
URL: https://github.com/apache/datafusion/pull/27047#discussion_r4719456641
##########
datafusion/functions-aggregate/src/first_last.rs:
##########
@@ -930,6 +858,433 @@ impl<S: ValueState + 'static> GroupsAccumulator for
FirstLastGroupsAccumulator<S
}
}
+/// The ordering values of each group's winner.
+enum GroupOrderings {
+ /// Arrow row format: comparing two orderings is a byte comparison and no
+ /// [`ScalarValue`] is built per group.
+ Rows(OrderingRows),
+ /// [`ScalarValue`]s compared with `compare_rows`, for ordering types whose
+ /// row encoding does not order like `compare_rows` (nested and union
+ /// types) or does not decode back to the planned type.
+ Scalars(ScalarOrderings),
+}
+
+/// Whether the arrow row encoding of `t` orders exactly like
+/// `compare_rows` over [`ScalarValue`]s: flat types, and dictionaries of them.
+fn row_comparable(t: &DataType) -> bool {
+ use DataType::*;
+ match t {
+ Boolean | Utf8 | LargeUtf8 | Utf8View | Binary | LargeBinary |
BinaryView
+ | FixedSizeBinary(_) => true,
+ Dictionary(_, v) => !matches!(v.as_ref(), Dictionary(_, _)) &&
row_comparable(v),
+ t => t.is_primitive(),
+ }
+}
+
+impl GroupOrderings {
+ fn try_new(dtypes: &[DataType], sort_options: &[SortOptions]) ->
Result<Self> {
+ if dtypes.iter().all(row_comparable)
+ && let Some(rows) = OrderingRows::try_new(dtypes, sort_options)?
+ {
+ return Ok(Self::Rows(rows));
+ }
+ Ok(Self::Scalars(ScalarOrderings::try_new(
+ dtypes,
+ sort_options,
+ )?))
+ }
+
+ fn resize(&mut self, n: usize) {
+ match self {
+ Self::Rows(r) => r.resize(n),
+ Self::Scalars(s) => s.resize(n),
+ }
+ }
+
+ fn take(&mut self, emit_to: EmitTo, decode: bool) -> Result<Vec<ArrayRef>>
{
+ match self {
+ Self::Rows(r) => r.take(emit_to, decode),
+ Self::Scalars(s) => s.take(emit_to, decode),
+ }
+ }
+
+ fn size(&self) -> usize {
+ match self {
+ Self::Rows(r) => r.size(),
+ Self::Scalars(s) => s.size(),
+ }
+ }
+
+ /// Releases capacity the stored groups do not need, such as the rows
+ /// of groups emitted with [`EmitTo::First`].
+ fn shrink_to_fit(&mut self) {
+ match self {
+ Self::Rows(r) => r.shrink_to_fit(),
+ Self::Scalars(s) => s.rows.shrink_to_fit(),
+ }
+ }
+
+ /// `size` recomputed from scratch (tests).
+ #[cfg(test)]
+ fn compute_size(&self) -> usize {
+ match self {
+ Self::Rows(r) => r.compute_size(),
+ Self::Scalars(s) => s.compute_size(),
+ }
+ }
+}
+
+struct ScalarOrderings {
+ rows: Vec<Vec<ScalarValue>>,
+ /// Typed nulls, the orderings of groups without a winner.
+ default: Vec<ScalarValue>,
+ sort_options: Vec<SortOptions>,
+ /// Cached `ScalarValue::size_of_vec` sum over `rows` (costly to
recompute),
+ /// including each row's `Vec` header.
+ heap: usize,
+}
+
+impl ScalarOrderings {
+ fn try_new(dtypes: &[DataType], sort_options: &[SortOptions]) ->
Result<Self> {
+ Ok(Self {
+ rows: Vec::new(),
+ default: dtypes
+ .iter()
+ .map(ScalarValue::try_from)
+ .collect::<Result<_>>()?,
+ sort_options: sort_options.to_vec(),
+ heap: 0,
+ })
+ }
+
+ fn resize(&mut self, n: usize) {
+ let len = self.rows.len();
+ if n > len {
+ self.rows.resize(n, self.default.clone());
+ // Measured on a stored copy: a clone's capacity can differ from
+ // `default`'s.
+ self.heap += (n - len) * ScalarValue::size_of_vec(&self.rows[n -
1]);
+ }
+ }
+
+ fn set(&mut self, group_idx: usize, ordering: &[ScalarValue]) {
+ let row = &mut self.rows[group_idx];
+ let old = ScalarValue::size_of_vec(row);
+ row.clear();
+ row.extend_from_slice(ordering);
+ self.heap = self.heap - old + ScalarValue::size_of_vec(row);
+ }
+
+ fn take(&mut self, emit_to: EmitTo, decode: bool) -> Result<Vec<ArrayRef>>
{
+ let taken = emit_to.take_needed(&mut self.rows);
+ // `size_of_vec` is costly (nested values), so it is not summed over
+ // the taken rows when nothing is left.
+ match emit_to {
+ EmitTo::All => self.heap = 0,
+ EmitTo::First(_) => {
+ self.heap -=
taken.iter().map(ScalarValue::size_of_vec).sum::<usize>()
+ }
+ }
+ if !decode {
+ return Ok(Vec::new());
+ }
+ let mut cols: Vec<Vec<ScalarValue>> = (0..self.default.len())
+ .map(|_| Vec::with_capacity(taken.len()))
+ .collect();
+ for row in taken {
+ for (col, v) in cols.iter_mut().zip(row) {
+ col.push(v);
+ }
+ }
+ cols.into_iter().map(ScalarValue::iter_to_array).collect()
+ }
+
+ /// `heap` already counts the `Vec` header of each stored row, so only the
+ /// spare capacity of `rows` is added.
+ fn size(&self) -> usize {
+ self.spare_headers() + self.heap
+ }
+
+ fn spare_headers(&self) -> usize {
+ (self.rows.capacity() - self.rows.len()) *
size_of::<Vec<ScalarValue>>()
+ }
+
+ #[cfg(test)]
+ fn compute_size(&self) -> usize {
+ self.spare_headers()
+ + self
+ .rows
+ .iter()
+ .map(ScalarValue::size_of_vec)
+ .sum::<usize>()
+ }
+}
+
+/// Orderings in the arrow row format.
+struct OrderingRows {
+ converter: RowConverter,
+ /// Ordering types as planned; decoding hydrates dictionaries, which are
+ /// cast back so the state schema does not change.
+ dtypes: Vec<DataType>,
+ /// Encoding of all-null orderings, stored for groups without a winner.
+ null_row: Vec<u8>,
+ storage: RowStorage,
+}
+
+enum RowStorage {
+ /// Every encoded row has the same width (fixed-width ordering types):
+ /// the rows lie back to back.
+ Fixed { width: usize, data: Vec<u8> },
+ /// One reusable buffer per group; `heap` is the sum of their capacities.
+ Var { rows: Vec<Vec<u8>>, heap: usize },
+}
+
+impl OrderingRows {
+ /// `None` when the encoding does not decode back to `dtypes` (for example
+ /// a dictionary whose values cannot be packed again by `cast`).
+ fn try_new(
+ dtypes: &[DataType],
+ sort_options: &[SortOptions],
+ ) -> Result<Option<Self>> {
+ let fields: Vec<SortField> = dtypes
+ .iter()
+ .zip(sort_options)
+ .map(|(t, o)| SortField::new_with_options(t.clone(), *o))
+ .collect();
+ if !RowConverter::supports_fields(&fields) {
+ return Ok(None);
+ }
+ let converter = RowConverter::new(fields)?;
+ let nulls: Vec<ArrayRef> = dtypes.iter().map(|t| new_null_array(t,
1)).collect();
+ let null_row =
converter.convert_columns(&nulls)?.row(0).as_ref().to_vec();
+ let fixed = dtypes
+ .iter()
+ .all(|t| t.is_primitive() || matches!(t, DataType::Boolean));
+ let storage = if fixed {
+ RowStorage::Fixed {
+ width: null_row.len(),
+ data: Vec::new(),
+ }
+ } else {
+ RowStorage::Var {
+ rows: Vec::new(),
+ heap: 0,
+ }
+ };
+ let rows = Self {
+ converter,
+ dtypes: dtypes.to_vec(),
+ null_row,
+ storage,
+ };
+ // Probe the round trip once, so `state` cannot fail on a type later.
+ if rows
+ .decode(std::iter::once(rows.null_row.as_slice()))
+ .is_err()
+ {
+ return Ok(None);
+ }
+ Ok(Some(rows))
+ }
+
+ fn len(&self) -> usize {
+ match &self.storage {
+ RowStorage::Fixed { width, data } => data.len() / width,
+ RowStorage::Var { rows, .. } => rows.len(),
+ }
+ }
+
+ fn resize(&mut self, n: usize) {
+ let len = self.len();
+ if n <= len {
+ return;
+ }
+ match &mut self.storage {
+ RowStorage::Fixed { data, .. } => {
+ for _ in len..n {
+ data.extend_from_slice(&self.null_row);
+ }
+ }
+ RowStorage::Var { rows, heap } => {
+ rows.resize_with(n, || self.null_row.clone());
+ *heap += (n - len) * self.null_row.len();
+ }
+ }
+ }
+
+ fn get(&self, group_idx: usize) -> &[u8] {
+ match &self.storage {
+ RowStorage::Fixed { width, data } => {
+ &data[group_idx * width..(group_idx + 1) * width]
+ }
+ RowStorage::Var { rows, .. } => &rows[group_idx],
+ }
+ }
+
+ fn set(&mut self, group_idx: usize, row: &[u8]) -> Result<()> {
+ match &mut self.storage {
+ RowStorage::Fixed { width, data } => {
+ if row.len() != *width {
+ return internal_err!(
+ "FIRST_VALUE/LAST_VALUE: ordering row of {} bytes,
expected {width}",
+ row.len()
+ );
+ }
+ data[group_idx * *width..(group_idx + 1) *
*width].copy_from_slice(row);
+ }
+ RowStorage::Var { rows, heap } => {
+ let buf = &mut rows[group_idx];
+ let old = buf.capacity();
+ buf.clear();
+ buf.extend_from_slice(row);
+ *heap = *heap - old + buf.capacity();
+ }
+ }
+ Ok(())
+ }
+
+ /// Encodes the orderings of the rows `winners[..].1` of a batch.
+ fn encode(
+ &self,
+ ordering_cols: &[ArrayRef],
+ winners: &[(usize, usize)],
+ ) -> Result<arrow::row::Rows> {
+ let indices = UInt64Array::from_iter_values(winners.iter().map(|w| w.1
as u64));
+ let cols = ordering_cols
+ .iter()
+ .map(|c| {
+ compact_sparse_dictionary(compute::take(c.as_ref(), &indices,
None)?)
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(self.converter.convert_columns(&cols)?)
+ }
+
+ /// Decodes encoded rows, one array per ORDER BY expression.
+ fn decode<'a>(&self, rows: impl Iterator<Item = &'a [u8]>) ->
Result<Vec<ArrayRef>> {
+ decode_rows(&self.converter, &self.dtypes, rows)
+ }
+
+ /// Removes the emitted groups; decodes their orderings when `decode`.
+ fn take(&mut self, emit_to: EmitTo, decode: bool) -> Result<Vec<ArrayRef>>
{
+ let n = match emit_to {
+ EmitTo::All => self.len(),
+ EmitTo::First(n) => n,
+ };
+ let self_len = self.len();
+ let (converter, dtypes) = (&self.converter, &self.dtypes);
+ let mut out = Vec::new();
+ match &mut self.storage {
+ RowStorage::Fixed { width, data } => {
+ let w = *width;
+ if decode {
+ out = decode_rows(converter, dtypes, data[..n *
w].chunks_exact(w))?;
+ }
+ match emit_to {
+ EmitTo::All => *data = Vec::new(),
+ // Like `EmitTo::take_needed`: when most rows are emitted,
+ // copy the kept rows into a buffer of their size, so the
+ // emitted rows' memory is released; otherwise shift them
+ // down in place.
+ EmitTo::First(_) if n * 2 > self_len => {
+ *data = data[n * w..].to_vec();
+ }
+ EmitTo::First(_) => {
+ data.drain(..n * w);
+ }
+ }
+ }
+ RowStorage::Var { rows, heap } => {
+ let taken = emit_to.take_needed(rows);
+ *heap -= taken.iter().map(Vec::capacity).sum::<usize>();
+ if decode {
+ out =
+ decode_rows(converter, dtypes,
taken.iter().map(Vec::as_slice))?;
+ }
+ }
+ }
+ Ok(out)
+ }
+
+ /// Releases the capacity of emitted groups' rows and of variable-width
+ /// rows that once held a longer winner.
+ fn shrink_to_fit(&mut self) {
+ match &mut self.storage {
+ RowStorage::Fixed { data, .. } => data.shrink_to_fit(),
+ RowStorage::Var { rows, heap } => {
+ rows.shrink_to_fit();
+ rows.iter_mut().for_each(Vec::shrink_to_fit);
+ *heap = rows.iter().map(Vec::capacity).sum();
+ }
+ }
+ }
+
+ fn size(&self) -> usize {
+ self.converter.size()
+ + self.null_row.capacity()
+ + self.dtypes.capacity() * size_of::<DataType>()
+ + match &self.storage {
+ RowStorage::Fixed { data, .. } => data.capacity(),
+ RowStorage::Var { rows, heap } => {
+ rows.capacity() * size_of::<Vec<u8>>() + heap
+ }
+ }
+ }
+
+ /// `size` recomputed from scratch (tests).
+ #[cfg(test)]
+ fn compute_size(&self) -> usize {
+ self.converter.size()
+ + self.null_row.capacity()
+ + self.dtypes.capacity() * size_of::<DataType>()
+ + match &self.storage {
+ RowStorage::Fixed { data, .. } => data.capacity(),
+ RowStorage::Var { rows, .. } => {
+ rows.capacity() * size_of::<Vec<u8>>()
+ + rows.iter().map(Vec::capacity).sum::<usize>()
+ }
+ }
+ }
+}
+
+/// `take` keeps the whole values array of a dictionary, and the row converter
+/// encodes all of them, so a batch whose dictionary is much larger than its
+/// few winners is reduced to the values the winners reference first.
+fn compact_sparse_dictionary(array: ArrayRef) -> Result<ArrayRef> {
+ let Some(dictionary) = array.as_any_dictionary_opt() else {
+ return Ok(array);
+ };
+ if dictionary.values().len() <= MAX_DICTIONARY_VALUES_PER_ROW *
array.len() {
+ return Ok(array);
+ }
+ let array = array.as_ref();
+ downcast_dictionary_array! {
+ array => Ok(Arc::new(compact_dictionary(array)?)),
+ t => internal_err!("expected a dictionary array, got {t}"),
+ }
+}
+
+/// Decodes rows of `converter`, casting each column back to its planned type
+/// (decoding hydrates dictionaries).
+fn decode_rows<'a>(
+ converter: &RowConverter,
+ dtypes: &[DataType],
+ rows: impl Iterator<Item = &'a [u8]>,
+) -> Result<Vec<ArrayRef>> {
+ let parser = converter.parser();
+ let arrays = converter.convert_rows(rows.map(|r| parser.parse(r)))?;
+ arrays
+ .into_iter()
Review Comment:
The Arrow decoder fails for both view types above i32::MAX non-inline bytes,
before hash aggregation slices the emitted state.
Please exclude views, including dictionary-wrapped views, from row storage
and test the fallback, or implement bounded decoding with multi-buffer support.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]