Skip to content

[Data] Adaptively skip map-side partial aggregation for high-cardinality keys - #68118

Merged
sampan-s-nayak merged 7 commits into
ray-project:masterfrom
sampan-s-nayak:data-3654-adaptive-partial-agg
Nov 19, 2026
Merged

sampan-s-nayak merged 7 commits into
ray-project:masterfrom
sampan-s-nayak:data-3654-adaptive-partial-agg

Conversation

@sampan-s-nayak

@sampan-s-nayak sampan-s-nayak commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Closes #67270.

Under SHUFFLE_V2, every map task builds partial aggregates by hashing on the group keys. When keys are nearly unique (e.g. groupby("order_id")), this backfires:

  • The map task builds a hash table about as big as its input, which can OOM.
  • The shuffle gets bigger, not smaller. For example, Mean turns 1 value into sum + count.
  • The reducer then runs a second full group-by.

This PR lets each map task decide whether partial aggregation is worth it. The approach is the same one DataFusion, Velox and Trino use (probe about 100k rows, threshold 0.8).

Map side (hash_aggregate_v2.py)

  • A planner-chosen PartialAggPolicy has three modes: ALWAYS (today's behavior), NEVER, and PROBE.
  • In PROBE mode, the map task groups the first probe_rows rows by key only. If groups / rows > unique_ratio_threshold, it ships raw rows, pruned to the key and target columns, instead of partial state.

Reduce side

  • Shards are told apart by the presence of the __agg0_* column.
  • A new optional ArrowAggSpec.raw_to_partial projects each raw row into its single-row partial state. It is column-wise pyarrow.compute with no hashing, and is implemented for Sum, Count, Min, Max, Mean, MissingValuePercentage and ZeroPercentage.
  • Raw and partial shards are then merged in one group_by. A high-cardinality query therefore does one hash pass instead of two.
  • If any spec has no raw_to_partial, the reducer falls back to _aggregate_raw_rows, which is still correct.

Planning (plan_all_to_all_op.py)

  • _choose_partial_agg_policy resolves the policy from DataContext.

Config (DataContext, on by default)

Setting Default
enable_adaptive_partial_aggregation True
partial_aggregation_mode None, which means "probe". "always" or "never" forces that mode for every map task.
adaptive_partial_aggregation_probe_rows 100_000
adaptive_partial_aggregation_unique_ratio_threshold 0.8

Not changed

  • The Python fallback aggregation path (used when a query includes Std, Quantile, AbsMax, AsList, ValueCounter, the approximate aggregations, or a custom AggregateFn). Its accumulators have no per-row raw-to-partial projection, so skipping would move the work to the reducer rather than remove it.
  • Collection aggregations (Unique, CountDistinct) and shuffle elimination.

The feature is on by default. Map blocks under probe_rows (100k) are never probed and keep today's behavior. The release benchmark below shows a clear win at high cardinality and no change at low cardinality. To turn it off, set RAY_DATA_ENABLE_ADAPTIVE_PARTIAL_AGGREGATION=0.

Benchmark

These are the aggregate_groups_* release tests: groupby_benchmark.py --sf 1000 --aggregate --shuffle-strategy shuffle_v2 --num-partitions 500, which runs mean(l_extendedprice) over TPC-H lineitem SF1000 (~6B rows). Each variant ran once, in release build 115235. The release-test variants are on a separate branch, data-3654-adaptive-partial-agg-release-test, and are not part of this PR.

Workload Without adaptive partial aggregation With adaptive partial aggregation Change
High cardinality (7M groups), object store 53.3 s (job) 43.5 s (job) −18.4%
High cardinality (7M groups), disk 52.9 s (job) 44.2 s (job) −16.4%
Low cardinality (84 groups), object store 25.8 s (job) 25.3 s (job) −1.9% (noise)
Low cardinality (84 groups), disk 24.3 s (job) 23.7 s (job) −2.2% (noise)

The speed-up is in the map stage. About 30 s into the high-cardinality runs, 26 of 154 map tasks had finished without the feature, against 92 of 156 with it. The reduce stage took about the same time in both. No run spilled.

Not a duplicate

#67270 has no other open PR. I searched open PRs for "partial aggregation" and found nothing overlapping. #67130 (disk shuffle map refactor) only touches the same planner call site.

Testing

New tests in test_hash_shuffle_v2.py (16, all passing):

  • Probe decisions: high cardinality, low cardinality, small blocks, and the forced modes.
  • Reduce over mixed raw/partial shards: 13 aggs including ignore_nulls variants, with nulls, NaN and int32 values, compared against the current two-phase result.
  • Policy selection.
  • End-to-end: use_disk × mode, compared with pandas.
pytest python/ray/data/tests/test_hash_shuffle_v2.py -k partial_agg   # 16 passed
pytest python/ray/data/tests/test_hash_shuffle_v2.py python/ray/data/tests/test_groupby_e2e.py \
       python/ray/data/tests/test_aggregations.py python/ray/data/tests/test_shuffle_elimination.py
       # feature on (default): 867 passed, 1 skipped, 2 timed out (see below)
RAY_DATA_DEFAULT_SHUFFLE_STRATEGY=shuffle_v2 \
pytest python/ray/data/tests/test_groupby_e2e.py python/ray/data/tests/test_aggregations.py
       # feature on (default): 571 passed, 2 timed out (see below)
RAY_DATA_DEFAULT_SHUFFLE_STRATEGY=shuffle_v2 RAY_DATA_PARTIAL_AGGREGATION_MODE=never \
pytest python/ray/data/tests/test_groupby_e2e.py python/ray/data/tests/test_aggregations.py
       # 573 passed (every map task forced to skip)

The 2 timeouts were test_groupby_map_groups_multiple_batch_formats[hash_shuffle-1/30], which uses the legacy HASH_SHUFFLE operator that this PR doesn't touch. Both suites were running at the same time on one machine. Run alone, the test passes with the feature on and off (10 passed each).

AI assistance (Claude Code) was used to write this change; I reviewed it.

🤖 Generated with Claude Code

…ity keys in SHUFFLE_V2

Probe the first N rows of each map block; if the key-unique ratio exceeds a
threshold, ship raw (column-pruned) rows instead of partial state. The reducer
projects raw rows into partial state per row (raw_to_state) and merges
everything in a single group_by. Gated behind
DataContext.enable_adaptive_partial_aggregation (off by default).

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak

Copy link
Copy Markdown
Contributor Author

Release benchmark: aggregate_groups_high_cardinality

release/nightly_tests/dataset/groupby_benchmark.py --sf 1000 --aggregate --group-by column02 column14 --shuffle-strategy shuffle_v2 --num-partitions 500

This is groupby(l_suppkey, l_shipmode).mean(l_extendedprice) over TPC-H lineitem SF1000 (~6B rows, ~7M groups). It uses the existing release-test cluster (fixed_size_all_to_all_compute.yaml). Each variant ran once, in Buildkite release build 115235. The variants with adaptive partial aggregation only add RAY_DATA_ENABLE_ADAPTIVE_PARTIAL_AGGREGATION=1.

Shuffle Without adaptive partial aggregation With adaptive partial aggregation Change
Object store 53.3 s (job) 43.5 s (job) −18.4%
Disk 52.9 s (job) 44.2 s (job) −16.4%

Times are the benchmark's timed groupby section. No run spilled.

…y selection

- Turn enable_adaptive_partial_aggregation on by default (release benchmark:
  ~17% faster on the 7M-group SF1000 groupby, no change at 84 groups).
- Accept partial_aggregation_mode="probe" and honor the configured probe size
  and threshold when it is forced.
- Drop the unused _estimate_key_unique_ratio planning hook.
- Rename ArrowAggSpec.raw_to_state to raw_to_partial.

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak
sampan-s-nayak marked this pull request as ready for review November 13, 2026 06:57
@sampan-s-nayak
sampan-s-nayak requested a review from a team as a code owner November 13, 2026 06:57
@sampan-s-nayak sampan-s-nayak added the go add ONLY when ready to merge, run all tests label Nov 13, 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 adaptive map-side partial aggregation for SHUFFLE_V2 group-by operations in Ray Data, allowing map tasks to skip pre-aggregation when key cardinality is high to save memory and reduce shuffled bytes. It adds configuration options, policy definitions, and logic to probe input rows and convert raw rows directly into partial states on the reducer side. The review feedback suggests importing Union from typing and updating type annotations for raw_to_partial and _count_state to accurately represent that they can handle both pa.Array and pa.ChunkedArray types.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 13, 2026

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

Stale Bugbot comment from a previous run.

Signed-off-by: sampan <[email protected]>

@rayo5o rayo5o 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.

The benchmark covers speed, so I looked at whether the mixed raw/partial reduce gives the same answers. Compared fc23ab3 with the merge base c55def8.

  • Reduce level: 29 input shapes, each split into 3 map outputs, every always/never mix compared with all-always. This covered all 7 vectorized aggs with both ignore_nulls settings, null keys (some rows, a whole shard, a null-typed shard), all-null values, int8/uint8/int16/uint32 keys and values, int32 and int64 shards in the same reduce, NaN, bool, string/large_string/timestamp(tz)/date32 Min/Max, decimal128, two keys, and a query with Std. All matched.
  • End to end on SHUFFLE_V2 (600k rows, unique keys in the first half, 10 keys in the second): probe (the default), always and never give the same frame as the merge base. Std through the Python path matches too.
  • The test commands in the description reproduce with the CI lock versions (pyarrow 25.0.1, pandas 2.3.3): 869 passed / 1 skipped, and 573 passed for both shuffle_v2 runs. No timeouts here. On the merge base, 10 of the 16 new tests fail; the 6 that pass are the e2e ones, which master already gets right.

Not a problem, just something I noticed: the map task concatenates its input batch (up to shuffle_input_batch_bytes, 1 GiB) before the transformer, so the first 100k rows decide for the whole batch. With a 100k-row block of unique keys followed by 5M rows over 10 keys, the map output was 77.8 MiB of raw rows instead of 3.8 MiB of partials. With the small block last it took the partial path. The cost stays within the pruned input size, so it's never worse than never.

Map tasks only ship raw rows when every agg can project them into partial
state, so the reducer no longer needs a two-pass fallback.

Signed-off-by: sampan <[email protected]>
# Never pre-aggregate: ship column-pruned rows, aggregate once on the reducer.
NEVER = "never"
# Decide per map task by counting distinct keys in a subset of its input rows.
PROBE = "probe"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I know that other engine use probe, but I think we can get approximate unique num since we have full block? So we can decide more accurately

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good idea, Ill use Haas–Stokes formula which postgres also uses

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this will slighlty slow down the estimation (probe was much simpler, but this should be more stable)

@owenowenisme owenowenisme Nov 18, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Wait I mean that we have the whole block we can do like:

h = hash(block.select(keys))  
m = max(block.num_rows // 16_384, 1)  # m is how many slices we want, 16384 here means we want ≈ 16k rows in the first slice
kept = h[(h >> (64 - log2(m))) == 0]     # keys that hash into slice 0, with all their rows
d_est = np.unique(kept).size * m
skip = d_est > threshold * block.num_rows

Similar to clickhouse's uniq implementation, this would be more accurate IIUC

@sampan-s-nayak sampan-s-nayak Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

looks like there is no row-hash kernel in arrow so this becomes more expensive to run. I asked claude to try this approach out and it looks like this approach is more accurate but slower. at the end of the day I feel the results will be similar so it might be ok to go with the existing approach

Block True distinct/rows Current Time Key-hash Time
unique 1.000 1.000 24ms 1.004 884ms
1% null + unique 0.990 0.990 29ms 0.990 786ms
10% null + unique 0.900 0.900 24ms 0.895 965ms
25% null + unique 0.750 0.752 25ms 0.753 1024ms
10 keys 0.000 0.000 13ms 0.000 607ms
2 rows per key 0.500 0.496 31ms 0.499 710ms
5 rows per key 0.200 0.205 20ms 0.198 522ms
90% unique + 1000 heavy keys 0.901 0.897 20ms 0.904 775ms
unique head, 10-key tail 0.020 0.020 59ms 0.019 632ms
Zipf 1.3 0.039 0.009 11ms 0.041 341ms
half unique, half ×2 0.750 0.667 30ms 0.749 461ms
string + int keys, unique 1.000 1.000 41ms 1.009 17,146ms

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

when using polars the numbers become more viable but polars is not always guaranteed to be present so I feel it should be ok to stick to current approach. alternative is to support both and current as a fall back but I feel that is overkill. wdyt?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I see, that make sense

Comment thread python/ray/data/context.py Outdated
Comment on lines +179 to +185
DEFAULT_ENABLE_ADAPTIVE_PARTIAL_AGGREGATION = env_bool(
"RAY_DATA_ENABLE_ADAPTIVE_PARTIAL_AGGREGATION", True
)

DEFAULT_PARTIAL_AGGREGATION_MODE = os.environ.get(
"RAY_DATA_PARTIAL_AGGREGATION_MODE", None
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think RAY_DATA_ENABLE_ADAPTIVE_PARTIAL_AGGREGATION is redundant? you have RAY_DATA_PARTIAL_AGGREGATION_MODE already

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

right, removing

…nt partial-agg flag

Map tasks used to decide whether to skip partial aggregation from the
distinct keys in their first probe_rows rows, so a block whose cardinality
changed partway through was judged by its head. They now sample rows across
the whole block and estimate the block's distinct keys with the Haas-Stokes
Duj1 estimator (as Postgres ANALYZE does for n_distinct).

Remove enable_adaptive_partial_aggregation: partial_aggregation_mode now
defaults to "estimate" (renamed from "probe"), and "always" turns
adaptive skipping off. Rename the probe_rows setting to sample_rows.

Signed-off-by: sampan <[email protected]>

@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 ccb62e4. Configure here.

sampan-s-nayak added a commit to sampan-s-nayak/ray that referenced this pull request Nov 18, 2026
…68118

Drop enable_adaptive_partial_aggregation, use the "estimate" mode and
adaptive_partial_aggregation_sample_rows.

Signed-off-by: sampan <[email protected]>

@rayo5o rayo5o 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.

Re-ran my first-round checks on ccb62e4 with the CI lock versions (pyarrow 25.0.1, pandas 2.3.3):

  • Answers are unchanged. The 29 mixed raw/partial reduce inputs match all-always (the two dictionary-key inputs fail under always too, same as before), and end to end estimate, always and never return the same frames as the merge base, Std included. test_hash_shuffle_v2.py: 86 passed.
  • The case from my first review is fixed: 100k unique keys followed by 5M rows over 10 keys now pre-aggregates (3.8 MiB of map output instead of 77.8 MiB of raw rows). 5M unique keys still skip, 12 ms vs 645 ms under always.

One thing left, inline below: the estimate runs low when most keys are unique and a few keys repeat a lot. The count_all clash Cursor flagged also reproduces, as a hard failure; I replied in that thread.

d = len(counts)
f1 = pc.sum(pc.equal(counts, 1)).as_py() or 0
denominator = n - f1 + f1 * n / total
return n * d / denominator

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.

Duj1 comes out low when a few heavy keys sit next to many unique ones, so those blocks now pre-aggregate. The heavy keys' sampled rows make n - f1 large, which pulls the estimate down even though the singletons really are unique.

One int64 key, 5M rows, the default 100k sample, some keys null and the rest unique. Map side only (_make_aggregating_transformer with Sum, Count, Mean), median of 5:

null keys distinct / rows estimate / rows decision map output map time
0% 1.00 1.00 skip 76 MiB 10 ms
1% 0.99 0.65 aggregate 189 MiB 649 ms
5% 0.95 0.27 aggregate 182 MiB 649 ms
10% 0.90 0.15 aggregate 172 MiB 581 ms

Non-null heavy keys do the same: with 1M rows, 90% unique plus 10 or 1000 heavy keys reads as 0.47–0.48. Counting distinct keys in the first 100k rows, as 8c29047 did, gets these right on shuffled input, but it reads "every key twice" as 0.95, which the estimate now gets right (0.50). The new test_estimate_distinct_keys cases all have equal rows per key, where Duj1 is accurate.

One option I tried: count each key seen 3+ times in the sample as one distinct key and apply Duj1 to the remaining rows only (n, d and N scaled down by the heavy rows). Across 12 distributions (equal multiplicities, unique plus heavy keys, Zipf) it landed on the same side of 0.8 as the true ratio every time, "every key twice" included. With a cut of 10 instead of 3 it missed the 1000-heavy-key case.

Answers stay correct either way; a wrong guess costs what always costs today.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good analysis, Ill update to use your solution.

…all name clash

Duj1 ran low when a few heavy keys (e.g. null) sat next to many unique
ones, so those blocks pre-aggregated. Keys seen 3+ times in the sample now
count as one distinct key each, and Duj1 runs on the remaining rows only.

Rename the sampled key columns before grouping, so a key named count_all
no longer collides with the count column.

Signed-off-by: sampan <[email protected]>

@rayo5o rayo5o 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.

Approving on 628e593. Both points from my last round are fixed:

  • Unique IDs with 1–10% null keys now estimate at 0.99–0.90 and skip pre-aggregation (5M rows: 13 ms on the map side vs 786 ms under always). Across 11 key distributions (equal rows per key, unique plus heavy keys, Zipf), the estimate lands on the same side of 0.8 as the true ratio in every case, "every key twice" included.
  • groupby("count_all") on 300k rows works again, for int and string keys.

Answers still match the merge base end to end for estimate, always and never (Std included), the 27 mixed raw/partial reduce inputs match all-always, and test_hash_shuffle_v2.py passes (90). The one premerge failure is a test_with_column timeout, which this PR doesn't touch.

@owenowenisme owenowenisme left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

approve with nit:
Non-blocking but add some validation for the data context vars(sample row & uniq ratio) that you added

Raise a ValueError naming the setting when partial_aggregation_mode is
unknown, adaptive_partial_aggregation_sample_rows isn't a positive integer,
or adaptive_partial_aggregation_unique_ratio_threshold isn't in [0, 1].

Signed-off-by: sampan <[email protected]>
@sampan-s-nayak
sampan-s-nayak merged commit 9d5c32d into ray-project:master Nov 19, 2026
6 checks passed
eugenepaniot added a commit to eugenepaniot/ray that referenced this pull request Nov 19, 2026
…floop-input

* upstream/master:
  [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366)
  [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329)
  [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118)
  [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947)
  [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117)
  [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318)
  [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988)
  [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259)
  [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177)
  [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302)
  [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085)
  [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162)
  [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161)
  [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248)
  [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951)
  [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317)
  [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306)
  [Train] Support post-mortem debugging for training function errors (ray-project#68296)
  [train][1/n] Give each health probe its own timeout (ray-project#68191)
  [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266)
  [Train] Add a guide to debugging failures and hangs (ray-project#68299)
  [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662)
  [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845)
  [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68303)
  [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467)
  [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243)
  [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218)
  [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803)
  [core][sandbox] Remove the readonly option (ray-project#68088)
  [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907)
  [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151)
  [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156)
  [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210)
  [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072)
  [serve][llm] Remove decode load progress (ray-project#68258)
  [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250)
  [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262)
  [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730)
  [serve] Observe the result of rank reassignment reconfigures (ray-project#67923)
  [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243)
  [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061)
  [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595)
  [Train] Remove local mode (ray-project#68239)
  [Data] Fix filtered Lance row-count metadata (ray-project#67228)
  [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437)
  [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079)
  [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242)
  [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888)
  [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542)
  [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004)
  [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171)
  [core] Send generator consumed-progress updates from io_service_ (ray-project#67160)
  [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154)
  [data][llm] Keep the prompt in vLLM error rows (ray-project#67665)
  [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699)
  [Data] Read text files on DataSource v2 (ray-project#68063)
  [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332)
  [Serve] Show progress of updating (ray-project#67107)
  [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009)
  [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175)
  [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788)
  [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974)
  [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816)
  [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68069)
  [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204)
  [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145)
  [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201)
  [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172)
  [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130)
  [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767)
  [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135)
  feat(core): add Cambricon MLU resource support (ray-project#66368)
  [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154)
  [data] Fix Parquet filename suffix detection (ray-project#67156)
  [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927)
  [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149)
  [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691)
  [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925)
  [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924)
  [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167)
  [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620)
  [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838)
  [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937)
  [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590)
  [data] Add Top-N execution (ray-project#66931)
  [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483)
  [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720)
  [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690)
  [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110)
  [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850)
  [core] Deflake tests that race on timing (ray-project#67717)
  [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285)
  [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109)
  [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166)
  [core][sandbox] Commit sandbox as new registry image (ray-project#67972)
  [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930)
  [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915)
  [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879)
  [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519)
  [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856)
  [Train] Do not start an elastic worker group with zero workers (ray-project#68101)
  [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070)
  [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359)
  [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065)
  [core][test] Create auth token in test_redis_wrong_password (ray-project#68014)
  [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698)
  [Data] Fix typing mismatches in Dataset public API (ray-project#62077)
  [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929)
  [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164)
  [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647)
  [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887)
  [Data] Eliminate redundant aggregation shuffle (ray-project#67198)
  [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005)
  [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045)
  [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006)
  [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878)
  [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837)
  [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122)
  [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900)
  [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899)
  [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898)
  [Core] Add initial foundational configurations and flags for fork server (ray-project#67356)
  [core][sandbox] Image layers caching (ray-project#67874)
  [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779)
  [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292)
  [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046)
  [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718)
  [train] Fix checkpoint sorting to support nested metrics (ray-project#59130)
  [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671)
  [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901)
  [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184)
  [core] Deflake `_run_hanging_command` tests (ray-project#67461)
  [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007)
  [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067)
  [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719)
  [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968)
  [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722)
  [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844)
  [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087)
  [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974)
  [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873)
  [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836)
  Add perf metrics for 2.60.0 (ray-project#67727)
  [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958)

Signed-off-by: Eugene Paniot <[email protected]>

# Conflicts:
#	python/ray/data/_internal/planner/plan_udf_map_op.py
richardliaw pushed a commit that referenced this pull request Nov 19, 2026
…que; add raw_to_partial hook (#68202)

> **Stacked on #68118.** Only the commits from `[Data] Vectorize AbsMax,
Std, ...` onward belong to this PR.

## Summary
This PR gives `AbsMax`, `Std`, `AsList`, `Quantile`, `ValueCounter` and
`TopKUnique` Arrow specs with `raw_to_partial`, so they run on the
vectorized SHUFFLE_V2 aggregation engine and support adaptive partial
aggregation (#68118). It also adds a public
`AggregateFnV2.raw_to_partial` hook, so custom aggregations on the
Python engine can opt into adaptive partial aggregation too.

## Before
- These six aggregations had no `ArrowAggSpec`. Any query that used one
of them ran entirely on the Python engine (sort + per-group accumulate),
even if it also used `Mean` or `Sum`.
- The Python engine never skips map-side partial aggregation. At high
cardinality, that is ~25–60× slower than the vectorized engine (numbers
below).
- Custom `AggregateFnV2`s had no way to support adaptive partial
aggregation.

## After
- **AbsMax.** Each shard computes `max(abs(x))` (with `abs_checked`),
and the reducer takes the `max` of those.
- **Std.** Partial state is `(count, mean, var0)`, computed by Arrow's
`count`/`mean`/`variance(ddof=0)`. The reducer merges partials with
Chan's parallel formula `M2 = Σ nᵢ(varᵢ + (μᵢ − μ)²)`, as Spark,
DataFusion and Trino do. This stays numerically stable when |mean| ≫
std.
- **ValueCounter / TopKUnique.** These share a value→count state, as in
Spark's `mode`, stored as parallel `values`/`counts` list columns.
Merging adds the counts per value. TopKUnique ranks the values within
each group.
- **AsList / Quantile.** The partial state is a list per group
(DataFusion's `array_agg`/`percentile_cont`); merging concatenates the
lists. Quantile sorts once in finalize and interpolates linearly. I
tried Spark's value→count state for Quantile first, but on mostly
distinct values (prices) it was 3.5× slower than master at low
cardinality.
- **Group-id sorts** cast ids to the narrowest unsigned type, so numpy
uses radix sort (~12× faster for ≤65535 groups).
- **New `ArrowAggSpec` hooks.**
- `grouped_raw`/`grouped_merge`: per-group numpy math through a per-row
group id. The id comes from adding a `("__ray_row", "list")` aggregation
to the same `group_by`, which keeps null keys consistent.
- `supports_type`: unsupported value types (nested, extension, or
non-numeric for the numeric aggregations) fall back to the Python
engine, so results don't change for those types.
- **`AggregateFnV2.raw_to_partial(block)` (public, optional).** It
returns one accumulator per row. When every aggregation in a
Python-engine query implements it, map tasks may ship raw rows, tagged
with a zero-byte `__ray_raw_rows` column, and the reducer converts them
to partials before combining. If any aggregation doesn't implement it,
the map always pre-aggregates, as before.
- TopKUnique with `encode_lists=True` and keyless (global) aggregations
stay on the Python engine.

**Behavior changes**
- `AbsMax` on an integer column holding `INT_MIN` now raises
(`abs_checked`). Before, Python's `abs` silently produced a value that
no longer fit the column type.
- `Std` now propagates NaN, consistent with vectorized `Mean`. The
Python engine's NaN handling depended on how rows were laid out across
blocks.

```mermaid
flowchart TD
    subgraph Before
        subgraph BS[Subsystem: shuffle / aggregation]
            subgraph BC[Component: hash_aggregate_v2]
                B0{Every agg has ArrowAggSpec?} -->|"no (Std, AbsMax, Quantile, AsList, ValueCounter, TopKUnique, custom)"| B1[Python engine: sort + accumulate, always pre-aggregate]
                B0 -->|yes| B2[Vectorized engine, adaptive skip]
            end
        end
    end
    subgraph After
        subgraph AS[Subsystem: shuffle / aggregation]
            subgraph AC[Component: hash_aggregate_v2]
                A0{Every agg has ArrowAggSpec and supported value type?} -->|yes, now incl. the 6 aggs| A2[Vectorized engine, adaptive skip, grouped_raw / grouped_merge hooks]
                A0 -->|no| A1{Every agg overrides raw_to_partial?}
                A1 -->|yes| A3[Python engine, adaptive skip: raw rows + __ray_raw_rows marker]
                A1 -->|no| A4[Python engine, always pre-aggregate]
            end
        end
    end
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class A1,A3 added
    class A0,A2 changed
```

## Subsystems
Shuffle / aggregation (`aggregate.py`, `_internal/arrow_aggregation.py`,
`hash_aggregate_v2.py`). Also docs (`aggregating-data.md`) and the
groupby release benchmark.

## Why this is not a duplicate
There are no open PRs for vectorizing these aggregations or for a
`raw_to_partial` hook (searched open PRs). This extends #68118, which
added adaptive partial aggregation only for aggregations that already
had Arrow specs.

## Testing
AI assistance (Claude Code) was used to write this change. I reviewed
the diff and ran the tests below locally.

- **New tests in `test_hash_shuffle_v2.py`:**
- vectorized vs Python engine across float/int32/bool/string/dictionary
columns, `ignore_nulls`, low/high cardinality and partial-agg modes
(`always`/`never`/mixed shards);
- AsList parity, NaN semantics (including AbsMax/Max), Std numerical
stability, unsupported types falling back to Python, an all-null block
of an unsupported type, and LargeList partial state;
  - the `raw_to_partial` hook, plus always pre-aggregating without it;
  - an e2e test over `use_disk` × mode compared against pandas.
- **Updated** `test_shuffle_elimination.py`: the new aggregations now
support complete aggregation.
- **Regression run:** `pytest
python/ray/data/tests/{test_groupby_e2e,test_aggregations,test_agg_e2e,test_dataset_aggregrations,test_hash_shuffle_v2,test_shuffle_elimination,test_dataset_stats}.py`
gave 1034 passed, 3 failed.
- Two `test_groupby_map_groups_multiple_batch_formats` timeouts were
from a loaded box. They pass when rerun, and timing over 3 runs matches
the base master commit (103–117s vs 111–122s).
- `test_count` fails because the dashboard/Prometheus metrics endpoint
isn't available in my local env. It doesn't aggregate.
- **Docs example** (`raw_to_partial` on the custom Mean) checked with
mode `never`.
- **Release tests (SF1000 TPC-H `lineitem`, 500 partitions, SHUFFLE_V2),
value column `l_extendedprice`.**
`aggregate_each_agg_{low,high}_cardinality`, each aggregation timed on
its own. Master = base commit `c55def829e` plus the same benchmark
commit.
- Low cardinality: master
[115667](https://buildkite.com/ray-project/release/builds/115667), PR
[115677](https://buildkite.com/ray-project/release/builds/115677).
- High cardinality: master
[115846](https://buildkite.com/ray-project/release/builds/115846) (two
runs: all aggregations with the no-progress watchdog off, and all but
AbsMax/Std with it on), PR
[115848](https://buildkite.com/ray-project/release/builds/115848).

| Aggregation | Low cardinality: master → PR | High cardinality: master
→ PR |
  |---|---|---|
  | absmax | 108.7s → 25.5s (4.3×) | 3640.9s → 46.8s (78×) |
  | std | 94.0s → 19.8s (4.7×) | 6171.4s → 43.9s (141×) |
| quantile | 101.1s → 78.7s (1.3×) | did not finish (no progress for 30
min) → 57.5s |
  | topk_unique | 475.7s → 431.6s (1.1×) | 3390.0s → 49.4s (69×) |
  | value_counter | 1185.4s → 381.0s (3.1×) | 2263.8s → 51.5s (44×) |
  | aslist | — | did not finish (same as quantile) → 52.6s |
| custom (Python engine, `raw_to_partial`) | 94.3s → 93.8s | 2337.6s →
89.5s (26×) |

- On master, high cardinality runs these on the Python engine, which
calls `aggregate_block` once per group, and nearly every row is its own
group. With Ray Data's default 30-minute no-progress watchdog, AbsMax
and Std fail on master; the times above are with it off.
- Low-cardinality `custom` is unchanged, as expected: the map
pre-aggregates either way.
- topk_unique/value_counter stay slow at low cardinality because almost
every price is distinct, so the value→count state barely compresses, and
only a handful of reducers hold each group.
- First PR commit before the Quantile fix
([115668](https://buildkite.com/ray-project/release/builds/115668)):
low-cardinality quantile took 355.8s (the regression the second commit
fixes).
- **Local benchmark** (4M rows, 100 keys, 4 CPUs, Python engine →
vectorized): quantile 7.25s → 4.60s, value_counter 4.88s → 1.60s,
topk_unique 3.53s → 1.77s. At 1M rows/~1M keys every aggregation is
24–62× faster.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: sampan <[email protected]>
elliot-barn added a commit that referenced this pull request Nov 23, 2026
…nto releases/2.61.0 (#68472)

## Description

Cherry-pick of #68433 (`1729626bbb`) onto `releases/2.61.0`. Lets the
upstream read or map fuse into the disk-shuffle writer, and sets the
polars thread limit inside the task rather than through the runtime env.

The pick applied without conflicts. Seven master commits that touch the
same files are not on the release branch (#67143, #68158, #68202 and its
revert #68383, #68319, #67570, #68118), so the picked files differ from
master in five places. Reviewers from Data, please confirm none of those
is a prerequisite.

## Testing

Ran locally against the `releases/2.61.0` wheel (`7c8ca5ea51`) with the
picked files overlaid: `test_hash_shuffle_v2.py`,
`test_operator_fusion.py` and `test_execution_optimizer_advanced.py`,
232 passed, 2 skipped.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: You-Cheng Lin <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: You-Cheng Lin <[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.

[Data] Adaptively skipping partial shuffle when cardinality is high

3 participants