Skip to content

Make ReadFromMergeTree::applyFilters rebuild an index analysis made before filter pushdown - #120011

Merged
github-merge-queue[bot] merged 4 commits into
masterfrom
estimate-keep-index-analysis
Oct 9, 2026
Merged

github-merge-queue[bot] merged 4 commits into
masterfrom
estimate-keep-index-analysis

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #115605

estimateReadRowsCount runs index analysis on a ReadFromMergeTree step and stores it on that step. Every caller on master runs after the filters are pushed down, so the stored KeyCondition matches the read. ReadFromMergeTree::applyFilters keeps that object when it is already set (if (!indexes)).

ReadFromMergeTree
+-- indexes   KeyCondition from the filters already on the step

#115605 uses estimateReadRowsCount to compare the right table's size with parallel_hash_join_threshold and select the serial or parallel hash layout. In the legacy analyzer's chooseJoinAlgorithm, this runs before joined_plan is optimized. That path is still used for joins inside IN subqueries in CHECK constraints during INSERT.

Without this change, the estimate can leave indexes that omit filters pushed down later. ReadFromMergeTree::applyFilters keeps those existing indexes, so the executed read loses pruning from those filters. This can cause unnecessary reads and a max_rows_to_read exception even when the filtered read would fit the limit. This change lets that estimate run before filter pushdown without disabling pruning when the read executes.

ReadFromMergeTree::applyFilters records whether it built indexes. If it did not, they were built before the filters were pushed down. It drops them and the range analysis made with them, then builds them from the filters. The step keeps an analysis it gets through its constructor. On master the new branch never runs.

ReadFromMergeTree::applyFilters

indexes built by applyFilters    kept, as master does
indexes built before pushdown    dropped with their range analysis
                                 rebuilt from the pushed-down filters

No caller on master leaves indexes for applyFilters to find. The only one is the estimate that #115605 adds to chooseJoinAlgorithm in src/Interpreters/ExpressionAnalyzer.cpp. User SELECT queries no longer reach that path.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

  • Merged into: 26.10.1.1-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1eeb87a]

Summary: ✅


AI Review

Summary

This PR fixes the stale ReadFromMergeTree index-analysis reuse by dropping pre-pushdown indexes and analyzed_result_ptr in applyFilters before rebuilding from the final pushed-down filters. That reset looks directionally correct, but I do not think this is ready to merge without a focused regression test for the exact max_rows_to_read failure mode described in the PR.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3284] The patch changes a subtle planner/execution contract, but it still does not pin the reported regression with a test. The bug here is specifically that estimateReadRowsCount can build empty-filter indexes before filter pushdown, execution later reuses them, and max_rows_to_read = 11 fails even though the pushed-down filter should prune the read to 10 rows. Without a focused 0_stateless regression test for that path, a later refactor can silently reintroduce the same stale-analysis reuse.
    Suggested fix: add a small stateless query test that drives the chooseJoinAlgorithm / estimateReadRowsCount path from the PR description and asserts the query stays under the row limit.
Final Verdict

⚠️ Needs changes before merge: add the missing regression test for the stale-analysis path this PR is fixing.

LLVM Coverage Report

Measured on commit 1eeb87a.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.60% -0.10%

Changed lines: Changed C/C++ lines covered: 13/15 (86.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1eeb87aa6 with master b5d7e18bb (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.

Compile time of recompiled translation units

119 translation units recompiled, 1424 s compile time in total, 119 of them have a recent master baseline.

Job report

@harikrishnan94
harikrishnan94 changed the base branch from master to two-level-hash-table-buckets September 16, 2026 15:34
harikrishnan94 added a commit that referenced this pull request Sep 16, 2026
…n of `estimate-keep-index-analysis`

`joinOrder.h` on `ijoin-add-block-to-join-worker-id` already declares
`estimateReadRowsCount` with the `keep_index_analysis` default argument in
`QueryPlanOptimizations`, so the declaration `uhj` carried from an older
version of #120011 redefined the default arguments and broke every
translation unit that includes the header. The file is now identical to
the parent branch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the two-level-hash-table-buckets branch from 47abb80 to d382e68 Compare September 22, 2026 04:20
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch from 84ca22f to e6d5aed Compare September 22, 2026 04:21
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch from 461e3d4 to 6ec533b Compare September 22, 2026 08:36
@harikrishnan94
harikrishnan94 force-pushed the two-level-hash-table-buckets branch from 2cd3284 to 3adc7e0 Compare September 22, 2026 08:42
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch 2 times, most recently from 1b1b578 to 725da1e Compare September 22, 2026 08:47
@harikrishnan94
harikrishnan94 force-pushed the two-level-hash-table-buckets branch from 65e42fc to 5952587 Compare September 22, 2026 13:29
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch from 725da1e to 04146ad Compare September 22, 2026 13:29
Copilot AI balanced review requested due to automatic review settings October 1, 2026 09:16

Copilot AI 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.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

Review effort: Lite
Findings: 1 Medium severity · 1 Low severity

Open (2)
What changed in this PR

This PR prevents stale MergeTree index analysis (computed before filter pushdown) from being reused after filters are applied, ensuring range pruning matches the final pushed-down filters.

Changes:

  • Track whether ReadFromMergeTree::indexes was built by applyFilters via a new boolean flag.
  • Invalidate precomputed indexes and associated analysis when applyFilters runs and detects the indexes were created before filter pushdown.
  • Preserve the tracking flag when adopting filters from another ReadFromMergeTree.
File Description
src/​Processors/​QueryPlan/​ReadFromMergeTree.h Adds state to track the origin of computed index analysis and propagates it in adoptFiltersFrom.
src/​Processors/​QueryPlan/​ReadFromMergeTree.cpp Drops stale index analysis during applyFilters and marks newly built indexes as originating from filter pushdown.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

/// filters. Drop them and the range analysis made with them; `indexes` are rebuilt below.
if (indexes && !indexes_built_by_apply_filters)
{
indexes.reset();
Comment on lines 694 to +697
/// Pre-computed value, needed to trigger sets creating for PK
mutable std::optional<Indexes> indexes;
/// True if `applyFilters` built `indexes` from the filters pushed down to this step.
bool indexes_built_by_apply_filters = false;
@harikrishnan94 harikrishnan94 changed the title Let estimateReadRowsCount keep an index analysis taken before filter pushdown off the read step Make ReadFromMergeTree::applyFilters rebuild an index analysis made before filter pushdown Oct 1, 2026

/// If `indexes` were built before the filters were pushed down to this step, they do not use those
/// filters. Drop them and the range analysis made with them; `indexes` are rebuilt below.
if (indexes && !indexes_built_by_apply_filters)

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.

This is the right invalidation point, but the PR still needs a focused regression test for the scenario it claims to fix. The bug here is subtle: a pre-pushdown estimateReadRowsCount builds empty-filter indexes, execution later keeps them, and max_rows_to_read = 11 fails even though the pushed-down filter should prune to 10 rows. Nothing in this diff pins that contract, so a future refactor can silently reintroduce the same stale-analysis reuse. Please add a small 0_stateless test that drives the chooseJoinAlgorithm / estimateReadRowsCount path from the PR description and asserts the query stays under the row limit.

Base automatically changed from two-level-hash-table-buckets to master October 1, 2026 17:18
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch from 22221e6 to 7d093b9 Compare October 1, 2026 17:18
harikrishnan94 and others added 3 commits October 5, 2026 20:40
…r pushdown off the read step

`estimateReadRowsCount` runs index analysis on a `ReadFromMergeTree` step and
memoizes it in the step's `indexes`. `ReadFromMergeTree::applyFilters` builds
the indexes only when they do not exist yet, so an estimate taken before the
filters reach the step leaves a `KeyCondition` built from an empty filter on
it, and the executed read prunes nothing.

Every caller on master estimates after `optimizePrimaryKeyConditionAndLimit`,
so none of them hits this. A caller that estimates before the plan is
optimized passes `keep_index_analysis = false`, and the analysis then goes
into a local `Indexes` object. `selectRangesToReadForEstimation` takes the
same flag. An analysis that already exists is reused either way, and the
default path does exactly what it did before.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment-only change from the retro `reduce-complexity`, `humanize` and `plain-prose` pass over this pull request. The `reduce-complexity` pass found nothing to apply.

Every sentence in the edited comments now stays within 25 words. The `selectRangesToReadForEstimation` doc keeps the link between `analyzed_result_ptr` not being set and the re-analysis at execution. The body comment in `selectRangesToReadForEstimation` names `keep_index_analysis` instead of "either way". The blocks wrap at the width of the neighbouring comments.

No statement, signature or default argument changes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… before filter pushdown

`applyFilters` used to keep any `indexes` it found on the step. Pull request
#115605 adds an estimate that runs before filter
pushdown, in `chooseJoinAlgorithm` of the old analyzer. That estimate builds `indexes` without any
filter, so the executed read would prune nothing.

Now `applyFilters` records that it built `indexes`. If it finds `indexes` that it did not build, it
drops them, together with the range analysis made with them. It then builds `indexes` from the
pushed-down filters, and the read analyzes its ranges again.

`estimateReadRowsCount` and `ReadFromMergeTree::selectRangesToReadForEstimation` no longer take
the `keep_index_analysis` flag. It is not needed any more.

On master, `applyFilters` never finds `indexes` that it did not build, so master behaves the same.

Related: #115605

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The comment above the check states the rule and no longer guesses where the stale `indexes` come
from. The comment on `indexes_built_by_apply_filters` no longer repeats what `adoptFiltersFrom`
does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the estimate-keep-index-analysis branch from 7d093b9 to 1eeb87a Compare October 5, 2026 15:10
@harikrishnan94
harikrishnan94 removed this pull request from stack #120423 October 6, 2026 07:36
@harikrishnan94
harikrishnan94 removed this pull request from stack #124166 October 7, 2026 12:21
@nickitat nickitat self-assigned this Oct 7, 2026

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

I think, the current master behavior should be preserved - index analysis might be very costly, we cannot repeat it multiple times. Also, I'm not sure why would we want to use it instead of the current approach that looks at the cached build side size?

@harikrishnan94

harikrishnan94 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

@nickitat this change only exists so that UHJ (#115605) can estimate the right table size with the old analyze and pick the hash table layout the way the new analyzer does. If the old analyzer doesn't need that support, I'd rather close this PR. i'll drop it.

@harikrishnan94
harikrishnan94 removed this pull request from stack #124421 October 8, 2026 09:43
@harikrishnan94
harikrishnan94 marked this pull request as draft October 8, 2026 09:43
harikrishnan94 added a commit that referenced this pull request Oct 8, 2026
The rebuild only served the estimate of the right table size in the old analyzer's `chooseJoinAlgorithm`. #115605 no longer makes that estimate. No other caller leaves `indexes` for `applyFilters` to find, so `ReadFromMergeTree` goes back to the code on master.

Related: #120011

Co-Authored-By: Claude Opus 5.5 <[email protected]>
harikrishnan94 added a commit that referenced this pull request Oct 8, 2026
…nAlgorithm`

The estimate ran index analysis before the filters were pushed down to the read. Index analysis can be expensive, and the read had to run it again to use the pushed-down filters. The new analyzer takes the right table size from the join-order pass and from the hash table statistics cache, so it does not have this cost.

User `SELECT` queries no longer reach the old analyzer. It still runs joins inside `IN` subqueries of `CHECK` constraints during `INSERT`. Without an estimate, `preferParallelHashLayout` picks the two-level layout whenever the join kind supports it. On master, the old analyzer always uses `ConcurrentHashJoin` when `parallel_hash` is allowed.

Review: #120011 (review)
Related: #120011

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-merge-queue
github-merge-queue Bot merged commit 1eeb87a into master Oct 9, 2026
149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
@harikrishnan94
harikrishnan94 deleted the estimate-keep-index-analysis branch October 13, 2026 15:45
@nickitat

Copy link
Copy Markdown
Member

@harikrishnan94 why did we merge it in the end?

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

We didn't.

**#120011 was marked merged indirectly through [[#120002](https://github.com/ClickHouse/ClickHouse/pull/120002)](https://github.com/ClickHouse/ClickHouse/pull/120002). Its code change had already been reverted, so the rejected behavior did not survive that merge.**

I checked the full timeline, commit ancestry, and source at the actual merge:

- **8 October, 15:13 IST:** you removed #120011 from the stack and converted it to draft. There is no subsequent ready-for-review or merge-queue event in [[its timeline](https://github.com/ClickHouse/ClickHouse/pull/120011)](https://github.com/ClickHouse/ClickHouse/pull/120011).
- **#120002 still contained all four commits from #120011**, followed by [`140b822`, “Revert the index rebuild…”](https://github.com/ClickHouse/ClickHouse/commit/140b822415bac5c3661c07896364435818aa4f65). That revert restored both affected files exactly to their contents before #120011.
- **9 October, around 09:49 IST:** #120002 merged, carrying both the original commits **and their revert** into `master`. GitHub recorded #120011 as merged at 09:49:24 and #120002 at 09:49:26. The [[commit ancestry confirms the connection](https://github.com/ClickHouse/ClickHouse/compare/1eeb87aa6c6850773d16d35ee7e6586c50c3acea...52e7be8c0a4590b79830c3f57dd077dba6c212d5)](https://github.com/ClickHouse/ClickHouse/compare/1eeb87aa6c6850773d16d35ee7e6586c50c3acea...52e7be8c0a4590b79830c3f57dd077dba6c212d5).

The key distinction is that **reverting commits undoes their changes but keeps them in history**. Removing a PR from a stack and making it draft also leaves those commits in any downstream branch.

GitHub detects that a PR’s original commits have become reachable from its base branch and automatically marks it merged. This is its documented [[“indirect merge” behavior](https://docs.github.com/en/pull-requests/reference/pull-request-merges#indirect-merges)](https://docs.github.com/en/pull-requests/reference/pull-request-merges#indirect-merges).

That explains the confusing `github-merge-queue[bot]` event: it reflects the history entering `master` through #120002. **Nobody needed to reopen or directly merge #120011, and its earlier merge readiness was not the cause.**

@nickitat

Copy link
Copy Markdown
Member

We didn't.

**#120011 was marked merged indirectly through [[#120002](https://github.com/ClickHouse/ClickHouse/pull/120002)](https://github.com/ClickHouse/ClickHouse/pull/120002). Its code change had already been reverted, so the rejected behavior did not survive that merge.**

I checked the full timeline, commit ancestry, and source at the actual merge:

- **8 October, 15:13 IST:** you removed #120011 from the stack and converted it to draft. There is no subsequent ready-for-review or merge-queue event in [[its timeline](https://github.com/ClickHouse/ClickHouse/pull/120011)](https://github.com/ClickHouse/ClickHouse/pull/120011).
- **#120002 still contained all four commits from #120011**, followed by [``140b822``, “Revert the index rebuild…”](https://github.com/ClickHouse/ClickHouse/commit/140b822415bac5c3661c07896364435818aa4f65). That revert restored both affected files exactly to their contents before #120011.
- **9 October, around 09:49 IST:** #120002 merged, carrying both the original commits **and their revert** into ``master``. GitHub recorded #120011 as merged at 09:49:24 and #120002 at 09:49:26. The [[commit ancestry confirms the connection](https://github.com/ClickHouse/ClickHouse/compare/1eeb87aa6c6850773d16d35ee7e6586c50c3acea...52e7be8c0a4590b79830c3f57dd077dba6c212d5)](https://github.com/ClickHouse/ClickHouse/compare/1eeb87aa6c6850773d16d35ee7e6586c50c3acea...52e7be8c0a4590b79830c3f57dd077dba6c212d5).

The key distinction is that **reverting commits undoes their changes but keeps them in history**. Removing a PR from a stack and making it draft also leaves those commits in any downstream branch.

GitHub detects that a PR’s original commits have become reachable from its base branch and automatically marks it merged. This is its documented [[“indirect merge” behavior](https://docs.github.com/en/pull-requests/reference/pull-request-merges#indirect-merges)](https://docs.github.com/en/pull-requests/reference/pull-request-merges#indirect-merges).

That explains the confusing ``github-merge-queue[bot]`` event: it reflects the history entering ``master`` through #120002. **Nobody needed to reopen or directly merge #120011, and its earlier merge readiness was not the cause.**

I see, thanks for explanation

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.

4 participants