Skip to content

perf: inline the first value in grouped integer DISTINCT counts - #27299

Open
QinXi-ai wants to merge 2 commits into
apache:mainfrom
QinXi-ai:perf/25936-inline-first-distinct-20261110
Open

QinXi-ai wants to merge 2 commits into
apache:mainfrom
QinXi-ai:perf/25936-inline-first-distinct-20261110

Conversation

@QinXi-ai

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Part of #25936. This implements the accumulator step in the follow-up plan.

Rationale for this change

The native grouped integer COUNT(DISTINCT) accumulator currently probes the shared distinct hash set for every non-null input row. For Q10, which has a million groups with four copies of one value per group, keeping that value inline avoids those probes.

I built both versions from c8265b68 on a shared Linux host, using a Xeon Gold 6238T, Rust 1.99.1 and release-nonlto. The suite used four million rows, one target partition, greedy / 1 GiB, with single_distinct_prefer_native enabled. These are medians from three alternating rounds, six iterations per round with the first discarded, giving 15 retained samples per version. CPU affinity was 0-7, with builds stopped during timing.

Case Main This PR Elapsed change Peak pool memory, main / PR
Q01, 2,000 groups, high NDV 318.93 ms 303.87 ms -4.7% 168.17 / 168.17 MiB
Q02, 2,000 groups, eight distinct values each 79.11 ms 80.65 ms +1.9% 0.824 / 0.511 MiB
Q07, skewed integer groups 208.60 ms 203.97 ms -2.2% 42.07 / 42.07 MiB
Q09, skewed composite groups 271.62 ms 269.60 ms -0.7% 42.25 / 42.25 MiB
Q10, a million groups, one distinct value each 382.14 ms 218.90 ms -42.7% 95.88 / 61.88 MiB
Q11, a million groups, at most two values each 417.89 ms 317.86 ms -23.9% 95.88 / 82.88 MiB
Q12, 95% of groups have only NULL arguments 677.61 ms 675.68 ms -0.3% 55.19 / 61.88 MiB

The inline buffer allocates a typed slot for every group, including groups with only NULL arguments. Q12 exposes that cost, with about 6.7 MiB more peak pool memory.

What changes are included in this PR?

Keep each group's first non-null value in a typed vector and put additional values in the shared hash set. After a batch where the average number of additional distinct values per group exceeds eight, move the inline values into the set and release the vector. Subsequent batches use the hash-only loop. This avoids the per-row cache check for the large sets in Q07 and Q09. CPU-0 repeats measured -2.9% and -3.5% elapsed changes for those two queries.

Both modes use the existing List state format. State emission, partial emission, merge and memory accounting handle the inline values and the switch to the hash-only mode.

Add Q11 and Q12 to the SQL benchmark suite to cover small distinct sets and NULL-heavy groups.

What is the testing strategy for this PR?

Added unit tests for partial emission, overlapping merges, group-index shifts, promotion, buffer accounting and reuse. SQL tests exercise small batches and overlapping partial states through the normal query path.

Validated on Linux with Rust 1.99.1.

  • All 64 aggregate-common tests passed.
  • The extended workspace suite passed 13,626 Rust tests, with 8 ignored, and completed all 547 SQL test files.
  • All 116 CLI tests passed.
  • Formatting, strict all-targets/all-features Clippy and the full uv run ./dev/rust_lint.sh suite passed.
  • All twelve SQL benchmark queries passed their result assertions.

Are there any user-facing changes?

Native grouped integer COUNT(DISTINCT) has the runtime and memory changes shown above.

Prepared with Codex assistance. Opening as a draft for author review.

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) functions Changes to functions implementation labels Nov 10, 2026
@QinXi-ai
QinXi-ai marked this pull request as ready for review November 13, 2026 16:03
@kosiew

kosiew commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

@QinXi-ai
Thank you for your contribution.

Can you isolate the benchmark creation in its own commit and rebase it as the first commit so that we can run benchmark like #27435 (comment)

@QinXi-ai
QinXi-ai force-pushed the perf/25936-inline-first-distinct-20261110 branch from c624a1f to 024788c Compare December 2, 2026 18:23
@QinXi-ai

