Repository navigation
Do not let index analysis fail a query on a subexpression it cannot evaluate - #117355
Conversation
…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
|
Workflow [PR], commit [528bf1c] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict
LLVM Coverage ReportMeasured on commit 528bf1c.
Changed lines: Changed C/C++ lines covered: 68/71 (95.77%) · Uncovered code |
…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.
…ng-unevaluable-subexpression-115271
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units337 translation units recompiled, 3441 s compile time in total, 337 of them have a recent master baseline. |
…ng-unevaluable-subexpression-115271
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]>
…ng-unevaluable-subexpression-115271
…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]>
… 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]>
…ng-unevaluable-subexpression-115271
… 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]>
…ng-unevaluable-subexpression-115271
…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]>
…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]>
…-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]>
… 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]>
… 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]>
… 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]>
… 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]>
… 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]>
… 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]>
…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]>
Changelog category (leave one):
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 exampleSELECT count() FROM t WHERE p != 1 AND intDiv(1, p - 1) > 0withuse_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 boundaryp = 1even underWHERE p != 1.The error escaped and turned a valid query into an exception:
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:
applyFunctionpublished 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
26.10.1.1831-master(included in26.10and later)