Skip to content

Explain analyze join stats - #110892

Merged
Fgrtue merged 43 commits into
masterfrom
explain-analyze-join-stats
Aug 14, 2026
Merged

Fgrtue merged 43 commits into
masterfrom
explain-analyze-join-stats

Conversation

@Fgrtue

@Fgrtue Fgrtue commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Related: #110668

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add information of internal state of joins to EXPLAIN ANALYZE

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3cf26b7]

Summary: ✅


AI Review

Summary

This PR extends EXPLAIN ANALYZE with join-side participation metrics, join-specific implementation details, and the matches = 1 mode for exact match bookkeeping. The new surface is useful, but the current head still has one new correctness bug in the hash-join counters, one unresolved correctness issue in ConstantJoin resource accounting, several introspection metrics that are still misleading, and a couple of documentation statements that now contradict the implementation.

PR Metadata
  • Changelog category: Improvement matches the change.
  • Changelog entry: required for Improvement, and the current entry is understandable but imprecise. A clearer replacement would be: Add join execution statistics to EXPLAIN ANALYZE.
Findings

❌ Blockers

  • [src/Interpreters/HashJoin/MatchedRowsStats.h:155] The new ReplicationOffsets path reads offsets[i - 1] on the first iteration, so EXPLAIN ANALYZE on ALL INNER / ALL RIGHT hash joins now depends on undefined behavior for the first probed row. This needs a prev_offset = 0 carry or an explicit first-row case.
  • [src/Interpreters/ConstantJoin.cpp:234] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3769953118] selected_right_row still contributes to the reported peak only; it never contributes to getTotalByteCount, spilling, or max_bytes_in_join enforcement. In the SelectedRowOnly plans (ANY INNER ... ON 1 = 1, LEFT SEMI ... ON 1 = 1, etc.) one very wide right row can therefore bypass the join size limit entirely.