QinXi-ai commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @kosiew. I split the PR into two commits. You can run the grouped COUNT(DISTINCT) suite at a9807de for the baseline, then at 024788c for the inline-first accumulator. The final tree matches the previous PR head.

One observation from a separate local experiment: Q10 and Q11 have dense integer group keys and at most two distinct values per group. A prototype that exploits both properties took Q10 from 381 to 4.9 ms and Q11 from 407 to 4.9 ms on a Xeon, relative to the benchmark-only commit. That was with one SQL partition and eight workers inside the prototype. With eight SQL partitions, both queries were slightly slower than baseline. I’ve kept the prototype on a separate branch.

@kosiew

kosiew commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

run benchmark grouped_count_distinct

baseline:
  ref: a9807de48a
env:
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  MEM_POOL_TYPE: greedy
  MEMORY_LIMIT: 1G

@adriangbot

Copy link
Copy Markdown

Benchmark for this request failed before finishing (Kubernetes reason: BackoffLimitExceeded).

Benchmarks requested: grouped_count_distinct

Runner log (last 40 lines)
2026-12-03T08:15:57.242161Z  INFO runner starting benchmark runner bench_type=Datafusion, pr_url=https://github.com/apache/datafusion/pull/27299, benchmarks=grouped_count_distinct
2026-12-03T08:15:57.317935Z  INFO benchmark_controller::runner::bench_datafusion === Cloning PR branch ===
2026-12-03T08:15:57.317955Z  INFO benchmark_controller::runner::shell running command cmd=git, args=["clone", "--depth=200", "https://github.com/apache/datafusion.git", "/workspace/datafusion-branch"], cwd="/"
2026-12-03T08:16:02.342566Z  INFO benchmark_controller::runner::shell running command cmd=git, args=["fetch", "origin", "refs/pull/27299/head:perf/25936-inline-first-distinct-20261110", "main"], cwd="/workspace/datafusion-branch"
2026-12-03T08:16:22.348052Z  INFO benchmark_controller::runner::shell running command cmd=git, args=["checkout", "perf/25936-inline-first-distinct-20261110"], cwd="/workspace/datafusion-branch"
2026-12-03T08:16:27.350314Z  INFO benchmark_controller::runner::shell running command cmd=git, args=["merge-base", "HEAD", "origin/main"], cwd="/workspace/datafusion-branch"
2026-12-03T08:16:32.352048Z ERROR runner benchmark failed error=git merge-base: git merge-base HEAD origin/main exited with code 1
stdout:

stderr:
Kubernetes message
Job has reached the specified backoff limit

File an issue against this benchmark runner

@kosiew kosiew mentioned this pull request Dec 3, 2026
@QinXi-ai
QinXi-ai force-pushed the perf/25936-inline-first-distinct-20261110 branch from 024788c to 3afc0b8 Compare December 3, 2026 09:08
@QinXi-ai

QinXi-ai commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

run benchmark grouped_count_distinct

baseline:
  ref: 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f
env:
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  MEM_POOL_TYPE: greedy
  MEMORY_LIMIT: 1G

@adriangbot

Copy link
Copy Markdown

@QinXi-ai

QinXi-ai commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@kosiew I rebased both commits onto 42778532 so the runner’s shallow clone can find the merge base. The benchmark-only commit is now 312ca330b6 and the inline-first change is 3afc0b8c37. Both patches are unchanged according to git range-diff.

Could you rerun this benchmark command with the updated baseline? The runner requires an allowlisted account.

@kosiew

kosiew commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

run benchmark grouped_count_distinct

baseline:
  ref: 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f
env:
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  MEM_POOL_TYPE: greedy
  MEMORY_LIMIT: 1G

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark running (GKE) | trigger
Instance: c4a-highmem-16 (12 vCPU / 65 GiB) | Linux bench-c7373470356-6171-r67bf 6.12.105+ #1 SMP Sat Sep 19 07:55:25 UTC 2026 aarch64 GNU/Linux

CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

Comparing perf/25936-inline-first-distinct-20261110 (3afc0b8) to 312ca33 diff

