Skip to content

perf: Optimize hashing, null-free fast path for percentile_cont, median - #23954

Merged
neilconway merged 3 commits into
apache:mainfrom
neilconway:neilc/perf-percentile-median
Jul 29, 2026
Merged

perf: Optimize hashing, null-free fast path for percentile_cont, median#23954
neilconway merged 3 commits into
apache:mainfrom
neilconway:neilc/perf-percentile-median

Conversation

@neilconway

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

This PR makes three improvements to non-distinct PercentileContAccumulator and MedianAccumulator, inspired by recent work on percentile_cont(DISTINCT) (#23946):

  1. Switch from SipHash to foldhash for internal hash maps
  2. Add a null-free fast path to update_batch and retract_batch
  3. Raise an error if we attempt to retract an unknown value in retract_batch, rather than silently ignoring it.

Benchmarks:

  percentile_cont no_nulls   window=256    -61.1%  (249.0 -> 96.6 us)
  percentile_cont with_nulls window=256    -59.4%  (232.7 -> 94.5 us)
  percentile_cont no_nulls   window=4096   -50.9%  (756.3 -> 370.4 us)
  percentile_cont with_nulls window=4096   -48.2%  (552.2 -> 286.2 us)
  percentile_cont no_nulls   window=16384  -47.3%  (2.311 -> 1.218 ms)
  percentile_cont with_nulls window=16384  -42.0%  (1.465 -> 0.851 ms)
  median          no_nulls   window=256    -62.8%  (247.0 -> 92.0 us)
  median          with_nulls window=256    -59.8%  (228.8 -> 92.0 us)
  median          no_nulls   window=4096   -40.0%  (411.4 -> 246.6 us)
  median          with_nulls window=4096   -39.4%  (364.4 -> 221.0 us)
  median          no_nulls   window=16384  -31.5%  (1.107 -> 0.759 ms)
  median          with_nulls window=16384  -32.9%  (0.947 -> 0.637 ms)

What changes are included in this PR?

See above.

Are these changes tested?

Yes: existing tests pass, new tests added for the null-free fast path and the improved error handling.

Are there any user-facing changes?

No.

The non-distinct PercentileContAccumulator and MedianAccumulator used
the default SipHash hasher for their internal HashMaps. This is slow;
switching to foldhash is significantly faster.

Also, add a null-free fast path to `update_batch` and `retract_batch`
in both accumulators.

Benchmarks:

  percentile_cont no_nulls   window=256    -61.1%  (249.0 -> 96.6 us)
  percentile_cont with_nulls window=256    -59.4%  (232.7 -> 94.5 us)
  percentile_cont no_nulls   window=4096   -50.9%  (756.3 -> 370.4 us)
  percentile_cont with_nulls window=4096   -48.2%  (552.2 -> 286.2 us)
  percentile_cont no_nulls   window=16384  -47.3%  (2.311 -> 1.218 ms)
  percentile_cont with_nulls window=16384  -42.0%  (1.465 -> 0.851 ms)
  median          no_nulls   window=256    -62.8%  (247.0 -> 92.0 us)
  median          with_nulls window=256    -59.8%  (228.8 -> 92.0 us)
  median          no_nulls   window=4096   -40.0%  (411.4 -> 246.6 us)
  median          with_nulls window=4096   -39.4%  (364.4 -> 221.0 us)
  median          no_nulls   window=16384  -31.5%  (1.107 -> 0.759 ms)
  median          with_nulls window=16384  -32.9%  (0.947 -> 0.637 ms)
If `retract_batch` is asked to remove values the accumulator is not
tracking, its state has diverged from the window frame and continuing
would silently produce wrong results; return an internal error rather
than silently ignoring.
@github-actions github-actions Bot added the functions Changes to functions implementation label Jul 28, 2026
@neilconway

Copy link
Copy Markdown
Contributor Author

cc @viirya

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

LGTM — nice to see the #23946 ideas carried over to the non-distinct accumulators, and the benchmark wins are substantial.

I went through all three changes:

  • foldhash on the to_remove map — matches what we did for the distinct path.
  • null-free fast path: update_batch uses extend_from_slice(values.values()) when there are no nulls, which is correct since null_count() == 0 guarantees every slot in the values buffer is a valid logical value (equivalent to iter().flatten()), and it's the wholesale append that drives the speedup. retract_batch's null-free branch mirrors it.
  • retract error: checking !to_remove.is_empty() after the removal loop is the right adaptation for the non-distinct multiset — any leftover entries are values that were retracted but never present, which is exactly the divergence worth surfacing rather than silently dropping. Consistent with the internal_err! we added on the distinct side.

Test coverage is good: the error-path test and the dense-vs-sparse update_batch equivalence test cover both new branches. LGTM.

@codecov-commenter

codecov-commenter commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.47312% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.75%. Comparing base (b0b9dae) to head (886dbef).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
...afusion/functions-aggregate/src/percentile_cont.rs 89.47% 4 Missing ⚠️
datafusion/functions-aggregate/src/median.rs 94.54% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #23954      +/-   ##
==========================================
+ Coverage   80.69%   80.75%   +0.05%     
==========================================
  Files        1095     1096       +1     
  Lines      372529   373511     +982     
  Branches   372529   373511     +982     
==========================================
+ Hits       300626   301627    +1001     
+ Misses      53942    53895      -47     
- Partials    17961    17989      +28     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@neilconway
neilconway added this pull request to the merge queue Jul 29, 2026
Merged via the queue into apache:main with commit 043d97f Jul 29, 2026
37 checks passed
@neilconway
neilconway deleted the neilc/perf-percentile-median branch July 29, 2026 14:15
naman-modi pushed a commit to naman-modi/datafusion that referenced this pull request Jul 29, 2026
…pache#23956)

## Which issue does this PR close?

- Closes apache#23955.

## Rationale for this change

`PrimitiveDistinctCountAccumulator::update_batch` does a per-element
validity check on every row even when the array has no nulls. Its own
`merge_batch` already inserts wholesale from the values buffer, so the
same fast path applies to `update_batch`. Inspired by the null-free fast
paths added to `percentile_cont`/`median` in apache#23954.

## What changes are included in this PR?

- When `null_count() == 0`, insert directly from the values buffer
(`self.values.extend(arr.values().iter().copied())`) instead of the
per-element `Option` check.
- Unit test asserting the fast and general paths agree (a dense array
and a null-containing array with the same non-null values yield the same
distinct count).

## Benchmarks

`count_distinct` benchmark, null-free 8192-row batches:

```
count_distinct i64 80% distinct   -67.0%  (54.9 -> 18.1 us)
count_distinct i64 99% distinct   -66.0%  (54.9 -> 18.7 us)
count_distinct u32 80% distinct   -66.9%  (53.9 -> 17.8 us)
count_distinct u32 99% distinct   -65.3%  (53.3 -> 18.5 us)
count_distinct i32 80% distinct   -66.9%  (54.1 -> 17.9 us)
count_distinct i32 99% distinct   -66.2%  (53.2 -> 18.0 us)
```

The bitmap-backed cases (u8/i8/u16/i16) and the grouped-accumulator
cases don't use this path and are unchanged, as expected.

## Are these changes tested?

Yes — new unit test; existing count-distinct tests pass.

## Are there any user-facing changes?

No.
alamb pushed a commit to alamb/datafusion that referenced this pull request Aug 2, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes #.

## Rationale for this change

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->
When browsing a recent PR
apache#23954, I found the there are
two corner cases missing test coverage in the codecov report. This PR
adds sql tests for them (test result verified with DuckDB)

Missing coverage:

https://app.codecov.io/gh/apache/datafusion/pull/23954?src=pr&el=tree&filepath=datafusion%2Ffunctions-aggregate%2Fsrc%2Fpercentile_cont.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#1935ab8f13c9459b071f56115e8527ed-R462

https://app.codecov.io/gh/apache/datafusion/pull/23954?src=pr&el=tree&filepath=datafusion%2Ffunctions-aggregate%2Fsrc%2Fmedian.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#7cad0cf744d908e2045a5f6c8b6cdf5e-R324

## What changes are included in this PR?

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

## Are there any user-facing changes?

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->
kosiew pushed a commit to kosiew/datafusion that referenced this pull request Aug 12, 2026
…edian` (apache#23954)

## Which issue does this PR close?

- Closes apache#23953

## Rationale for this change

This PR makes three improvements to non-distinct
`PercentileContAccumulator` and `MedianAccumulator`, inspired by recent
work on `percentile_cont(DISTINCT)` (apache#23946):

1. Switch from SipHash to foldhash for internal hash maps
2. Add a null-free fast path to `update_batch` and `retract_batch`
3. Raise an error if we attempt to retract an unknown value in
`retract_batch`, rather than silently ignoring it.

Benchmarks:

percentile_cont no_nulls window=256 -61.1% (249.0 -> 96.6 us)
percentile_cont with_nulls window=256 -59.4% (232.7 -> 94.5 us)
percentile_cont no_nulls window=4096 -50.9% (756.3 -> 370.4 us)
percentile_cont with_nulls window=4096 -48.2% (552.2 -> 286.2 us)
percentile_cont no_nulls window=16384 -47.3% (2.311 -> 1.218 ms)
percentile_cont with_nulls window=16384 -42.0% (1.465 -> 0.851 ms)
median no_nulls window=256 -62.8% (247.0 -> 92.0 us)
median with_nulls window=256 -59.8% (228.8 -> 92.0 us)
median no_nulls window=4096 -40.0% (411.4 -> 246.6 us)
median with_nulls window=4096 -39.4% (364.4 -> 221.0 us)
median no_nulls window=16384 -31.5% (1.107 -> 0.759 ms)
median with_nulls window=16384 -32.9% (0.947 -> 0.637 ms)

## What changes are included in this PR?

See above.

## Are these changes tested?

Yes: existing tests pass, new tests added for the null-free fast path
and the improved error handling.

## Are there any user-facing changes?

No.
kosiew pushed a commit to kosiew/datafusion that referenced this pull request Aug 12, 2026
…pache#23956)

## Which issue does this PR close?

- Closes apache#23955.

## Rationale for this change

`PrimitiveDistinctCountAccumulator::update_batch` does a per-element
validity check on every row even when the array has no nulls. Its own
`merge_batch` already inserts wholesale from the values buffer, so the
same fast path applies to `update_batch`. Inspired by the null-free fast
paths added to `percentile_cont`/`median` in apache#23954.

## What changes are included in this PR?

- When `null_count() == 0`, insert directly from the values buffer
(`self.values.extend(arr.values().iter().copied())`) instead of the
per-element `Option` check.
- Unit test asserting the fast and general paths agree (a dense array
and a null-containing array with the same non-null values yield the same
distinct count).

## Benchmarks

`count_distinct` benchmark, null-free 8192-row batches:

```
count_distinct i64 80% distinct   -67.0%  (54.9 -> 18.1 us)
count_distinct i64 99% distinct   -66.0%  (54.9 -> 18.7 us)
count_distinct u32 80% distinct   -66.9%  (53.9 -> 17.8 us)
count_distinct u32 99% distinct   -65.3%  (53.3 -> 18.5 us)
count_distinct i32 80% distinct   -66.9%  (54.1 -> 17.9 us)
count_distinct i32 99% distinct   -66.2%  (53.2 -> 18.0 us)
```

The bitmap-backed cases (u8/i8/u16/i16) and the grouped-accumulator
cases don't use this path and are unchanged, as expected.

## Are these changes tested?

Yes — new unit test; existing count-distinct tests pass.

## Are there any user-facing changes?

No.
kosiew pushed a commit to kosiew/datafusion that referenced this pull request Aug 12, 2026
## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes #.

## Rationale for this change

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->
When browsing a recent PR
apache#23954, I found the there are
two corner cases missing test coverage in the codecov report. This PR
adds sql tests for them (test result verified with DuckDB)

Missing coverage:

https://app.codecov.io/gh/apache/datafusion/pull/23954?src=pr&el=tree&filepath=datafusion%2Ffunctions-aggregate%2Fsrc%2Fpercentile_cont.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#1935ab8f13c9459b071f56115e8527ed-R462

https://app.codecov.io/gh/apache/datafusion/pull/23954?src=pr&el=tree&filepath=datafusion%2Ffunctions-aggregate%2Fsrc%2Fmedian.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#7cad0cf744d908e2045a5f6c8b6cdf5e-R324

## What changes are included in this PR?

<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## Are these changes tested?

<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
-->

## Are there any user-facing changes?

<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
-->

<!--
If there are any breaking changes to public APIs, please add the `api
change` label.
-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize hashing, null-free fast path in percentile_cont, median

3 participants