Skip to content

Do not recursively split always-true ranges in PK analysis - #93813

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
EmeraldShift:fast-pk
May 30, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
EmeraldShift:fast-pk

Conversation

@EmeraldShift

@EmeraldShift EmeraldShift commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

For very large tables, with queries that select one or more large, consecutive ranges of the table, the generic exclusion search algorithm can take a significant fraction of the total time. This is because for each candidate range, it only considers whether the key condition can be true within that range, otherwise it discards the range. But if the range cannot be false, the algorithm currently splits the range into merge_tree_coarse_index_granularity pieces, and recursively checks them. This leads to O(N * log N) evaluations of the key condition against the inner marks.

It turns out KeyCondition already supports checking if the condition can be false within a range. This PR enables the check, and exits the algorithm early if the selected range cannot be false.

Compare performance:

CREATE OR REPLACE TABLE excl (a int, b int)
ENGINE = MergeTree() ORDER BY (a, b)
SETTINGS index_granularity = 1
AS SELECT 1, 1 FROM numbers(1_000_000);

-- Query
EXPLAIN indexes = 1
SELECT * FROM excl WHERE b = 1
SETTINGS max_threads = 1, send_logs_level = 'trace'

-- Base:
<Trace> default.excl (SelectExecutor): Used generic exclusion search over index for part all_1_1_0 with 1379234 steps
...
0 rows in set. Elapsed: 0.422 sec.

-- PR:
<Trace> default.excl (SelectExecutor): Used generic exclusion search over index for part all_1_1_0 with 1 steps
...
0 rows in set. Elapsed: 0.003 sec.

Maybe there are some cases where it is too expensive to check if a range can be false. I claim we should detect those cases with heuristics and selectively disable this optimization.

Part of #92780

Changelog category (leave one):

  • Performance Improvement

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

Improved the performance of generic exclusion search for queries that select large consecutive ranges of the table.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.269

@EmeraldShift
EmeraldShift marked this pull request as draft January 9, 2026 13:32
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

cc @nihalzp

I'm curious what you think about this one -- it seems almost too obvious to me, so I'm worried I'm missing something. Also, would it compatible with your other PR(s) to sparsify and remove Field from PK analysis?

@nihalzp nihalzp added the can be tested Allows running workflows for external contributors label Jan 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e966b31]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 9, 2026
@nihalzp

nihalzp commented Jan 9, 2026

Copy link
Copy Markdown
Member

Thanks for the idea. I will have a careful look tomorrow.

@nihalzp nihalzp self-assigned this Jan 9, 2026
@nihalzp

nihalzp commented Jan 10, 2026

Copy link
Copy Markdown
Member

@EmeraldShift Some tests seems to have failed and look related. Maybe inspecting them could reveal some edge case?

Yes, they should be compatible.

When bool masks from  hyperrectangles are combined, `BoolMask::operator|`
combines `can_be_false` with `&&`, which destroys information about one
or the other range possibly being false. With the new PK skipping logic,
this caused ClickHouse to read more granules than necessary. We now use
`BoolMask::combine`, which correctly combines `can_be_false` with `||`.

Thinking more about it, it sounds like we should change `operator|` to
behave in a similar way, but I'm less confident in correctness of that.
@EmeraldShift

EmeraldShift commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I think there was a latent bug in the usage of BoolMask for space-filling curves, which I've fixed inline in the PR. Details are in e966b31.

@EmeraldShift

Copy link
Copy Markdown
Contributor Author

Now all tests pass, and there's a good performance improvement for some indexing tests.

@nihalzp Would you mind taking a look?

image image

@EmeraldShift
EmeraldShift marked this pull request as ready for review January 11, 2026 01:46
@EmeraldShift EmeraldShift changed the title WIP: Do not recursively split always-true ranges in PK analysis Do not recursively split always-true ranges in PK analysis Jan 11, 2026
@@ -3473,7 +3458,7 @@ BoolMask KeyCondition::checkInHyperrectangle(
current_intersection = current_intersection & BoolMask(intersects, !contains);
}

mask = mask | current_intersection;
mask = BoolMask::combine(mask, current_intersection);

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.

Yes, that was incorrect and this is the correct fix. Since space-filling curves are analyzed in relaxed mode, this bug currently will not give incorrect results in master.

Comment on lines +1748 to +1752
auto result = check_in_range(range, BoolMask());
if (!result.can_be_true)
continue;

if (range.end == range.begin + 1)
if (!result.can_be_false || range.end == range.begin + 1)

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.

This looks okay. There is no correctness issue here. My only concern is that this may lead to less pruning in some case (I feel it should be quite rare) when we are in relaxed mode (as a result, exact_ranges is nullptr); because in relaxed mode, can_be_false is not reliable anymore and can have false negatives.

I will let @amosbird weigh in here because this part is written by him and may have some insights.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have two concerns here:

auto result = check_in_range(range, BoolMask());

This introduces extra overhead on the hot path. In some cases we end up evaluating can_be_false for the whole range and then again for sub-ranges after splitting, which can effectively double the effort without guaranteed pruning benefit.

if (!result.can_be_false || range.end == range.begin + 1)

As @nihalzp pointed out, in relaxed mode (exact_ranges == nullptr), can_be_false has weak semantics and can easily produce false negatives. Relying on it to stop splitting may noticeably reduce pruning effectiveness. This is not a rare case — relaxed mode is quite common in practice (e.g. time functions, IN / IN SET conditions).

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.

Yes, relaxed mode is quite common. But to get relaxed mode + false negative, it should be rare because IN manually sets can_be_false=true if the atom is relaxed and IN SET can have can_be_false=false in very specific scenario.

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.

@amosbird I think this can have some benefit for NOT IN relaxed case. Suppose IN has can_be_true=false, then NOT IN will have can_be_false=false but this is not a false negative. If the atom is relaxed, then if we manually set can_be_false=true in most cases, then I think we can avoid all false negative and still can benefit from the NOT ... versions.

What do you think?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While looking into this change, I realized that the semantics of BoolMask in relaxed mode are quite hard to reason about, especially once NOT is involved.

Conceptually, what we are trying to represent is a three-state outcome for a range:
all true / all false / undecided. BoolMask approximates this using can_be_true and can_be_false, which works reasonably well in non-relaxed mode, but becomes very confusing in relaxed mode due to over-approximation.

In relaxed mode, the guarantees are asymmetric:

  • can_be_true == false is a strong and reliable signal (ALL_FALSE)
  • can_be_false == false is no longer reliable and may be a false ALL_TRUE

This asymmetry is easy to miss and makes optimizations around splitting, pruning, and NOT inversion difficult to reason about and easy to misuse.

Because of this, I’d like to propose a small refactor: instead of relying on BoolMask semantics in relaxed mode, we could explicitly model the result as a tri-state (ALL_FALSE / UNDECIDED / ALL_TRUE). This would make the code easier to reason about and reduce the risk of subtle pruning regressions.

@EmeraldShift EmeraldShift Jan 13, 2026 •

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 see. I didn't realize there was this much subtlety to the modes of checking the key condition. Pending that refactoring, what do you think about applying this optimization iff:

exact_ranges != nullptr || settings['merge_tree_read_all_true_ranges_in_relaxed_mode']

(modulo the setting name, setting is default false)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m a bit concerned that this setting is too subtle. If it defaults to false, chances are it will almost never be enabled or exercised in practice.

Instead, I think we should aim for a more generally applicable optimization strategy—one that delivers a significant improvement while only introducing negligible or at least well-understood regressions.

Concretely, it might make sense to first evaluate the cost of always attempting the check_in_range(range, BoolMask()) derivation. If the overhead turns out to be negligible, then this PR could already apply the optimization unconditionally in the non-relaxed mode, without gating it behind an extra setting.

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.

Oh, the way I had written it, it would already unconditionally be applied in non-relaxed mode, but be controlled by a setting only in relaxed mode. The performance tests have already run against the unconditional change, and I see mainly speedup. But its possible that those tests aren't stressing this hot loop enough?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But its possible that those tests aren't stressing this hot loop enough?

We probably need a more deliberate microbenchmark or targeted test to validate this. It may turn out to be negligible, but it’s worth proving either way.

@EmeraldShift

Copy link
Copy Markdown
Contributor Author

Sorry, I will probably not have time to work on this soon. But I do think the optimization is valuable, as long as we can get more confident that BoolMask::can_be_false is always set to 1 as appropriate in relaxed mode. It's already done for FUNCTION_IN_RANGE, e.g.:

/// If the condition is relaxed, the `can_be_false` branch is no longer reliable; it may have false negatives.
/// If `element.range` is relaxed (and thus wider) and contains `key_range`, then `can_be_false` becomes false.
/// However, in reality `can_be_false` may be true, because the actual range of element may be stricter than `element.range`.
/// For example, for `match(...)`, a false negative here (i.e. `can_be_false` is false) would make
/// `not match(...)` set `can_be_true = false`, causing us to skip the granule, which would be incorrect.
/// Therefore, we must set `can_be_false = true` to be safe.
/// Additionally, when `KeyCondition::isRelaxed()` is true, the caller should ignore `can_be_false` anyway.
if (element.relaxed)
  rpn_stack.back().can_be_false = true;

Additionally, we should just skip the optimization if KeyCondition::isRelaxed() or exact_ranges == nullptr.

I haven't looked into how set index ranges are computed when we start with an empty BoolMask(). It sounds like it might scan every granule in the range? If that's the case, then this optimization might cause more checks of the range because we have to compute can_be_false on each pass. I wonder if there's a different approach we can add to skip this work? Could we compute exact ranges directly from scanning the set, rather than scan it every time we check some exclusion-searched range?

@nihalzp

nihalzp commented Feb 11, 2026

Copy link
Copy Markdown
Member

@EmeraldShift Yes, I think that this optimization will be quite good. For this, we have to make sure that we never return false negative from checkInRange. I do plan to ensure that in KeyCondition by removing the data member relaxed by pushing all relaxation to atom level. Afterwards, we can merge this PR.

But I want to work on removing the relaxed variable after some of my PK PRs have been merged to avoid duplicate and unnecessary merge conflict work.

@alexey-milovidov

Copy link
Copy Markdown
Member

Yes, the existence of relaxed in KeyCondition always confused me. Will be happy if we can get rid of it!

@alexey-milovidov
alexey-milovidov merged commit 937f841 into ClickHouse:master May 30, 2026
128 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @EmeraldShift @alexey-milovidov — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body thoroughly explains the exclusion-search optimization in MergeTreeDataSelectExecutor.cpp but does not mention the second changed file (KeyCondition.cpp:4831, operator|→BoolMask::combine). That change is correctness-critical: it ensures can_be_false is computed correctly for space-filling-curve keys once the algorithm starts relying on it, so a reviewer should know why it ships together.

  • Suggested addition:

    Also fixes the space-filling-curve branch of KeyCondition::checkInHyperrectangle to combine per-sub-hyperrectangle results with BoolMask::combine (OR of both components) instead of operator| (which ANDed can_be_false). This is required so that can_be_false is reliable for morton/hilbert keys now that the exclusion search consumes it to decide whether a range is always-true.

Ignore this if the current title/body is intentional.

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 pr-performance Pull request with some performance 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.

6 participants