Run configuration
run benchmark grouped_count_distinct
env:
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  MEMORY_LIMIT: "1G"
  MEM_POOL_TYPE: "greedy"
baseline:
  ref: "312ca330b6d76ef93b2cbfec3fd1b6f48cea174f"
Trigger comment
run benchmark grouped_count_distinct
```yaml
baseline:
  ref: 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f
env:
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  MEM_POOL_TYPE: greedy
  MEMORY_LIMIT: 1G
```

Results will be posted here when complete


File an issue against this benchmark runner

@adriangbot

Copy link
Copy Markdown

🤖 Benchmark completed (GKE) | trigger

Instance: c4a-highmem-16 (12 vCPU / 65 GiB)

Comparing perf/25936-inline-first-distinct-20261110 (3afc0b8) to 312ca33 diff

Run configuration
run benchmark grouped_count_distinct
env:
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  MEMORY_LIMIT: "1G"
  MEM_POOL_TYPE: "greedy"
baseline:
  ref: "312ca330b6d76ef93b2cbfec3fd1b6f48cea174f"
Trigger comment
run benchmark grouped_count_distinct
```yaml
baseline:
  ref: 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f
env:
  DATAFUSION_OPTIMIZER_SINGLE_DISTINCT_PREFER_NATIVE: "true"
  DATAFUSION_EXECUTION_TARGET_PARTITIONS: "1"
  MEM_POOL_TYPE: greedy
  MEMORY_LIMIT: 1G
```
CPU Details (lscpu)
Architecture:                            aarch64
CPU op-mode(s):                          64-bit
Byte Order:                              Little Endian
CPU(s):                                  16
On-line CPU(s) list:                     0-15
Vendor ID:                               ARM
Model name:                              Neoverse-V2
Model:                                   1
Thread(s) per core:                      1
Core(s) per cluster:                     16
Socket(s):                               -
Cluster(s):                              1
Stepping:                                r0p1
BogoMIPS:                                2000.00
Flags:                                   fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti
L1d cache:                               1 MiB (16 instances)
L1i cache:                               1 MiB (16 instances)
L2 cache:                                32 MiB (16 instances)
L3 cache:                                80 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-15
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; CSV2, BHB
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected
Details

group                         HEAD                                   perf_25936-inline-first-distinct-20261110
-----                         ----                                   -----------------------------------------
grouped_count_distinct/Q01    1.00    154.6±0.55ms        ? ?/sec    1.01    155.8±2.14ms        ? ?/sec
grouped_count_distinct/Q02    1.02     35.5±0.35ms        ? ?/sec    1.00     34.8±0.08ms        ? ?/sec
grouped_count_distinct/Q03    1.04    153.0±1.84ms        ? ?/sec    1.00    146.9±1.84ms        ? ?/sec
grouped_count_distinct/Q04    1.04    157.9±1.46ms        ? ?/sec    1.00    151.3±1.21ms        ? ?/sec
grouped_count_distinct/Q05    1.01    201.8±3.79ms        ? ?/sec    1.00    200.2±2.95ms        ? ?/sec
grouped_count_distinct/Q06    1.02    202.1±4.64ms        ? ?/sec    1.00    199.1±2.65ms        ? ?/sec
grouped_count_distinct/Q07    1.00    135.4±1.72ms        ? ?/sec    1.01    136.2±1.79ms        ? ?/sec
grouped_count_distinct/Q08    1.05    155.2±1.31ms        ? ?/sec    1.00    147.4±2.20ms        ? ?/sec
grouped_count_distinct/Q09    1.00    175.7±2.04ms        ? ?/sec    1.01   177.7±19.31ms        ? ?/sec
grouped_count_distinct/Q10    2.29    283.3±3.67ms        ? ?/sec    1.00    123.6±2.27ms        ? ?/sec
grouped_count_distinct/Q11    1.69    285.2±4.47ms        ? ?/sec    1.00    168.4±1.90ms        ? ?/sec
grouped_count_distinct/Q12    1.04    202.9±2.11ms        ? ?/sec    1.00    194.9±2.99ms        ? ?/sec

Memory Pool Peaks

