Skip to content

[Data] Combine aggregated blocks column-wise instead of folding row by row - #66194

Merged
goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
AarryaSaraf:data-combine-aggregated-columnwise
Sep 16, 2026
Merged

goutamvenkat-anyscale merged 3 commits into
ray-project:masterfrom
AarryaSaraf:data-combine-aggregated-columnwise

Conversation

@AarryaSaraf

Copy link
Copy Markdown
Contributor

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:

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:

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

@AarryaSaraf
AarryaSaraf marked this pull request as ready for review September 15, 2026 23:56
@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner September 15, 2026 23:56
@AarryaSaraf AarryaSaraf added go add ONLY when ready to merge, run all tests data Ray Data-related issues labels Sep 15, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +579 to +591
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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)

Comment on lines +1164 to +1165
def aggregate_block(self, block: Block) -> AggType:
accessor = BlockColumnAccessor.for_column(block[self._target_col_name])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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])

Comment on lines +1287 to 1288
def aggregate_block(self, block: Block) -> AggType:
column = self._compute_unique(block)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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)

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit f78c275. Configure here.

yield tuple(), self.to_block()
return
if self.num_rows() == 0:
return self._empty_table()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

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]>
Comment thread python/ray/data/aggregate.py Resolved
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit e4836c1 into ray-project:master Sep 16, 2026
6 checks passed
goutamvenkat-anyscale pushed a commit that referenced this pull request Sep 18, 2026
…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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants