Skip to content

Refactoring: Extract relation statistics, bloom filter sizing preparing for MinMaxRuntimeFilter - #120232

Merged
cv4g merged 2 commits into
masterfrom
minmax-join-runtime-filter-prep
Sep 16, 2026
Merged

cv4g merged 2 commits into
masterfrom
minmax-join-runtime-filter-prep

Conversation

@cv4g

@cv4g cv4g commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Prep for #96779.

This PR is extracting class RelationStats, remapColumnStats to RelationStatistics.h and moves bloom filter sizing and debugging related functions into dedicated source and header files too. This is to prepare for additional callers in the code that is planning MinMaxRuntimeFilters.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Workflow [PR]
Sync PR [sync-upstream/pr/120232]

Version info

  • Merged into: 26.9.1.1603 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ddc075d]

Summary: ✅


AI Review

Summary

This PR extracts shared relation-statistics estimation and runtime Bloom-filter sizing helpers out of optimizeJoin.cpp / runtime-filter call sites as prep work for #96779. I reviewed the current diff and touched code paths (optimizeJoin, JoinStepLogical, distributed-plan join/aggregation decisions, Cascades statistics, and runtime-filter build/probe sizing) and did not find a correctness, safety, or test-coverage regression in the current head; the refactor remains mechanical and the PR's CI is green.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit ddc075d.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 240/253 (94.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 15, 2026
@cv4g
cv4g marked this pull request as ready for review September 16, 2026 07:11
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ddc075d04 with master d5b837071 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

7 object files changed (+193.01 KiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp.o new 188.05 KiB +188.05 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeJoin.cpp.o 687.83 KiB 610.66 KiB -77.18 KiB (-11.22%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatistics.cpp.o new 56.83 KiB +56.83 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/RuntimeFilterBloomSizing.cpp.o new 32.16 KiB +32.16 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

24 translation units recompiled, 124 s compile time in total, 21 of them have a recent master baseline.

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp 17.1 s 10.2 s -7.4 s (-42%)

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp: 11.6 s

Job report

return std::max(total, CascadesDefaults::MIN_ROW_WIDTH);
}

RelationStats parseTableStatsHint(const String & stats_hint_json, const String & table_name);

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.

Moved to debugHelpers.{h, cpp}


namespace QueryPlanOptimizations
{
void remapColumnStats(std::unordered_map<String, ColumnStats> & mapped, const ActionsDAG & actions);

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.

Moved to RelationStatistics.{h, cpp}

/// Propagate per-column statistics through `actions`, rekeying the map in place by output name.
/// An output inherits an input's stats when it is that input, an alias of it, or a deterministic
/// single-argument function of it (which cannot increase the distinct count).
void remapColumnStats(std::unordered_map<String, ColumnStats> & mapped, const ActionsDAG & actions);

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.

Previously additionally forward declared in Cascades/StatisticsDerivation.cpp.
Moved to RelationStatistics.{h, cpp}

*/
RelationStats parseTableStatsHint(const String & stats_hint_json, const String & table_name);
RelationStats parseTableStatsHint(ContextPtr context, const String & table_name);
RelationStats getRandomizedStats(UInt64 seed, size_t relation_index, const String & table_name, const Block & header);

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.

All three function decls previously forward declared in optimizeJoin.h too.
Moved to debugHelpers.h


RelationStats parseTableStatsHint(ContextPtr context, const String & table_name);
RelationStats parseTableStatsHint(const String & stats_hint_json, const String & table_name);
RelationStats getRandomizedStats(UInt64 seed, size_t relation_index, const String & table_name, const Block & header);

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.

All three function decls previously forward declared in debugHelpers.cpp too.
Moved to debugHelpers.h

String dump() const;
};

struct RelationStats

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.

Moved to RelationStatistics.h

static constexpr UInt64 MAX_RUNTIME_BLOOM_FILTER_BYTES = 16 * 1024 * 1024;
static constexpr UInt64 MAX_RUNTIME_BLOOM_FILTER_HASH_FUNCTIONS = 10;
static constexpr UInt64 DEFAULT_RUNTIME_BLOOM_FILTER_BYTES = 512 * 1024;
static constexpr UInt64 DEFAULT_RUNTIME_BLOOM_FILTER_HASH_FUNCTIONS = 3;

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.

All four definitions moved to RuntimeFilterBloomSizing.cpp

throw Exception(
ErrorCodes::PARAMETER_OUT_OF_BOUND,
"Specified runtime bloom filter hash function count {} is too big, maximum: {}",
bloom_filter_hash_functions, MAX_RUNTIME_BLOOM_FILTER_HASH_FUNCTIONS);

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.

Whole hunk extracted into resolveRuntimeBloomFilterDefaults (replacing zeroes by default values), validateRuntimeBloomFilterParameters (throwing if value exceeds limit) in RuntimeFilterBloomSizing.cpp

= static_cast<double>(*distinct_keys_hint) / HashJoinEntry::MAX_OVERESTIMATION_FACTOR;
const double predicted_fill_rate = -std::expm1(
-static_cast<double>(bloom_filter_hash_functions) * least_distinct_keys
/ (static_cast<double>(bytes_limit) * 8.0));

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.

Extracted into estimateRuntimeBloomFilterSetBitsRatio in RuntimeFilterBloomSizing.cpp

const double ideal_bloom_filter_bytes = std::ceil(-static_cast<double>(hash_functions) * static_cast<double>(distinct_keys) / std::log1p(-target_fill_rate) / 8.0);
const double clamped_bloom_filter_bytes = std::clamp(ideal_bloom_filter_bytes, 0.0, static_cast<double>(MAX_STATS_SIZED_BLOOM_FILTER_BYTES));
return std::max(static_cast<UInt64>(clamped_bloom_filter_bytes), default_bloom_filter_bytes);
}

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.