Peak MemoryPool reservation per query — what DataFusion's accounting believes it reserved. Recorded only for benchmarks that write a results JSON (the dfbench suites, and the suites bench.sh runs through the Criterion SQL harness since #25644), and only under a memory limit: DATAFUSION_RUNTIME_MEMORY_LIMIT, or one the suite sets itself.

Base: 312ca330b6d76ef93b2cbfec3fd1b6f48cea174f | Changed: perf/25936-inline-first-distinct-20261110

grouped_count_distinct

Query Base Changed Change
grouped_count_distinct/Q01 168.2 MiB 168.2 MiB +0.0%
grouped_count_distinct/Q02 843.6 KiB 523.3 KiB -38.0%
grouped_count_distinct/Q03 168.1 MiB 168.1 MiB +0.0%
grouped_count_distinct/Q04 168.2 MiB 168.2 MiB +0.0%
grouped_count_distinct/Q05 223.5 MiB 223.5 MiB +0.0%
grouped_count_distinct/Q06 191.5 MiB 191.5 MiB +0.0%
grouped_count_distinct/Q07 42.1 MiB 42.1 MiB +0.0%
grouped_count_distinct/Q08 42.2 MiB 42.2 MiB +0.0%
grouped_count_distinct/Q09 42.3 MiB 42.3 MiB +0.0%
grouped_count_distinct/Q10 95.9 MiB 61.9 MiB -35.5%
grouped_count_distinct/Q11 95.9 MiB 82.9 MiB -13.6%
grouped_count_distinct/Q12 55.2 MiB 61.9 MiB +12.1%

Pool accounting vs. process RSS

Max pool peak is the largest reservation any single query in the run reached; peak RSS covers the whole invocation, including data loading and allocator retention, and the two high-water marks need not coincide in time. The gap is therefore an upper bound on what the pool did not account for, not a measurement of it.

Benchmark Side Max pool peak Peak RSS Gap RSS / pool
grouped_count_distinct base (312ca330b6d76ef93b2cbfec3fd1b6f48cea174f) 223.5 MiB 1.1 GiB 878.3 MiB 4.9×
grouped_count_distinct changed (perf/25936-inline-first-distinct-20261110) 223.5 MiB 1.1 GiB 900.9 MiB 5.0×
Resource Usage

grouped_count_distinct — base (merge-base)

Metric Value
Wall time 545.2s
Peak memory 1.1 GiB
Avg memory 216.5 MiB
CPU user 157.8s
CPU sys 1.4s
Peak spill 0 B

grouped_count_distinct — branch

Metric Value
Wall time 550.2s
Peak memory 1.1 GiB
Avg memory 216.3 MiB
CPU user 157.4s
CPU sys 1.4s
Peak spill 0 B

File an issue against this benchmark runner

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

@QinXi-ai,

Thanks for the optimization. The inline fast path preserves distinct-count semantics and partial-state compatibility while substantially improving singleton performance and memory usage.
Benchmark results look great.

Approving with suggestions. The increased memory usage for very sparse inputs is a bounded trade-off worth documenting or addressing separately.

}
});
if let Some(first_values) = &mut self.first_values {
first_values.resize(total_num_groups, T::Native::default());

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.

Could we consider density-based promotion in update_batch and merge_batch? With twelve sparse DISTINCT expressions, peak reservations increased from 5.24 MB to 8.38 MB, introducing spills at 6M. Any guard should preserve Q10/Q11 gains; otherwise, documenting the trade-off is sufficient.

fn evaluate(&mut self, emit_to: EmitTo) -> datafusion_common::Result<ArrayRef> {
let counts = emit_to.take_needed(&mut self.counts);
if let Some(first_values) = &mut self.first_values {
let _ = emit_to.take_needed(first_values);

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.

Optional: consider dropping drain(..n) directly for small discarded inline prefixes to avoid allocation. Retain split-and-drop for large prefixes so the remaining buffer can shrink.

first value, which lets repeated singleton values skip the distinct hash set.
The rewrite's outer aggregate only sees the deduplicated pairs.

When the average number of additional distinct values per group exceeds eight,

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.

Could we clarify that promotion is checked after each update or merge batch, includes NULL-only groups in the average, and remains active through partial emissions until EmitTo::All resets the accumulator?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants