alamb commented on code in PR #27047:
URL: https://github.com/apache/datafusion/pull/27047#discussion_r4731474853
##########
benchmarks/sql_benchmarks/README.md:
##########
@@ -20,6 +20,7 @@ in the community:
| `clickbench` | ClickBench benchmark
|
| `clickbench extended` | 12 additional, more complex queries against the
Clickbench dataset |
| `clickbench_sorted` | ClickBench benchmark using a pre-sorted hits file.
|
+| `first_last_orderings`| Grouped `first_value` (Q01) and `DISTINCT ON` (Q03)
ordered by a time zone aware timestamp, and the same queries over the same
instants without a time zone (Q02, Q04), from
[#27046](https://github.com/apache/datafusion/issues/27046). Each pair should
take about the same time at any `--partitions`. Q05 and Q06 order by (int, int)
and (string, int). Size the inline table with `FIRST_LAST_ROWS` (default
`2000000`, two rows per group). |
Review Comment:
Thank you for adding benchmarks
Can we pleas slim this descirption down to just what they test, like
> Grouped `first_value` (Q01) and `DISTINCT ON` queries
Then move the details / issue link to comments in the benchmark scripts
itself?
Also, can you please add the benchmark in a separate PR (that we can merge
first and then we can use our benchmark bot to verify the results)?
##########
datafusion/functions-aggregate/src/first_last.rs:
##########
@@ -493,107 +480,93 @@ impl<S: ValueState> FirstLastGroupsAccumulator<S> {
})
}
- fn should_update_state(
- &self,
- group_idx: usize,
- new_ordering_values: &[ScalarValue],
- ) -> Result<bool> {
- if !self.is_sets.get_bit(group_idx) {
- return Ok(true);
- }
-
- debug_assert_eq!(new_ordering_values.len(), self.ordering_req.len());
- let current_ordering = &self.orderings[group_idx];
- compare_rows(current_ordering, new_ordering_values,
&self.sort_options).map(|x| {
- if self.pick_first_in_group {
- x.is_gt()
- } else {
- x.is_lt()
- }
- })
- }
-
- fn take_orderings(&mut self, emit_to: EmitTo) -> Vec<Vec<ScalarValue>> {
- let result = emit_to.take_needed(&mut self.orderings);
-
- match emit_to {
- EmitTo::All => self.size_of_orderings = 0,
- EmitTo::First(_) => {
- self.size_of_orderings -=
- result.iter().map(ScalarValue::size_of_vec).sum::<usize>()
- }
- }
-
- result
- }
-
fn resize_states(&mut self, new_size: usize) {
self.state.resize(new_size);
-
- if self.orderings.len() < new_size {
- let current_len = self.orderings.len();
-
- self.orderings
- .resize(new_size, self.default_orderings.clone());
-
- self.size_of_orderings += (new_size - current_len)
- * ScalarValue::size_of_vec(
- // Note: In some cases (such as in the unit test below)
- // ScalarValue::size_of_vec(&self.default_orderings) !=
ScalarValue::size_of_vec(&self.default_orderings.clone())
- // This may be caused by the different vec.capacity()
values?
- self.orderings.last().unwrap(),
- );
- }
-
+ self.orderings.resize(new_size);
self.is_sets.resize(new_size);
self.extreme_of_each_group_buf.0.resize(new_size, 0);
self.extreme_of_each_group_buf.1.resize(new_size);
}
- fn update_state(
+ /// Makes each batch row of `winners` (`(group_idx, idx_in_batch)`, at most
+ /// one per group) the group's winner when it beats the stored one
(strictly,
+ /// so ties keep the stored winner), or always when `replace`.
+ fn update_winners(
&mut self,
- group_idx: usize,
- orderings: &[ScalarValue],
- array: &ArrayRef,
- idx: usize,
+ ordering_cols: &[ArrayRef],
+ vals: &ArrayRef,
+ winners: &[(usize, usize)],
+ replace: bool,
) -> Result<()> {
- self.state.update(group_idx, array, idx)?;
- self.is_sets.set_bit(group_idx, true);
-
- debug_assert_eq!(orderings.len(), self.ordering_req.len());
- let old_size = ScalarValue::size_of_vec(&self.orderings[group_idx]);
- self.orderings[group_idx].clear();
- self.orderings[group_idx].extend_from_slice(orderings);
- let new_size = ScalarValue::size_of_vec(&self.orderings[group_idx]);
- self.size_of_orderings = self.size_of_orderings - old_size + new_size;
+ if winners.is_empty() {
+ return Ok(());
+ }
+ let pick_first = self.pick_first_in_group;
+ let beats = |current_vs_new: std::cmp::Ordering| {
+ if pick_first {
+ current_vs_new.is_gt()
+ } else {
+ current_vs_new.is_lt()
+ }
+ };
+ match &mut self.orderings {
+ GroupOrderings::Rows(r) => {
Review Comment:
Maybe this would be better as a method on `GroupOrderings` as it is
modifying internal state of GroupOrderings (takes `&mut self...`)
##########
benchmarks/sql_benchmarks/README.md:
##########
Review Comment:
Nothing this PR did but these descriptions are just 🤮
##########
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:
We could do better with a Vec<u8> and Vec<offsets>, though then you would
have to potentially compact the results for variable sized rows
##########
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.
Review Comment:
> or does not decode back to the planned type.
What is an example of something that doesn't decode back to the planned type?
##########
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.
Review Comment:
I thought that row encoding was always supposed to be the same
A bit of digging suggests that there is already some discrepancy in
ScalarValue comparsion between nested lists and nulls or something. We can deal
with that in a follow on PR if necessary
##########
datafusion/functions-aggregate/src/first_last.rs:
##########
@@ -760,19 +733,14 @@ impl<S: ValueState> FirstLastGroupsAccumulator<S> {
self.extreme_of_each_group_buf.0[group_idx] = idx_in_val;
}
- let mut ordering_buf = Vec::with_capacity(self.ordering_req.len());
- // Take the buffer to appease the borrow checker; `update_state`
+ // Take the buffer to appease the borrow checker; `update_winners`
// needs `&mut self`.
let touched = std::mem::take(&mut self.touched_groups_buf);
- for &group_idx in &touched {
- let idx = self.extreme_of_each_group_buf.0[group_idx];
- extract_row_at_idx_to_buf(
- &values_and_order_cols[1..],
- idx,
- &mut ordering_buf,
- )?;
- self.update_state(group_idx, &ordering_buf, vals, idx)?;
- }
+ let winners: Vec<(usize, usize)> = touched
+ .iter()
+ .map(|&g| (g, self.extreme_of_each_group_buf.0[g]))
+ .collect();
+ self.update_winners(&values_and_order_cols[1..], vals, &winners,
true)?;
Review Comment:
nit: I would find the `true` argument here easier to read if it were a self
describing enum, like `Update::Always`
So something like
```rust
self.update_winners(&values_and_order_cols[1..], vals, &winners,
Update::Always)?;
```
--
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]