Moved to RuntimeFilterBloomSizing.cpp and renamed to growRuntimeBloomFilterBytesFromStats.

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6bbc6806-3aba-4bf8-8388-49f583246e5d
  • MIRAI run: 80999247-1bd0-4230-a89d-b39ed345c351
  • PR check IDs:
    • clickbench_409017_1789556962
    • clickbench_409023_1789556962
    • clickbench_409029_1789556962
    • tpch_adapted_1_official_409035_1789556962
    • tpch_adapted_1_official_409052_1789556962
    • tpch_adapted_1_official_409062_1789556962

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

I'm fine with these changes. Overall, they make the code more modular and improve the readability as well as the intended semantics.
I have a small concern about the refactoring of few methods into debugHelpers.h.
For e.g., it contains the method getRandomizedStats(..) which is more generic (and not only debug helper) and can be used in various scenarios when testing e.g., plan robustness hand-in-hand with cardinality estimation, etc. I would have called this file something like utils.h or other name containing utils as prefix. It looks to me that its more about utilities than mere debugging.

@cv4g

cv4g commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

I'm fine with these changes. Overall, they make the code more modular and improve the readability as well as the intended semantics. I have a small concern about the refactoring of few methods into debugHelpers.h. For e.g., it contains the method getRandomizedStats(..) which is more generic (and not only debug helper) and can be used in various scenarios when testing e.g., plan robustness hand-in-hand with cardinality estimation, etc. I would have called this file something like utils.h or other name containing utils as prefix. It looks to me that its more about utilities than mere debugging.

Thank you! I'll rename it in a follow up PR right away.

@cv4g
cv4g added this pull request to the merge queue Sep 16, 2026
Merged via the queue into master with commit df58b20 Sep 16, 2026
347 of 348 checks passed
@cv4g
cv4g deleted the minmax-join-runtime-filter-prep branch September 16, 2026 16:52
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 16, 2026
@rschu1ze rschu1ze changed the title Extract relation statistics, bloom filter sizing preparing for MinMaxRuntimeFilter Refactoring: Extract relation statistics, bloom filter sizing preparing for MinMaxRuntimeFilter Sep 16, 2026
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.8: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.8 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.8,
  so the file gets a static copy of it with the same body.

The setting `query_plan_lower_array_join_function` does not exist on 26.8
(`arrayJoin` is never lowered to an `ArrayJoinStep` there), so the test
`05406_join_swap_array_join_estimate` drops it from four queries. Those
queries then run the `arrayJoin` expression path, with the same result,
and the reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vdimir pushed a commit that referenced this pull request Nov 2, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.9: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #126491 is applied there, with two adaptations:
- the third argument (`for_runtime_filter_transport`) of the recursive call
  does not exist on 26.9 and is dropped;
- `toUInt64Saturating` (added by #124008, master-only) does not exist on 26.9,
  so the file gets a static copy of it with the same body.

The test `05406_join_swap_array_join_estimate` is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 4, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.8: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #128248 is applied there, on top of the 26.8 resolution
of #126491, with one adaptation: `ArrayJoinStep` has no element filter on
26.8 (`query_plan_fuse_filter_into_array_join` does not exist there), so
only a filter above the step leaves the row count unknown.

The test `05406_join_swap_array_join_estimate` drops the settings that do
not exist on 26.8 (`query_plan_fuse_filter_into_array_join`,
`query_plan_lower_array_join_function`), so its "element filter" and
"filter step" queries are the same query there. The reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 4, 2026
`estimateReadRowsCount` is in `optimizeJoin.cpp` on 26.9: it moved to
`RelationStatisticsEstimator.cpp` only with #120232, which is master-only.
So the change of #128248 is applied there, on top of the 26.9 resolution
of #126491. The hunk is the same as on master.

The test `05406_join_swap_array_join_estimate` is the same as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants