← Back to Pull requests

perf(msq): merge key statistics snapshots without rebuilding them #20915

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 17, 2026 05:01 UTC
Author

Description

When a stage needs range partitioning, the controller fetches a key statistics snapshot from every worker. It merges them on one thread before it can compute partition boundaries.

For GROUP BY shuffles, the snapshots hold DistinctKeyCollector keys. Each merge first copied the snapshot into a HashMap (DistinctKeySnapshot.getKeysAsMap). It then built a throwaway Object2LongRBTreeMap, sorted with the cluster-by comparator (DistinctKeyCollectorFactory.fromSnapshot). Only after that did it add the tree's keys to the controller's collector, one by one.

With many workers and wide keys, the rebuild dominates the merge. We saw a Dart GROUP BY across about 400 Historicals spend about 20 seconds merging statistics on the Broker, several times longer than its scan. Fetching empty snapshots from the same workers took under 4 seconds, so most of the time is the merge. Task-based MSQ queries with many workers take the same path.

Merge snapshots directly

  • Added KeyCollectorFactory.addSnapshot(collector, snapshot). The default implementation is the existing collector.addAll(fromSnapshot(snapshot)), so QuantilesSketchKeyCollectorFactory is unchanged.

  • DistinctKeyCollectorFactory overrides it with the new DistinctKeyCollector.addAll(DistinctKeySnapshot):

  • - The collector first raises its spaceReductionFactor to the snapshot's, as addAll(DistinctKeyCollector) does.
    - It then calls add for each key in the snapshot's list.
    - Snapshots list their keys in sorted order, so keys arrive in the same order as before and the result is the same.
  • DelegateOrMinKeyCollectorFactory merges directly when both sides have a delegate. In the other cases it keeps the existing path, which adds at most one key.

  • ClusterByStatisticsCollectorImpl.addAll(ClusterByStatisticsSnapshot) now calls addSnapshot.
  • I considered putting the hook on the collector instead, as KeyCollector.addAll(KeyCollectorSnapshot). The factory already converts snapshots and knows both types, and the default implementation needs fromSnapshot, so the hook lives on the factory.

    Count retained bytes when merging into an empty collector

    DistinctKeyCollector didn't count the bytes of keys in two cases:

  • keys loaded by the constructor that fromSnapshot uses;

  • keys that addAll copies into an empty collector.
  • Downsampling later subtracts the bytes of the keys it drops, so retainedBytes could go negative and the controller could exceed its statistics budget. Both cases now count their
    keys' bytes.

    Workers also combine their per-processor collectors starting from an empty onens). With this fix they stay within their statistics budget too, so they maydownsample sooner than before.

    One difference from the old path remains. Suppose the collector is empty and a single snapshot's keys reach its byte limit. The direct merge downsamples right away, while the old path
    waited until a later
    add.

    Benchmarks

    MsqSketchesMergeBenchmark, added in this PR, merges every worker's snapshot ollector, as the controller does before it generates partition boundaries.

  • Each invocation merges freshly deserialized snapshots.

  • Each worker has 10,000 keys of 8 columns, and each key appears on 4 workers.

  • Workers have a 150 MB statistics budget and the controller has 300 MB.
  • The run used an Apple M3 Pro with JDK 25, a 4 GB heap, -prof gc, and 5 warmup and 5 measurement iterations of 10 s. "Before" is this PR's base commit with only the benchmark added.
    ± is JMH's 99.9% confidence interval.

    | Collector | Workers | Before | After | Allocated per merge |
    |---|---|---|---|---|
    | Distinct keys (
    aggregate=true) | 10 | 102.9 ± 38.3 ms | 35.0 ± 1.9 ms | 54
    | Distinct keys (
    aggregate=true) | 100 | 1,512.1 ± 55.7 ms | 725.1 ± 156.3 ms | 547.3 MB → 230.2 MB |
    | Quantiles sketch (
    aggregate=false) | 10 | 35.1 ± 3.4 ms | 33.7 ± 1.6 ms |
    | Quantiles sketch (
    aggregate=false) | 100 | 541.5 ± 55.1 ms | 526.4 ± 26.8 ms | 1,080.3 MB → 1,080.3 MB |

    For distinct keys, the direct merge is 2.1× to 2.9× faster and allocates about 58% less. The quantiles-sketch path is unchanged: it allocates the same, and its times are within noise.
    Its rows pool two later runs of each jar, alternating before and after, becaus

    To run it: java -jar benchmarks/target/benchmarks.jar MsqSketchesMergeBenchma

    A larger one-off run was built to match the query above:

  • One thread merges 417 worker snapshots, which were built and serialized the way workers do it.

  • There are 966,345 distinct groups with 24-column keys averaging 717 bytes, about 18.5 workers.

  • The controller budget is 300 MB. The run was on the same machine.
  • | Worker statistics budget | Total snapshot size | Old path | Direct merge |
    |---|---|---|---|
    | 150 MB (no downsampling) | 13.1 GB | 33.3 s | 7.5 s |
    | 8 MB | 1.6 GB | 4.0 s | 2.6 s |

    Both paths ended with the same number of retained keys, total weight, retainedtor and partition count.

    Tests

  • New tests check the direct merge against fromSnapshot + addAll:

  • - snapshots at mixed
    spaceReductionFactors;
    - every combination of empty, delegate and min-key-only collectors in
    Deleg
    - retained bytes after merging into an empty collector.
  • KeyCollectorTestUtils.doTest now also adds snapshots to an empty collector.

  • The byte-count tests fail without the fix.

  • The existing statistics and kernel tests, MSQSelectTest and MSQInsertTest
  • Release note

    Merging key statistics on the controller is faster for range-partitioned GROUPQ and Dart queries with many workers. Retained-bytes accounting for thesestatistics is also fixed, so controllers and workers stay within their statistics memory budgets.

    <hr>

    ##### Key changed/added classes in this PR
    KeyCollectorFactory
    DistinctKeyCollector
    DistinctKeyCollectorFactory
    DelegateOrMinKeyCollectorFactory
    ClusterByStatisticsCollectorImpl
    MsqSketchesMergeBenchmark`

    <hr>

    This PR has:

  • been self-reviewed.

  • a release note entry in the PR description.

  • added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.

  • added comments explaining the "why" and the intent of the code wherever n unfamiliar reader.

  • added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code

  • coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-cov

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: amaechler Review duration: 19484m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #20915"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%
    Repository