Skip to content

Do not let index analysis fail a query on a subexpression it cannot evaluate - #117355

Merged
fm4v merged 15 commits into
masterfrom
fix-partition-pruning-unevaluable-subexpression-115271
Oct 8, 2026
Merged

fm4v merged 15 commits into
masterfrom
fix-partition-pruning-unevaluable-subexpression-115271

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed an exception (such as Division by zero) thrown from index analysis when a monotonic function chain over a key column cannot be evaluated on a key range endpoint, for example SELECT count() FROM t WHERE p != 1 AND intDiv(1, p - 1) > 0 with use_skip_indexes = 0. Also fixed a possible segmentation fault caused by a poisoned entry in the index analysis function result cache.

Documentation entry for user-facing changes

Index analysis evaluates a monotonic function chain on the endpoints of a key range. Those endpoints are values the analysis substitutes, not values the query asked about, so the chain can fail for an endpoint the predicate itself excludes: intDiv(1, p - 1) divides by zero on the boundary p = 1 even under WHERE p != 1.

The error escaped and turned a valid query into an exception:

CREATE TABLE t (p Int64, b UInt64) ENGINE = MergeTree ORDER BY b PARTITION BY p
    SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1, 10);
SELECT count() FROM t WHERE p != 1 AND intDiv(1, p - 1) > 0 SETTINGS use_skip_indexes = 0;
-- Code: 153. DB::Exception: Division by zero

With the default settings the same query returned the correct 0, but only because the minmax index happened to prune the part before the partition pruner was asked — so whether the query worked depended on which index ran first.

Index analysis is an approximation, and its answer for a range it cannot evaluate is "unknown", the same answer it already gives for a function that is not monotonic on the range. That leaves the range unpruned and the query correct. A broken invariant (LOGICAL_ERROR), a memory limit, a deadline (TIMEOUT_EXCEEDED) or a cancellation is still rethrown - those are the outer guards of the query, not something index analysis may decide to ignore.

Fixing this exposed a latent segmentation fault: applyFunction published its cache entry with a null column before evaluating the function, so a throw left a poisoned entry behind, and the next lookup for the same (function, column) pair dereferenced it. The entry is now computed before it is published.

Closes: #115271
Closes: #124510


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

Version info

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

…valuate

Index analysis evaluates a monotonic function chain on the endpoints of a
key range. Those endpoints are values the analysis substitutes, not values
the query asked about, so the chain can fail for an endpoint the predicate
itself excludes: `intDiv(1, p - 1)` divides by zero on the boundary `p = 1`
even under `WHERE p != 1`.

The error escaped and turned a valid query into an exception:

    CREATE TABLE t (p Int64, b UInt64) ENGINE = MergeTree ORDER BY b PARTITION BY p
        SETTINGS index_granularity = 1;
    INSERT INTO t VALUES (1, 10);
    SELECT count() FROM t WHERE p != 1 AND intDiv(1, p - 1) > 0
        SETTINGS use_skip_indexes = 0;   -- Division by zero

With the default settings the same query returned the correct `0`, but only
because the minmax index happened to prune the part before the partition
pruner was asked - so whether the query worked depended on which index ran
first.

Index analysis is an approximation, and its answer for a range it cannot
evaluate is "unknown", the same answer it already gives for a function that
is not monotonic on the range. That leaves the range unpruned and the query
correct. A broken invariant, a memory limit or a cancellation is still
rethrown.

Fixing this exposed a latent segmentation fault: `applyFunction` published
its cache entry with a null column before evaluating the function, so a
throw left a poisoned entry behind, and the next lookup for the same
(function, column) pair dereferenced it. The entry is now computed before it
is published.

Closes: #115271
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [528bf1c]

Summary: ✅


AI Review

Summary

This PR makes MergeTree index analysis treat monotonic-function chains that fail only on substituted range endpoints as "unknown" instead of surfacing a user-visible exception, preserves fatal outer-guard errors, fixes the poisoned cache-entry path in applyFunction, and teaches the exact-range check to drop over-approximated ranges instead of treating them as inconsistent. I re-read the current diff and all prior discussion/replies, and I do not see any unresolved correctness, safety, or performance issues in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 528bf1c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 68/71 (95.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…fix `clang-tidy`

`applyFunction` executes the function over the whole boundary column, and
monotonic conversions throw `TIMEOUT_EXCEEDED` from their cancellation budget.
Downgrading that to "unknown" would let a query that hit `max_execution_time`
during index analysis fall back to a full scan instead of aborting, so it is
rethrown together with `LOGICAL_ERROR`, `MEMORY_LIMIT_EXCEEDED` and
`QUERY_WAS_CANCELLED`.

Also drop a `std::move` on an argument bound by const reference, which
`performance-move-const-arg` rejected in the `arm_tidy` build.
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 528bf1ca7 with master 2493c465d (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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 05:53
The queries added so far proved the "unknown" answer for a chain that cannot be
evaluated, but none of them reached the second half of the change: the transformed
key is cached per `(function, index column)` and the entry is shared by every range
of a part, so a range whose endpoint fails to evaluate is followed by ranges that
look that entry up. `applyFunction` used to publish the entry with a null column
before computing it, and the throw left that placeholder behind for the next lookup
to dereference.

A primary key with `index_granularity = 1` puts the failing boundary `k = 1` in the
middle of many ranges, which is what makes the later lookups happen. Verified
load-bearing: with the `applyFunction` half of the fix reverted and the `try` / `catch`
kept, the new query segfaults; with the fix, the test passes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits September 17, 2026 21:00
…r the test

Address review: after a throw, `applyFunction` left no cache entry behind, so every
later range of the part asking about the same (function, column) pair re-ran the
whole-column execution and threw again before `applyMonotonicFunctionsChainToRange`
turned it into "unknown". The entry is now published as a failure sentinel (a null
column under the pair's name) and the lookup short-circuits on it: `applyFunction`
returns `std::nullopt`, and the caller answers "unknown" for the range at once.

Measured on a 64-mark part with `index_granularity = 1` (`system.errors` for
`ILLEGAL_DIVISION`): 69 throws per query before, 1 after; 138 vs 2 for two atoms.

The test moves from `05086` (taken on master) to `05227`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
… check

`Upgrade check (amd_release)` intermittently fails its `Error message in
clickhouse-server.log` sub-test on one benign line:

  <Error> StorageFileLog (test_1.filelog_bad_path_attach): The absolute data
  path should be inside `user_files_path`(/var/lib/clickhouse/user_files/)

04202_filelog_attach_path_outside_user_files has an explicit ATTACH query for a
FileLog table whose path is outside `user_files_path`. ATTACH is
LoadingStrictnessLevel::ATTACH, which is >= SECONDARY_CREATE, so the constructor
takes the relaxed branch in src/Storages/FileLog/StorageFileLog.cpp: it logs at
<Error> and returns instead of throwing BAD_ARGUMENTS. That branch is what the
test covers, since refusing to load at reattach time would break server startup.
The table outlives the test because stress threads run with a fixed
--database=test_N (ci/jobs/scripts/stress/stress.py) and clickhouse-test skips
its per-test teardown whenever --database is set, so the shared database is never
dropped. The upgrade restart re-attaches the table, the relaxed branch fires
again, and the line lands in the scanned log, where the post-restart scrub had no
entry for it.

The matcher keys on the StorageFileLog logger plus the message and carries no
table or database name, so the same message is allowlisted for any FileLog table.
The `): ` boundary keeps the discriminating cases visible: a different message
from the same logger, this message from another storage, and a Code: 36 throw of
the same text (the strict-mode path, a real failure) all still fail the job.

Validated against the failing run's own 12.6 MB clickhouse-server.upgrade.log
(PR ClickHouse#117355, sha cff5510): with the entry the scan artifact is empty, and
with it removed the artifact is the 189-byte line CI reported as the failure.

Related: ClickHouse#113781
Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 14:52
… index analysis

Also rethrow `QUERY_WAS_CANCELLED_BY_CLIENT` (the stored cancellation from
`checkTimeLimit`), `CANNOT_ALLOCATE_MEMORY`, `TOO_SLOW` and `ABORTED`
instead of downgrading them to an unknown range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 4, 2026 15:51
…able chain

Address review: `getMonotonicityForRange` can execute the function on the
range endpoints itself (`plus` / `minus` in `FunctionBinaryArithmetic`), so it
can throw before the function is applied. The fail-close handling now wraps the
whole chain, with the same set of rethrown outer-guard error codes.

Fix the AST fuzzer failure `Inconsistent KeyCondition behavior`: once a chain
cannot be evaluated, every range of the part answers "unknown", and the debug
check of the exact range search of `count()` took that over-approximation for
an inconsistency. `KeyCondition` now counts (per thread) the ranges it answered
"unknown" for that reason, and the exact range search drops the exact range
without reporting an inconsistency when its check consulted such a chain.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117355&sha=21a1e5fd80a35a3db6507bb7aa420006ea2e5cb2&name_0=PR
#117355

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merged via the queue into master with commit 50e7ba9 Oct 8, 2026
149 checks passed
@fm4v
fm4v deleted the fix-partition-pruning-unevaluable-subexpression-115271 branch October 8, 2026 13:09
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
alexey-milovidov added a commit that referenced this pull request Oct 8, 2026
…rand-overflow-117237

Conflicts in `KeyCondition.cpp` resolved in favor of `master`: #123535 and #117355 made
`KeyCondition::applyMonotonicFunctionsChainToRange` treat any non-fatal exception at a range endpoint
as "cannot analyze" and `applyFunction` cache a failure sentinel for every exception. That subsumes
this PR's `DECIMAL_OVERFLOW`-only handling, so the PR's `applyMonotonicFunctionsChainToRangeImpl`
split is dropped from `KeyCondition.cpp` and `KeyCondition.h`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 8, 2026
…-pruning

Resolve the conflict with ClickHouse#117355, which wrapped the chain loop of
`KeyCondition::applyMonotonicFunctionsChainToRange` in a `try`: the
`single_point` NULL-sentinel guard stays the first statement of the loop body.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… NULL for it

Port of #124041, a prerequisite of #121154 on this branch: when a link of the monotonic chain
turns a non-NULL bound into NULL, the bound has no position in the `Range` order, so the range
is left unanalyzed instead of compared. Without it the `NOT (coalesce(nullIf(c0, 5), 0) = 1)`
case of `05233_assume_not_null_nullable_partition_key_pruning` still prunes the partition of 5
(4 rows expected, 3 returned), as seen on the 26.9 backport.

#124041 is written against the try/catch chain loop of #117355, which this branch does not have,
so this applies only its check to the branch's loop.

#130788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 17, 2026
…ot read

A `_part_offset` projection used as an index (`optimize_use_projection_filtering`)
evaluates the query filter, restricted to the projection's columns, over every row
of the selected projection ranges, and only afterwards keeps the offsets that fall
inside the parent part's read ranges. So the filter also runs on rows in granules
the primary key or a skip index excluded, and on rows a guard over a column outside
the projection would reject. A conjunct that throws for such a row (`gcd(1, x - 5)`,
`intDiv`, `toUInt64(String)`, ...) made the whole query fail, although the same
query with `optimize_use_projection_filtering = 0` returns a result.

The projection index is an optimization of index-analysis kind, so handle it like
ClickHouse#117355 handles `KeyCondition`: if evaluating the projection filter throws, rethrow
the query's outer-guard errors (`isQueryOuterGuardError`: LOGICAL_ERROR, memory
limits, cancellation, timeouts, ABORTED), otherwise give up the projection index for
that part. The part is then read as with the setting off, so the main read throws
if and only if the query without the index throws. The null bitmap already means
"read this part without the projection index" (cancellation path), so no consumer
changes. `isQueryOuterGuardError` moves out of the anonymous namespace of
`KeyCondition.cpp` and is declared in `KeyCondition.h`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
@nihalzp nihalzp added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 24, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants