Skip to content

Short-circuit MergeTree analysis for empty PREWHERE sets - #113963

Open
rorylshanks wants to merge 55 commits into
ClickHouse:masterfrom
rorylshanks:fix-empty-in-prewhere
Open

rorylshanks wants to merge 55 commits into
ClickHouse:masterfrom
rorylshanks:fix-empty-in-prewhere

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

An IN (subquery) predicate with a ready empty set is already folded to false by FunctionIn. For MergeTree reads, this happened only after range and data-skipping index analysis, which could spend significant time scanning Bloom-filter indexes even though the query would read no rows.

This change re-evaluates the PREWHERE actions before range selection and returns an empty analysis result when the filter is constant false. Unready sets, including GLOBAL IN sets, remain nonconstant and are not folded prematurely.

The regression test verifies that an empty set avoids Bloom-filter analysis while a nonempty set still uses the index. In the focused performance test with two million granules, median client time decreased from 116.4 ms to 1.77 ms, a 65.6× improvement.

Changelog category (leave one):

  • Performance Improvement

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

Skip MergeTree range and data-skipping index analysis when a ready PREWHERE IN set is empty.


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

@rorylshanks
rorylshanks marked this pull request as ready for review August 8, 2026 17:15
@yariks5s yariks5s self-assigned this Aug 8, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b27ed96]

Summary: ✅


AI Review

Summary

PR #113963 skips MergeTree range and data-skipping index analysis when a ready PREWHERE filter is provably false. Reviewed head b27ed9695e01c81196e3c9bb05fd72ad082995ed, including all prior discussion and subsequent fixes. No remaining actionable findings. Review evidence includes the focused regression tests and reported before/after benchmark; no local build or tests were run.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 32 queries analysed

This PR adds an early exit to ReadFromMergeTree range selection. When a PREWHERE folds to constant false (an empty IN set or a constant-false filter), index analysis is skipped. The check only runs for queries that have a PREWHERE. Only clickbench Q33 (-12.6%) and Q34 (-12.0%) were flagged, and both stay not_sure: they are GROUP BY scans with no PREWHERE or IN subquery, so they never reach the new code. Their roughly 12% gains, and similar CPU drops, line up with a known shift in master's baseline for these queries, so they say nothing about this change. No tpch_adapted_1_official query moved. That is expected, because none of them filter on an empty IN set.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1143 999 -12.6% <0.0001 aggregation: This is a full-scan GROUP BY with no PREWHERE or IN subquery, so the new empty-set check never runs. The -12.6% comes from master's baseline shifting during the comparison window, not from this PR.
⚠️ 34 not_sure 1141 1004 -12.0% <0.0001 aggregation: This is a full-scan GROUP BY with no PREWHERE or IN subquery, so the new early exit in ReadFromMergeTree is skipped. The -12.0% matches the shift in master's baseline and is not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 071db02d-acc2-473a-98a4-abeaeda00f45
  • MIRAI run: b9cb0359-574e-46f2-b25c-820df8c6f046
  • PR check IDs:
    • clickbench_408984_1791484511
    • clickbench_408996_1791484510
    • clickbench_409002_1791484510
    • tpch_adapted_1_official_409008_1791484510
    • tpch_adapted_1_official_409040_1791484510
    • tpch_adapted_1_official_409069_1791484510

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b27ed9695 with master f1e98b9e5 (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

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

Job report

Build the folding header from all columns required by the `PREWHERE` actions so automatic parallel-replica estimation can include virtual columns.
@rorylshanks

Copy link
Copy Markdown
Contributor Author

@groeneai

Copy link
Copy Markdown
Collaborator

Not caused by your change. The root cause is a TimeSeries inner-table drop that waits uncancellably.

From hung_check.log for that run, the processlist holds 7 stuck DDL queries. The head is DROP TABLE prometheus (ENGINE = TimeSeries), is_cancelled = 1, elapsed 3156s, parked here (frames elided):

DatabaseCatalog::waitTableFinallyDropped
InterpreterDropQuery::waitForTableToBeActuallyDroppedOrDetached
InterpreterDropQuery::executeToTable            <- inner (samples/tags) table drop
InterpreterDropQuery::executeDropQuery
StorageTimeSeries::dropInnerTableIfAny
DatabaseAtomic::dropTable                       <- outer TimeSeries table drop
InterpreterDropQuery::executeToTableImpl
InterpreterDropQuery::executeToTable

The other 6 queries (5x DROP DATABASE ... SYNC, 1x DETACH DATABASE, elapsed 391s to 2988s) are all queued in DDLGuard::DDLGuard on the guard that query holds, so the database stays wedged and the hung check fires.

Why the wait cannot be interrupted: InterpreterDropQuery::executeDropQuery runs the inner drop on Context::createCopy(global_context) (InterpreterDropQuery.cpp:890) while propagating sync verbatim (:883). A global context can never carry a process list element (Context.cpp:4231-4234), so getProcessListElementSafe() at :129 returns null, the throw_if_cancelled callback becomes a no-op, and waitTableFinallyDropped loops until shutdown. is_cancelled = 1 at 3156s elapsed is exactly that: cancellation was requested and the wait never observed it. #97586 made the outer wait cancellable, but the inner-table wait is reached through the global context and was not covered. Checked against the failing build 9bdcd0ec, not just current master.

On attribution: Stress test (amd_debug) with this hung check is 73 rows across 61 distinct PRs and 9 master runs in the last 30 days. Your diff is confined to ActionsDAG, ExpressionAnalyzer and ReadFromMergeTree and has no DDL surface, so it cannot reach this path.

No fixing PR exists for this wait today (#97586, #102804 and #113263 each make a different wait cancellable). A fix task owns it at full effort and I will post the PR link in this thread when it opens.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113963&sha=e1b13078febf32c8cd0803d0bd4febbdb9662f81&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

@groeneai

Copy link
Copy Markdown
Collaborator

Correcting myself on the last paragraph: there is an in-progress fix to link, and I should have led with it.

#113397 (open, @ tiandiwonder) - "Fix a table permanently stuck in the drop queue after a failed materialized-CTE query". That is the other half of the mechanism. The wait I described only fails to return because the inner samples table never actually finishes dropping: DatabaseCatalog::dropTableFinally gates on isSharedPtrUnique(storage), and a materialized-CTE query that throws during plan optimization leaks the plan graph together with every StoragePtr it holds, so the entry is pinned forever. #113397 fixes that leak. The uncancellable wait is then a secondary defect: it turns a stuck drop into an unkillable one rather than an error.

Also worth knowing for your PR, since it explains the timing: the onset is #113772 (merged 2026-08-10T07:46:51Z), which force-enables enable_materialized_cte on the PromQL entry points, so materialized-CTE plans became reachable from ordinary PromQL queries. That setting defaults to 0, which is why this surfaces only where something enables it. Checked ancestry against the tested trees rather than your branch tip: the trigger is present in the failing build 9bdcd0ec (behind 0), and absent from your earlier 45d616c5 run. Your 00:42Z Stress test (amd_debug) red is therefore a different instance, and the 16:25Z one lands squarely after the trigger.

Net for you: nothing to do on this PR. Track #113397; if it merges and the hung check still fires on the 04811_promql* carrier, the residual is the cancellation gap I described and I will follow up here with that PR.

Match the order of `FilterTransform::prepare`: run `FilterTransform::isAlwaysFalseByEmptySet`
first and call `updateHeader` only when it does not fire. Otherwise the dry run of the whole
`PREWHERE` DAG could throw during index analysis for a sibling `and` branch that the runtime
filter would have short-circuited to zero rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rorylshanks

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113963&sha=efa74f5f89af2fa8c284affd0f1c8ad5aa89a08d&name_0=PR&name_1=Performance%20Comparison%20(amd_release%2C%20master_head%2C%205%2F6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

uuid_ip_comparison (added on 2026-09-15) reads a Memory table and doesn't touch the code changed here. Queries #3 and #10 have shown as unstable on master and on other PRs (for example #121137 and #118321).

The Upgrade check (amd_release) failure (CHECKSUM_DOESNT_MATCH after a mutation) has hit 2 to 4 unrelated PRs a day over the last week. It looks related to #110674.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated both; neither is a regression in what this PR changes.

Performance Comparison (amd_release, master_head, 5/6) fails on one dashboard row, uuid_ip_comparison #10 (ipv6_a < (SELECT ipv6_a ... LIMIT 1)), 47.5 -> 61.1 ms. #3 (fs16_a < fs16_b, 65.2 -> 76.1 ms) is reported slower but does not gate. On amd both queries step between two timing levels, and they do it between two master builds as well: #10 went 46 -> 60 ms on master d43d606767f0, #3 65 -> 75 ms on master 51fcc23a55a9. Since 2026-09-17 the #10 step shows in 6 other amd runs out of 337, in both directions. In this run arm is flat (27.4 -> 27.3 ms), and so are the amd queries scanning the same ipv6 columns. What this PR changes on these queries' path runs once per query (the empty-set check in FilterTransform::prepare, the constant-folding check moved into ActionsDAG); the per-row comparison and filter code is untouched.

The confirmation rerun reproduced both after a restart, so this build is on the slow level; the run on the new head is a different build. The dashboard scored it confirmed_regression against its 2.0% default floor, because its history modules report no recent master history for this query (dashboard). That scoring lives outside this repository, so there is no PR from me for this one.

Upgrade check (amd_release): the two configure calls drew different codecs, ZSTD(1) for the previous release and LZ4 after the upgrade. test_1.r2 ran mutation all_0_0_0_1 after the restart under LZ4 while its peer had written it under ZSTD(1), so both checksum aggregates differ. That is what #121249 (mine, open) fixes: the second server reuses the first draw, and its own Upgrade check printed ZSTD(1) twice and passed. Same analysis, with a local reproduction, on #119196. #110674 targets a different trigger of this message (replicas applying different lightweight-update patch sets, #100493); the codec draw alone accounts for this job.

Of the 17 occurrences since 2026-09-20, 10 are this codec case. The other 7 are not: 3 are the lightweight-update fixture t_lwu_cleanup_1 logging different columns hash, 3 are the 04907 fixture differing only in compressed files (two of them with the same hashes under different codec draws), and 1 kept the same codec on both servers. #121249 covers none of those 7; I'm looking at them separately.

rorylshanks and others added 8 commits September 26, 2026 10:29
Projection analysis calls `selectRangesToRead` with the projection metadata, while
`PREWHERE` still refers to the parent table columns, so
`StorageSnapshot::getSampleBlockForColumns` threw `NOT_FOUND_COLUMN_IN_BLOCK`.
Use the types of the `PREWHERE` DAG inputs instead and drop the storage snapshot
plumbing that was only needed for that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ree`

Master made the `indexes` spelling the primary setting name, so `Setting::force_data_skipping_indices` no longer exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@yariks5s yariks5s assigned yariks5s and unassigned yariks5s Oct 19, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants