Repository navigation
[Data] Combine aggregated blocks column-wise instead of folding row by row - #66194
Conversation
…y row Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces VectorizedAggregateFnV2 to support fully vectorized aggregations, refactoring several aggregation classes (such as Count, Sum, Min, Max, Quantile, and Unique) to utilize vectorized column combinations. Additionally, the aggregation and combination logic in table_block.py has been updated to leverage these vectorized operations. Feedback on the changes highlights a bug in the collision resolution logic (_resolve_aggregated_column_names) when handling more than two duplicate aggregation names, as well as opportunities to add defensive checks in Quantile and Unique aggregations to prevent cryptic errors when the target column name is missing.
| name_counts: Dict[str, int] = collections.defaultdict(int) | ||
|
|
||
| resolved_agg_names: List[str] = [] | ||
|
|
||
| for agg in aggs: | ||
| name = agg.name | ||
| # Check for conflicts with existing aggregation | ||
| # name. | ||
| if name in name_counts: | ||
| name = TableBlockAccessor._munge_conflict(name, name_counts[name]) | ||
|
|
||
| name_counts[name] += 1 | ||
| resolved_agg_names.append(name) |
There was a problem hiding this comment.
There is a bug in the collision resolution logic when there are more than two aggregations with the same name. For example, if aggs has names ['a', 'a', 'a'], the first resolves to 'a', the second to 'a_2', and the third also to 'a_2' because name_counts['a'] remains 1 and is not incremented for the original name. This leads to duplicate column names and potential data overwriting. We should use a while loop to ensure uniqueness and correctly increment the counts of the original names.
| name_counts: Dict[str, int] = collections.defaultdict(int) | |
| resolved_agg_names: List[str] = [] | |
| for agg in aggs: | |
| name = agg.name | |
| # Check for conflicts with existing aggregation | |
| # name. | |
| if name in name_counts: | |
| name = TableBlockAccessor._munge_conflict(name, name_counts[name]) | |
| name_counts[name] += 1 | |
| resolved_agg_names.append(name) | |
| name_counts: Dict[str, int] = collections.defaultdict(int) | |
| resolved_agg_names: List[str] = [] | |
| for agg in aggs: | |
| original_name = agg.name | |
| name = original_name | |
| while name in name_counts: | |
| name = TableBlockAccessor._munge_conflict(original_name, name_counts[original_name]) | |
| name_counts[original_name] += 1 | |
| name_counts[name] += 1 | |
| resolved_agg_names.append(name) |
| def aggregate_block(self, block: Block) -> AggType: | ||
| accessor = BlockColumnAccessor.for_column(block[self._target_col_name]) |
There was a problem hiding this comment.
If on is not provided to Quantile, self._target_col_name will be None. Accessing block[None] will raise a cryptic KeyError or TypeError at runtime. Adding a defensive check here ensures a clear and helpful error message is raised.
| def aggregate_block(self, block: Block) -> AggType: | |
| accessor = BlockColumnAccessor.for_column(block[self._target_col_name]) | |
| def aggregate_block(self, block: Block) -> AggType: | |
| if self._target_col_name is None: | |
| raise ValueError("Column to aggregate on has to be provided for Quantile.") | |
| accessor = BlockColumnAccessor.for_column(block[self._target_col_name]) |
| def aggregate_block(self, block: Block) -> AggType: | ||
| column = self._compute_unique(block) |
There was a problem hiding this comment.
If on is not provided to Unique, self._target_col_name will be None. This will cause _compute_unique to fail with a cryptic error when accessing block[None]. Adding a defensive check here ensures a clear and helpful error message is raised.
| def aggregate_block(self, block: Block) -> AggType: | |
| column = self._compute_unique(block) | |
| def aggregate_block(self, block: Block) -> AggType: | |
| if self._target_col_name is None: | |
| raise ValueError("Column to aggregate on has to be provided for Unique.") | |
| column = self._compute_unique(block) |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit f78c275. Configure here.
| yield tuple(), self.to_block() | ||
| return | ||
| if self.num_rows() == 0: | ||
| return self._empty_table() |
There was a problem hiding this comment.
Empty global aggregation drops result row
Medium Severity
_aggregate now returns an empty table for any zero-row block, including global aggregations (no group key). _iter_groups_sorted still treats the whole block as one group so an empty input used to emit a single identity row. _combine_aggregated_blocks then drops those empty partials and returns another empty table, so ds.aggregate(Count()) on an empty dataset becomes None instead of {count(): 0}.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit f78c275. Configure here.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
…names (#66218) ## Why Two bugs in `TableBlockAccessor`'s aggregation path, both visible from the public API. **A global aggregation over an empty dataset returns `None`.** ```python ray.data.range(10).filter(lambda row: False).aggregate(Count()) # before: None # after: {'count()': 0} ``` #66194 added an early return for zero-row blocks. That is right for a keyed aggregation — no rows means no groups — but a global aggregation always has exactly one group, and still owes its identity row. Counting an empty dataset is `0`, not "no answer". **Repeated aggregations overwrite each other's results.** ```python ray.data.range(4).aggregate(Sum("id"), Sum("id"), Sum("id")) # before: {'sum(id)': 6, 'sum(id)_2': 6} # after: {'sum(id)': 6, 'sum(id)_2': 6, 'sum(id)_3': 6} ``` `_resolve_aggregated_column_names` suffixes duplicate names, but incremented the counter for the *suffixed* name rather than the original. The original's count never advanced past one, so every duplicate after the first resolved to `_2` again. Because `_aggregate` builds rows with `row[name] = accumulator`, two aggregations sharing a name means one result is silently dropped. ## What changes - The empty-block early return in `_aggregate` is gated on there being group keys, and the `num_rows() > 0` check around `accumulate_block` is restored, so an empty group leaves the accumulators at their identity values. - `_resolve_aggregated_column_names` counts the original name and suffixes until the name is free. Looping rather than suffixing once also covers a generated suffix colliding with an aggregation explicitly named that, as in `["a", "a_2", "a"]`. It now takes the names rather than the aggregations, since that is all it reads. - `GPUAggregationPlan` carried its own copy of that loop, which resolved names differently from the CPU path — the same query returned different column names depending on the shuffle strategy. It now calls the shared helper. - Tests for both bugs in `test_dataset_aggregrations.py`. The name-collision bug predates #66194 — it dates to #20044 and survived #46668 and #50498; #66194 only lifted the loop into a helper, which is why `git blame` points there. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…y row (ray-project#66194) ## Why In a `groupby`, each map task partially aggregates its block and a reduce task merges those partials. The merge currently walks the partial blocks row by row, folding accumulators one pair at a time with a Python-level `combine()` call. With many groups that's hundreds of thousands of Python calls just to add numbers together, and it dominates the reduce step. ## What changes Take `ds.groupby("group").sum("value")` with two map tasks. Each emits a partially aggregated, sorted block: ``` block 1 block 2 group sum(value) group sum(value) a 3 a 5 b 7 b 2 ``` Before, the reduce step merged these by folding accumulators pairwise in Python, one call per group per extra block: ```python Sum.combine(3, 5) # group a Sum.combine(7, 2) # group b ``` Now it concatenates the blocks once, slices out each group, and merges the whole accumulator column in a single Arrow kernel: ```python pyarrow.compute.sum([3, 5]) # group a pyarrow.compute.sum([7, 2]) # group b ``` With `G` groups and `B` partial blocks, that replaces `G × (B-1)` Python calls with `G` Arrow calls — so the gap widens as either grows. Concretely: - `_combine_aggregated_blocks` concatenates and sorts the partials once, then hands each aggregation a whole accumulator column per group. - `Count`, `Sum`, `Min`, `Max`, `AbsMax`, `AsList`, `Quantile` and `Unique` gain a `_combine_column` implementing that merge. - Anything without one — `Mean`, `Std`, `CountDistinct`, and all user-defined aggregations — keeps the existing row-wise fold, so behaviour is unchanged. - The map-side `_aggregate` is rewritten the same way, over the existing `_iter_groups_sorted` helper. ## Numbers Block-level benchmark, 4 aggregations (`Count`, `Sum`, `Min`, `Max`), 8 partial blocks, best of 5: | rows | groups | merge before | merge after | speedup | |---:|---:|---:|---:|---:| | 1M | 10 | 1.31 ms | 0.36 ms | 3.6x | | 1M | 1,000 | 123.1 ms | 21.3 ms | **5.8x** | | 1M | 100,000 | 8,886 ms | 2,075 ms | **4.3x** | | 100k | 100,000 | 1,650 ms | 1,328 ms | 1.2x | The map-side `_aggregate` is 1.0–1.2x. Output is identical to the current implementation in all four configurations. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…names (ray-project#66218) ## Why Two bugs in `TableBlockAccessor`'s aggregation path, both visible from the public API. **A global aggregation over an empty dataset returns `None`.** ```python ray.data.range(10).filter(lambda row: False).aggregate(Count()) # before: None # after: {'count()': 0} ``` ray-project#66194 added an early return for zero-row blocks. That is right for a keyed aggregation — no rows means no groups — but a global aggregation always has exactly one group, and still owes its identity row. Counting an empty dataset is `0`, not "no answer". **Repeated aggregations overwrite each other's results.** ```python ray.data.range(4).aggregate(Sum("id"), Sum("id"), Sum("id")) # before: {'sum(id)': 6, 'sum(id)_2': 6} # after: {'sum(id)': 6, 'sum(id)_2': 6, 'sum(id)_3': 6} ``` `_resolve_aggregated_column_names` suffixes duplicate names, but incremented the counter for the *suffixed* name rather than the original. The original's count never advanced past one, so every duplicate after the first resolved to `_2` again. Because `_aggregate` builds rows with `row[name] = accumulator`, two aggregations sharing a name means one result is silently dropped. ## What changes - The empty-block early return in `_aggregate` is gated on there being group keys, and the `num_rows() > 0` check around `accumulate_block` is restored, so an empty group leaves the accumulators at their identity values. - `_resolve_aggregated_column_names` counts the original name and suffixes until the name is free. Looping rather than suffixing once also covers a generated suffix colliding with an aggregation explicitly named that, as in `["a", "a_2", "a"]`. It now takes the names rather than the aggregations, since that is all it reads. - `GPUAggregationPlan` carried its own copy of that loop, which resolved names differently from the CPU path — the same query returned different column names depending on the shuffle strategy. It now calls the shared helper. - Tests for both bugs in `test_dataset_aggregrations.py`. The name-collision bug predates ray-project#66194 — it dates to ray-project#20044 and survived ray-project#46668 and ray-project#50498; ray-project#66194 only lifted the loop into a helper, which is why `git blame` points there. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>


Why
In a
groupby, each map task partially aggregates its block and a reduce task merges those partials. The merge currently walks the partial blocks row by row, folding accumulators one pair at a time with a Python-levelcombine()call. With many groups that's hundreds of thousands of Python calls just to add numbers together, and it dominates the reduce step.What changes
Take
ds.groupby("group").sum("value")with two map tasks. Each emits a partially aggregated, sorted block:Before, the reduce step merged these by folding accumulators pairwise in Python, one call per group per extra block:
Now it concatenates the blocks once, slices out each group, and merges the whole accumulator column in a single Arrow kernel:
With
Ggroups andBpartial blocks, that replacesG × (B-1)Python calls withGArrow calls — so the gap widens as either grows.Concretely:
_combine_aggregated_blocksconcatenates and sorts the partials once, then hands each aggregation a whole accumulator column per group.Count,Sum,Min,Max,AbsMax,AsList,QuantileandUniquegain a_combine_columnimplementing that merge.Mean,Std,CountDistinct, and all user-defined aggregations — keeps the existing row-wise fold, so behaviour is unchanged._aggregateis rewritten the same way, over the existing_iter_groups_sortedhelper.Numbers
Block-level benchmark, 4 aggregations (
Count,Sum,Min,Max), 8 partial blocks, best of 5:The map-side
_aggregateis 1.0–1.2x. Output is identical to the current implementation in all four configurations.🤖 Generated with Claude Code