akupchinskiy commented on code in PR #27047:
URL: https://github.com/apache/datafusion/pull/27047#discussion_r4739386421


##########
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.

Review Comment:
   Done in 766e59a4d6, with one change: the rows are in blocks that never 
reallocate rather than one `Vec<u8>`, because growing a single buffer briefly 
holds two copies and raised peak memory by up to 20% at 5M groups. With blocks, 
50M rows / 5M groups take 510 ms and 1.8 GB peak RSS vs 1079 ms and 2.3 GB on 
main.



-- 
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]

Reply via email to