⚠️ Majors

  • [src/Interpreters/ConstantJoin.cpp:907] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3751632120] Left: rows is still counted from block.rows(), but JoiningTransform::readExecute rebuilds probe blocks with cloneWithColumns(chunk.detachColumns()). For count()-style constant joins that means zero-column probe blocks report 0 rows even when the join processed real input rows, so EXPLAIN ANALYZE SELECT count() ... CROSS JOIN ... prints a wrong left-side row count.
  • [src/Interpreters/HashJoin/MatchedRowsStats.cpp:49] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3744974492] Exact right-side match tracking for parallel_hash still sizes each bitmap to max(selector) + 1, not to the number of rows actually owned by that slot. On sparse zero-copy selectors this inflates bookkeeping roughly by the shard count and can make EXPLAIN ANALYZE matches = 1 fail from profiling overhead alone.
  • [src/Interpreters/MergeJoin.cpp:1358] On external partial_merge, Right: size is still filled from right_blocks.bytes, which is the total size of all right-side blocks, not the live in-memory footprint once those blocks are flushed to disk. The report therefore mixes “logical bytes of the right side” with “current memory usage” depending on storage, which makes the metric misleading exactly on the spill path users are trying to inspect.
  • [src/Interpreters/ConcurrentHashJoin.cpp:841] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3729361579] Hash table: memory is still computed as the sum of per-slot build peaks. Those slot-local peaks need not overlap in time, so the reported peak can exceed the actual hash-table peak by a large factor and mislead users about the memory cost of parallel_hash.
  • [src/Processors/QueryPlan/AnalyzePlanStats.cpp:230] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3728965557] Stage statistics still drop processors whose elapsed time is exactly zero before incrementing total_num_processors. That makes the processors = 1 output hide idle processors and understate max_parallelism, which is precisely the skew/debugging case this new introspection is meant to explain.
  • [tests/queries/0_stateless/04603_explain_analyze_join_matched_rows.sql.j2:15] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3761470346] The value-based matched-row suites still force query_plan_join_swap_table = 0, so they never verify the swapped-join path that remaps physical build/probe statistics back to logical SQL sides. The group-presence tests are too weak to catch a left/right value swap there.
  • [tests/queries/0_stateless/04759_explain_analyze_join_matched_rows_merge_algorithms.sql.j2:45] [dismissed by author -- https://github.com/Explain analyze join stats #110892#discussion_r3761470352] The merge/hash comparison coverage still exercises explicit join_algorithm = 'grace_hash', but not the SpillingHashJoin wrapper that converts hash / parallel_hash after max_bytes_before_external_join is crossed. That leaves the new stats unproven across the actual auto-spill conversion path.
  • [docs/reference/statements/explain.mdx:838] The docs now say Join(ANY, LEFT, …) reports “neither” side, but filled hash joins still print both Left: and Right: lines there; only matched becomes not collected.
  • [docs/reference/statements/explain.mdx:846] The docs also say CROSS, COMMA, and constant-ON joins report neither side, but ConstantJoin::getAnalysisReport always emits both per-side lines and only leaves matched as not collected.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 1035/1134 (91.27%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 17, 2026
@Fgrtue
Fgrtue requested a review from vdimir July 17, 2026 16:11
@mintlify

mintlify Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 17, 2026, 4:31 PM

Comment thread src/Interpreters/DirectJoin.cpp Resolved
@vdimir vdimir self-assigned this Jul 20, 2026
Comment thread src/Processors/QueryPlan/JoinStep.cpp Resolved
Comment thread src/Interpreters/FullSortingMergeJoin.h Resolved
Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved

@Fgrtue Fgrtue left a comment

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.

Comment thread src/Interpreters/ConstantJoin.cpp Resolved
if constexpr (isLeftOrFull(kind))
{
size_t lnum = nextDistinct(left_cursor);
size_t lnum = consumeEqualRange(left_cursor, any_join_state.matched.left, matched_rows.left);

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.

In consumeEqualRange we compare cursor = left_cursor against matched_range = JoinKeyRow(left_cursor, lpos), won't it always be the same row? Can't we just decide whether to increment the matched count or not based on cmp?

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.

I agree that in principal this is redundant. I'll remove it.

added_columns.applyLazyDefaults();
}
}
if constexpr (leftMatchedSource(KIND, STRICTNESS) == LeftMatchedSource::DefaultRowMarkers)

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.

leftMatchedSource reconstructs the matched-left count four different ways after the fact. But the probe loop already knows the answer per left row: right_row_found in both joinRightColumns variants, and any_matched in joinRightColumnsWithAdditionalFilter — where you do count it directly. Couldn't we just accumulate matched_left there for every kind and drop the enum? The only case where key found != matched is ASOF, where findAsof can come back empty, and processMatch could return that.

Besides being uniform, it would let DefaultRowMarkers go, and with it the forced record_row_refs.

The price is one add per left row in the probe loop, always on. I'd expect it to be lost in the noise next to the hash lookup.

Was this considered and rejected for a reason I'm missing?

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_row_found in both joinRightColumns variants, and any_matched in joinRightColumnsWithAdditionalFilter — where you do count it directly

This would require us to do intervention into the probe loop of joinRightColumns. The goal was not to add anything into the probe loop, in order for EXPLAIN ANALYZE matches=1 making the same cost in the hot loop as it was without it.

The price is one add per left row in the probe loop, always on. I'd expect it to be lost in the noise next to the hash lookup.

This was my initial attempt, but we decided not to do it -- to keep it completely pure. That is why I have built this machinery.

IColumn::Offsets offsets;
Chunk joined_chunk = storage->getByKeys({key_col}, attribute_names, null_map, offsets);

if (table_join->collectAnalyzeStats())

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.

For future work: it would be worth adding information about how many rows were scanned during direct joins. For example, when joining with MergeTree, it can use an index or perform full scans. See

pipeline.setProgressCallback([](const auto & progress) { ProfileEvents::increment(ProfileEvents::JoinBuildTableRowCount, progress.read_rows); });
, similar to how ProfileEvents::JoinBuildTableRowCount is calculated.

- `compact` — see [EXPLAIN PLAN](#explain-plan) section. Default: 1.
- `pretty` — see [EXPLAIN PLAN](#explain-plan) section. Default: 1.
- `processors` — For `EXPLAIN ANALYZE`, prints an additional line per stage with the per-processor elapsed time distribution: `min`, `median`, `max`, and `sum`. Useful to spot load skew across parallel processors. Default: 0.
- `matches` — For `EXPLAIN ANALYZE`, makes join steps do the extra bookkeeping needed for the `matched`, `match rate` and `fanout` metrics in the cases where those numbers cannot be derived from what the join produces anyway. Where they can, they are reported without this option. See [Join steps](#explain-analyze-join-steps). Default: 0.

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.

nit: matches is a bit cryptic on its own - matches of what, and printed or computed? Something like exact_matches would read closer to what it does, since a plain EXPLAIN ANALYZE already reports matches where it can. Feel free to ignore.

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.

I thought about making it exact_matches, but I don't like making names for settings for EXPLAIN long. Because people have to write the full name, and there is not auto helper for that. I think short name might be less annoying.

Comment thread src/Core/Joins.h Outdated
Comment on lines +162 to +163
constexpr bool collectsAnalyzeStats(JoinAnalyzeMode mode) { return mode != JoinAnalyzeMode::None; }
constexpr bool collectsExactMatches(JoinAnalyzeMode mode) { return mode == JoinAnalyzeMode::Exact; }

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'd compare mode directly rather than adding functions

Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
Comment thread src/Interpreters/ConstantJoin.cpp Resolved
@Fgrtue

Fgrtue commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

@Fgrtue
Fgrtue added this pull request to the merge queue Aug 13, 2026
@Fgrtue
Fgrtue removed this pull request from the merge queue due to a manual request Aug 13, 2026
Comment thread docs/reference/statements/explain.mdx Resolved
Comment thread docs/reference/statements/explain.mdx Resolved
@Fgrtue

Fgrtue commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

@Fgrtue
Fgrtue added this pull request to the merge queue Aug 14, 2026
Merged via the queue into master with commit 4d51bb7 Aug 14, 2026
357 of 359 checks passed
@Fgrtue
Fgrtue deleted the explain-analyze-join-stats branch August 14, 2026 09:57
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 17, 2026
azat pushed a commit to azat/ClickHouse that referenced this pull request Aug 17, 2026
…s unit test

`gtest_merge_join_starved_totals.cpp` was written on 2026-08-09 against the
three argument `TableJoin(const Settings &, VolumePtr, TemporaryDataOnDiskScopePtr)`
constructor. Commit b1a380d (PR ClickHouse#110892, merged 2026-08-14) inserted a
`JoinAnalyzeMode analyze_mode_` parameter in the second position, so the call no
longer resolves.

The merge queue built the pull request head, which still had the old base, while
MasterCI builds the post merge tree, where the signature has already changed. The
test file therefore only broke after the merge, and it broke `unit_tests_dbms` in
every configuration that enables tests, which stops `ninja clickhouse-bundle`
before the binary is produced.

`JoinAnalyzeMode::None` is what the test used to get: before the parameter
existed, `analyze_mode` was left at its in class default of `None`. It also keeps
the assertion meaningful. The only behavioural reader of the mode on this path is
`MergeJoin::runPostBuildPhase`, whose condition is
`is_right || is_full || (is_all_join && collectExactMatches())`, and the test
builds a `JoinKind::Full` join, so `is_full` already selects the branch and the
mode cannot change the outcome.

Verified locally: the failing translation unit reproduces the CI error before the
change, `unit_tests_dbms` and `clickhouse` both link after it, and
`MergeJoinStarvedTotals.FullJoinKeepsRightRows` passes. To confirm the test is
still a live oracle rather than merely compiling, `hasPostBuildPhase` was flipped
to `false`, which reproduced the original wrong results
({(0,0),(1,0),(2,0)} instead of {(0,0),(0,3),(1,1),(2,0)}).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

4 participants