Repository navigation
Conversation
Primary key analysis applies a monotonic function chain speculatively over the whole in-memory index column of a part, not just over the endpoints of the range being analysed. A single index value on which the function throws therefore aborted the whole query, even when the offending value was excluded by the predicate, or belonged to a granule a preceding key column had already pruned. `intDiv` throws for a zero divisor and for the signed minimum divided by an effective -1; `toUnixTimestamp64Nano` throws `DECIMAL_OVERFLOW` near the `DateTime64` maximum. The same queries answer fine on a table with no key, which is what shows the SQL is valid: index analysis is an optimisation, so a failure to apply the chain must degrade to "cannot prune" rather than fail the query. `applyFunction` now reports the failure instead of letting the exception escape, and `applyMonotonicFunctionsChainToRange` maps it to `std::nullopt` - the signal all three of its consumers already treat as "monotonicity unknown on this range". The cache entry is published only after a successful execute, plus an explicit sticky negative entry: master emplaced the entry with a null column before the execute that can throw, the probe loop matches on the name alone, and `FieldRef` dereferences the column unconditionally, so a later probe over the same part would read a half-built entry. That alone is not enough. `matchesExactContinuousRange` asks only whether every chain function is always monotonic, and `markRangesFromPKRange` validates that promise against the ranges it produced, raising `LOGICAL_ERROR: Inconsistent KeyCondition behavior` in debug and sanitizer builds when contradicted. But exactness also requires that the chain was successfully applied: the `nullopt` fallback yields `(true, true)`, a correct over-approximation for pruning that by construction is not exact. On master the exception hid this by failing the query first. So an explicit status flag is propagated from `applyMonotonicFunctionsChainToRange` through both `KeyCondition::checkInRange` and `KeyCondition::checkInHyperrectangle` overloads and both `MergeTreeSetIndex::checkInRange` overloads, and consulted per analysed `part_range`: a range whose chain could not be applied records no exact range, and no inconsistency is reported for it. Ranges that analysed cleanly keep contributing exact ranges, and the invariant check still fires unchanged for a genuine monotonicity lie - the honest "not monotonic on this range" answer deliberately does not set the flag. The parameter is trailing and defaulted, so no existing caller changes. This mirrors the pre-existing escape a few lines above, which already stops filling exact ranges when a condition is relaxed, for the same reason: an analysis that was weakened cannot support `BoolMask::can_be_false`.
Four of the exact-range cases are the only coverage of the exactness precondition this PR adds, and exact ranges are requested only by the trivial-count path, which `optimize_use_projections` and `optimize_use_implicit_projections` gate. The CI runner randomizes both, so on roughly a tenth of runs those cases silently degraded into duplicates of the earlier ones. Pin them per statement, and emit the simplest of the four shapes once per primary-key representation because `use_lightweight_primary_key_index_analysis` selects between the two `checkInRange` overload families the PR edits and is randomized too. The `toUnixTimestamp64Nano` case is the PR's only evidence that the fix is function-agnostic rather than `intDiv`-specific, and its overflow threshold sits 763 seconds past the literal it inserts. With no explicit timezone the type parsed that literal in the server's timezone, which CI randomizes on every stateless job, so any positive UTC offset removed the overflow. Pin the column and the comparison bound to UTC; `session_timezone` is randomized separately, so a floating bound against a UTC-pinned column shifts which rows the predicate keeps. The two closing negative controls read plan text, so they report zero whenever the string is absent for any reason. `parallel_replicas_local_plan` replaces the local `ReadFromMergeTree` with a bare remote step, and `optimize_aggregation_in_order` makes `canUseProjectionForReadingStep` refuse the exact-count optimization once parallel reading is on, which the two ParallelReplicas paramsets enable in the default profile. Pin those per statement rather than tagging the file, so the thirteen bug cases keep the randomized coverage that found the two settings already pinned. `merge_tree_coarse_index_granularity` needed no pin: measured across its whole randomized range the granule assertion is unchanged. Also note at the flag's declaration that only the binary search consults it, since the generic exclusion search derives exactness from the mask.
The set-index propagation this PR adds has one call site per primary-key representation: `KeyCondition::checkInHyperrectangle`'s full overload calls `MergeTreeSetIndex::checkInRange(const Ranges &, ...)`, and its sparse overload calls `checkInRange(const std::vector<int> &, ...)`. Which one runs is `use_lightweight_primary_key_index_analysis`, which the CI runner randomizes, so the single `IN` case exercised one site per run and left the other uncovered. Emit that case once per representation, each asserting the value in effect so a clause that stopped taking effect fails the reference. Dropping the flag from `MergeTreeSetIndex::checkInRange` alone now makes both rows abort while the two range rows still pass, which is what pins the two sites separately rather than merely twice. Nothing asserted that a set-index chain which applies cleanly still prunes: the `IN` cases compare a count against an `ENGINE = Memory` oracle, and declining set-index analysis is an over-approximation, so the counts stay correct. The file's only plan-level assertions both used a range predicate. Add the `IN` counterpart of the granule-pruning control; making both `checkInRange` overloads decline analysis turns its plan into `Granules: 100/100` while every existing assertion still passes. The non-monotonic case's comment claimed it kept the exact-range consistency check from being switched off. It cannot observe that: a chain that is not always monotonic makes `matchesExactContinuousRange` false, so analysis takes the generic exclusion search, which never reads the failure flag. State what the case does guard, and where the stronger property is established instead. Also correct the count of stateless tests pinning `explain_query_plan_default` to `legacy`: 477 pin it, 478 mention it, and the one file in the difference pins a different value.
…04648 The failure flag this pull request threads through key analysis suppresses exact ranges. The test pinned that direction thoroughly, and it pinned that a chain which applies cleanly still prunes granules, but nothing pinned that such a chain still yields an exact range. The only exact-count assertion used `a > 10 AND a < 90`, whose `monotonic_functions_chain` is empty, so `applyMonotonicFunctionsChainToRange` is never entered for it and the flag cannot be set on its path. A regression setting the flag after a successful transform therefore preserved every count in the file, both granule assertions and that exact-count assertion, while silently disabling the trivial-count optimization for every chain-based predicate. Only one stateless test on master asserts that optimization at all and it carries no chain either, so nothing else would have caught it. Add four assertions that drive the exact-count optimization through `intDiv(a, 10)`, which is always monotonic as `matchesExactContinuousRange` requires: once per primary key representation, and once per spelling so the set index's own call sites are covered in this direction too. The `IN` set has one element because a larger one relaxes the condition, and a relaxed condition zeroes the exact ranges outright. Reporting the flag on the success path now flips exactly those four rows and leaves every pre-existing assertion passing, which is the asymmetry that makes them worth having. Also drop the count from the comment above the `explain_query_plan_default` pin. It said two closing controls read `EXPLAIN` output as text; there are more now and the number will keep drifting, while the sentence needs no numeral. Co-Authored-By: Claude Fable 5 <[email protected]>
KeyCondition::checkInHyperrectangle reported each atom's per-granule verdict to the partial-disjunction bitset from a counter incremented at the bottom of the per-element loop, so every early exit skipped both the report and the increment. From then on the counter trailed the element's real position in the RPN, and MergeTreeDataSelectExecutor - which indexes that bitset positionally, both when writing and when re-evaluating the expression in mergePartialResultsForDisjunctions - read one atom's verdict out of another atom's bit. The bitset starts out all-true, so an unwritten position reads as "this atom may be true" and the shift is silent: the merged expression is not the query's, and a granule that cannot match survives. On master that early exit was reachable only for an honestly non-monotonic chain. This branch adds three more routes to it (a throwing getMonotonicityForRange, a throwing explicit-field transform, a throwing whole-column transform), and those are exactly the queries it makes work, so the latent accounting bug becomes reachable through the new behaviour. Derive the position from the loop index instead of a separate counter, and report through one helper that every path out of the body calls, so the invariant is that the callback runs exactly once per element with the element's own index. Chasing the seven early exits with an extra increment would leave the next added one broken again. A caught chain failure pushes (true, true) and is not FUNCTION_UNKNOWN, so it reports is_unknown = false with element_result = true. The consumer early-returns on is_unknown and leaves the bit at its all-true default, which is the same value, so reporting it as known simply writes it explicitly. The regression case in 04648 asserts the combined granule count, because the row count stays correct here and only pruning is lost: 6/8 with the position keyed on the RPN index, 7/8 with it shifted.
…wrong comments A monotonic function chain can throw at two distinct points during key analysis: while the chain is applied to an analysed endpoint, and one step earlier, while the chain's monotonicity is being decided. `plus`/`minus` by a constant decide monotonicity by evaluating the function on both endpoints, so an endpoint that overflows makes the decision itself throw. Only the first route was covered: a build with just the `getMonotonicityForRange` guard removed left the whole test green, so that guard was unpinned. Add a `Decimal64` case whose analysed range contains a value that overflows the addition while the query's own row domain excludes it. Verified by instrumenting all three catch sites: the new case reaches the monotonicity-decision catch, while the existing `intDiv` cases reach only the whole-column transform catch. With the monotonicity guard removed the suite now stops exactly at the new case and every earlier case is unchanged. Also correct three comments that stated things which are not true: - The claim that a session `SET` loses to the CI runner was backwards. The runner passes randomized values as client command-line options, and the client applies each `SET` in the stream to its context afterwards, so a session `SET` does win. The statement-level `SETTINGS` clauses stay, for the real reason: they scope each pin to the statements that need it. - `explain_query_plan_default` is not randomized by the runner. - The "477 other stateless tests" count was wrong and drifts with every merge, so it is gone rather than replaced. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (6 gate rounds, 40 findings adjudicated, 0 open)Before opening this PR I ran an independent second-model review against the diff, in six rounds, plus Rounds: 6 approach rounds (5 findings) and 6 diff rounds (40 findings: 28 accepted, 6 rejected Accepted and fixed
Rejected, with evidence
Noted, not blocking
Verification carried over each roundDeterministic failure on the merge base and success on the fix build for every bug case, with an Session id: cron:clickhouse-review-slot-54:20260728-062700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260727-231000 |
|
cc @rschu1ze @alesapin — could you review this? Primary key analysis applies a monotonic function chain over the whole in-memory index column of a part, so an index value the query's own predicate excludes could make the function throw and fail a valid query ( |
|
Workflow [PR], commit [5ab56c8] Summary: ❌
AI ReviewSummaryThis PR makes primary-key analysis fail soft when a monotonic chain throws on values that the query would never read, and it also fixes the skip-index OR position accounting that those new early exits exposed. The direction is right, but the current head still has two correctness blockers: the new fail-soft paths still swallow fatal/resource exceptions, and the generic-exclusion exact-range path can still treat a failed chain under Findings❌ Blockers
Tests
Final Verdict❌ Changes requested. |
| result_column = func->execute(args, result_type, args.front().column->size(), /* dry_run = */ false) | ||
| ->convertToFullColumnIfLowCardinality(); | ||
| } | ||
| catch (const Exception &) |
There was a problem hiding this comment.
This catch is too broad for the new fallback path. func->execute on the whole primary-index column can also throw query-control or resource exceptions (TIMEOUT_EXCEEDED, QUERY_WAS_CANCELLED, QUERY_WAS_CANCELLED_BY_CLIENT, CANNOT_ALLOCATE_MEMORY, MEMORY_LIMIT_EXCEEDED), not just data-domain errors like ILLEGAL_DIVISION / DECIMAL_OVERFLOW. Swallowing those here turns them into a sticky negative cache entry for the whole part, so the query keeps running as a full scan instead of honoring the failure. Please rethrow the control/resource codes here (and in the sibling new catches below), or whitelist only the semantic exception codes that should degrade to "cannot prune".
There was a problem hiding this comment.
Agreed on the resource half, and it reproduces. Measured on this branch against a 400000-mark index, SELECT count() FROM t_idx WHERE intDiv(a, 10) IN (0):
max_memory_usage |
master | this branch |
|---|---|---|
| 8000000 | Code: 241 MEMORY_LIMIT_EXCEEDED |
returns the correct 10, having read 400000/400000 marks |
| 9000000 | 10/400000 marks | 10/400000 marks |
MemoryTracker throws a plain DB::Exception (src/Common/MemoryTracker.cpp:240-245, :358-365), so catch (const Exception &) does swallow it; master's applyFunction has no try/catch at all, so it propagated there. The sticky-entry clause holds too, with one bound worth stating: the negative entry lives in the index_columns vector built per call at MergeTreeDataSelectExecutor.cpp:1931, so one transient failure disables pruning for the whole part for the remainder of that markRangesFromPKRange call, not process-wide.
One correction. The cancellation codes are not reachable at this site: TIMEOUT_EXCEEDED, QUERY_WAS_CANCELLED and QUERY_WAS_CANCELLED_BY_CLIENT are polled at pipeline boundaries, not inside IFunction::execute, and the src/Functions/ sites that raise them (h3PolygonToCells.cpp:175, h3PolygonToCellsWithContainment.cpp:249, FunctionBaseXXConversion.h:362, sleep.cpp, array/arrayFold.cpp) declare no hasInformationAboutMonotonicity(), which is the gate for entering a monotonic chain (KeyCondition.cpp:2074, :3183, :5335). The finding stands on the resource codes alone.
Fix, applied to all three catches this PR adds (:1757, :1824, :5249; :2441 is pre-existing and byte-identical to master): classify on e.code() and rethrow everything that is not a data-domain error, keeping ILLEGAL_DIVISION and DECIMAL_OVERFLOW degrading to "cannot prune", shaped like MergeTreeSelectProcessor.cpp:457-462. I will re-run the test file's 16 cases against the whitelist before pushing.
| return (*col)[0]; | ||
| } | ||
| catch (const Exception &) | ||
| { |
There was a problem hiding this comment.
@groeneai is it safe to ignore the exception here? Is the exception logged somewhere?
There was a problem hiding this comment.
No to both.
Not safe in general. The catch swallows any DB::Exception, and MEMORY_LIMIT_EXCEEDED is one: MemoryTracker raises it as a plain DB::Exception (src/Common/MemoryTracker.cpp:240-245, :358-365), not as a distinct type. I could measure that on the whole-column sibling of this catch (:1824, same shape), where the transform allocates 4 MiB. Against a 400000-mark index, SELECT count() FROM t_idx WHERE intDiv(a, 10) IN (0):
max_memory_usage |
master | this branch |
|---|---|---|
| 8000000 | Code: 241 MEMORY_LIMIT_EXCEEDED |
returns the correct 10, having read 400000/400000 marks (PK index has dropped 0/400000) |
| 9000000 | prunes to 10/400000 marks | prunes to 10/400000 marks |
So the branch as posted converts a resource failure into a silent full scan, which is a change in query-failure semantics rather than a swallowed diagnostic. This site here executes on a single constant row, so it allocates far less and I have no measurement of it faulting, but the catch is equally broad: once a query sits at its memory limit any allocation throws, and this one would be swallowed too. For the data-domain codes the path exists for (ILLEGAL_DIVISION, DECIMAL_OVERFLOW) the degradation to "cannot prune" is intended and safe.
Not logged anywhere. KeyCondition.cpp contains 0 LOG_*, 0 getLogger, 0 ProfileEvents and 0 tryLogCurrentException, so the swallow is unobservable from both SQL and the server log.
Fixing both halves: classify on e.code() in all three catches this PR adds (:1757 here, :1824, :5249), rethrow anything that is not a data-domain error, keep the data-domain codes degrading to "cannot prune". If you want the intended degradation visible as well, say so and I will add a trace line or a ProfileEvent for it.
There was a problem hiding this comment.
Agreed, and sorry for the long silence here.
The blanket catch (const Exception &) goes. applyFunctionForField and applyFunction will not catch at all; there will be one catch at applyMonotonicFunctionsChainToRange, where only value-domain evaluation errors (division by zero, decimal overflow, value parse or format errors) mean "this range cannot be evaluated", and everything else propagates. That restores the case I measured earlier in this thread: with the current catch, SELECT count() FROM t_idx WHERE intDiv(a, 10) IN (0) under max_memory_usage = 8000000 returned a result instead of Code: 241, because MemoryTracker throws a plain DB::Exception.
#117355 is open on the same call site and already has that shape. One difference I would keep: a whitelist of value-domain codes rather than a list of codes to rethrow, so a resource or cancellation code added later is not swallowed by default. Say the word if you prefer the #117355 list.
Since #117355 covers the partition-pruning and primary-key faces, the only part of this PR it does not cover is the IN path (MergeTreeSetIndex::checkInRange) plus the exactness guard that stops _exact_count_projection from trusting a widened mask. Do you want this PR cut down to that, or closed in favour of #117355?
CI finish ledger — 271c59aEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260729-043000 |
ColumnWithTypeAndName's three-argument constructor takes every parameter
by const reference (src/Core/ColumnWithTypeAndName.h:27), so neither
std::move on that line could move anything. clang-tidy reports
performance-move-const-arg twice for it and warnings are errors in the
arm_tidy build, so the Build (arm_tidy) check failed.
Removing the calls is codegen-identical and restores the convention the
rest of the file already follows: master has no
ColumnWithTypeAndName{std::move(...)} site, and the sibling publish a few
lines above passes its arguments plainly.
Verified with clang-tidy-21 over the file: two performance-move-const-arg
errors at 1833:53 and 1833:79 before, zero after, and no other finding
under the full enabled checkset.
|
Fixed in 2ccb5ee. The red was mine.
One thing you should know before merging, since I found it while re-reviewing this push and it is worse than the tidy failure. The exception-swallowing this PR adds can suppress an exception the query is supposed to raise: CREATE TABLE gb (a Int8) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1;
INSERT INTO gb SELECT number-128 FROM numbers(256);
SELECT count() FROM gb WHERE intDiv(a, toInt8(-1)) = 0 OR a <= 50;On this branch that returns I am fixing that together with the exception classification I already owe @ PedroTadim and the review bot on this PR (classify on |
| /// then only an over-approximation, so the exactness guarantee `matchesExactContinuousRange` gives does not hold for | ||
| /// it. Reset per analysed `part_range` below, because a chain can fail on one range and succeed on another (whether | ||
| /// it throws depends on the endpoint values). Only the binary search consults it: the generic exclusion search | ||
| /// derives exactness from the mask itself, so an over-approximated mask there already yields no exact range. |
There was a problem hiding this comment.
This assumption breaks for the generic exclusion path when exact_ranges are collected for _exact_count_projection. genericExclusionSearch marks a range exact whenever check_in_range(range).can_be_false is false, and a swallowed chain failure can still produce that under OR: on an Int8 key, intDiv(a, toInt8(-1)) = 0 OR a <= 50 gives (true, true) | (true, false) == (true, false) for any subrange entirely <= 50. On this branch that lets SELECT count() ... return a count from _exact_count_projection instead of raising ILLEGAL_DIVISION, because the failed intDiv side is never evaluated on rows. The generic path needs its own per-range chain-application-failure guard before it records exact_ranges, plus a regression for the exact-count OR shape.
There was a problem hiding this comment.
Confirmed, and the shape you give is exactly it. My own second-model review found the same defect independently in the same round, with the same intDiv(a, toInt8(-1)) = 0 OR a <= 50 predicate on an Int8 key: this branch returned 179 where master, an ENGINE = Memory oracle and an ENGINE = Log oracle all raise ILLEGAL_DIVISION. The same predicate over a non-key column raises on master and on this branch, so the suppression was specific to the new swallow path rather than a general property of exact counts.
Fixed locally, not yet pushed. The generic-search callback now resets the per-range failure flag and reports the range as possibly containing a non-matching row when a chain failed, so it is still accepted but stops being exact and its rows get evaluated. That is scoped to the case where exact ranges are actually collected. I also corrected the claim at MergeTreeDataSelectExecutor.cpp:2143 that only the binary search needs to consult the flag, which your comment is anchored to.
The regression is in 04648, both directions: the failing disjunction must raise, the same predicate with the minimum excluded must match the oracle, and a healthy chain must still produce an exact range. That last one needed an EXPLAIN indexes = 1, projections = 1 assertion on Exact count optimization is applied rather than a count comparison, because a count stays correct whether or not an exact range was used.
Two more findings came out of the same review and are why this is not pushed yet. The error classification I added alongside this is still too narrow: it admits the arithmetic, conversion and parse errors I have measured, but the review has now named a third missing code, so I am inverting it to a denylist of the errors that describe the query rather than the data. I will push once that is settled.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 196/201 (97.51%) · Uncovered code |
| @@ -221,13 +221,25 @@ class MergeTreeSetIndex | |||
|
|
|||
| bool hasMonotonicFunctionsChain() const; | |||
|
|
|||
| BoolMask checkInRange(const Ranges & key_ranges, const DataTypes & data_types, bool single_point = false) const; | |||
| /// `chain_application_failed`, when given, is set to true if a monotonic function chain could not be applied to some | |||
There was a problem hiding this comment.
Not clear what returned mask is a mere over-approximation means. Please rewrite.
There was a problem hiding this comment.
You are right, that sentence does not say what the mask actually guarantees. I will replace it with:
/// `chain_application_failed`, when given, is set to true if the monotonic function chain could not be
/// evaluated on one of the analysed ranges. Such a range is treated as "may or may not match", which is
/// safe for pruning (a range that can contain matching rows is never dropped), but the mask must then
/// not be read as exact: combined under OR it can report that every row of a range matches when only
/// some of them do.
/// See KeyCondition::applyMonotonicFunctionsChainToRange.
If you want it phrased differently, give me the wording and I will use yours.
| @@ -0,0 +1,388 @@ | |||
| -- Tags: no-random-merge-tree-settings | |||
There was a problem hiding this comment.
@groeneai This test is waaaay too complex. Replace everything with a minimal reproducible example.
There was a problem hiding this comment.
Agreed: 388 lines, 25 tables, 56 queries. I will cut it to one table and the single query that reproduces the bug, in the shape of the test in #117355, and keep at most one further case for the exactness face (_exact_count_projection over OR), which goes too if that part of the PR goes. The type matrix and the EXPLAIN-reading controls go.
…ity rework Master reworked the same code paths, so all five conflicts needed both sides: - kept master's `getArgumentTypeOfMonotonicFunction` forward declaration next to the now `std::optional`-returning `applyFunctionForField`; - took master's cache-miss path, which publishes the placeholder entry before executing and preserves the function's own result type, and wrapped only the `execute` call in the try/catch - the published entry already keeps its null column on a throw, which is exactly the negative cache the lookup loop reads; - kept master's stripped-type seeding in `applyMonotonicFunctionsChainToRange` alongside the failure reporter, and dropped the now-redundant `recursiveRemoveLowCardinality` at the call site; - took master's restructured single-Tuple-key-column branch in `FUNCTION_POINT_IN_POLYGON`, and added `report_element()` to the two bail-outs master introduced there, which otherwise leave the element unreported and break this branch's "report exactly once per element, on every path out" contract. The translation unit was syntax-checked after the resolution. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units361 translation units recompiled, 3612 s compile time in total, 361 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
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. |
Related: #90461
Related: #107586 (comment)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a valid
MergeTreequery failing during primary key analysis when a monotonic function in the filter throws on some value stored in the part's primary index, even though the query's own row domain excludes that value. For exampleSELECT count() FROM t WHERE a > -50 AND intDiv(a, toInt8(-1)) = 0on anInt8key containing-128raisedILLEGAL_DIVISION, and a similar filter usingtoUnixTimestamp64Nanoon aDateTime64key raisedDECIMAL_OVERFLOW. Index analysis now treats such a failure as "cannot prune this range" instead of failing the query.Description
KeyConditionapplies a monotonic function chain speculatively over the whole in-memory index column of a part, not just over the endpoints of the range under analysis (applyFunction,src/Storages/MergeTree/KeyCondition.cpp, with its own comment "we calculate the whole column where the field comes from"). One index value on which the function throws therefore aborted the entire query. The offending value can be excluded by the query's own predicate, and it can even sit in a granule that a preceding key column already pruned. The same queries answer correctly on a table with no key at all, which is what shows the SQL is valid: index analysis is an optimisation, and its failure must degrade to "cannot prune", never fail the query.Two functions used in the tests exhibit it for different reasons:
intDivthrows for a zero divisor and for the signed minimum divided by an effective-1, andtoUnixTimestamp64NanothrowsDECIMAL_OVERFLOWnear theDateTime64maximum. The second one reports its monotonicity correctly - it is a pure monotone rescale - so this is not about inaccurate monotonicity, and a per-function guard would not close the class.The fix has three parts: the guard itself, an exactness precondition the guard makes reachable, and a latent positional bug in the skip-index disjunction accounting that the same three new routes make reachable.
applyFunctionnow reports the failure instead of letting the exception escape, andapplyMonotonicFunctionsChainToRangemaps it tostd::nullopt, the signal all four of its call sites (bothKeyCondition::checkInHyperrectangleoverloads and bothMergeTreeSetIndex::checkInRangeoverloads) already treat as "monotonicity unknown on this range" by answering(true, true). The cache entry is published only after a successful execute, plus an explicit sticky negative entry: on master the entry was emplaced with a null column before the execute that can throw, the probe loop matches on the name alone, andFieldRef's constructor dereferences the column unconditionally, so a second probe over the same part would read a half-built entry. That cache is shared for the whole part, so this is reachable. The in-tree constant-transform path inapplyDeterministicDagToColumn, in the same file, already does exactly this, with a comment naming the same bug class (ORDER BY toUUID(p)wherepis aString).That alone is not sufficient.
matchesExactContinuousRangeasks only whether every chain function is always monotonic, andmarkRangesFromPKRangevalidates that promise against the ranges it actually produced, raisingLOGICAL_ERROR: Inconsistent KeyCondition behaviorin debug and sanitizer builds when contradicted. Exactness however requires both that the chain is always monotonic and that it was successfully applied: thenulloptfallback yields(true, true), which is a correct over-approximation for pruning but by construction is not exact. On master the exception hid this by failing the query first, so removing it makes the contradiction reachable. An explicit status flag is therefore propagated fromapplyMonotonicFunctionsChainToRangethrough bothKeyCondition::checkInRangeandKeyCondition::checkInHyperrectangleoverloads and bothMergeTreeSetIndex::checkInRangeoverloads, and consulted per analysedpart_range: a range whose chain could not be applied records no exact range and reports no inconsistency, while ranges that analysed cleanly keep contributing exact ranges. The honest "not monotonic on this range" answer deliberately does not set the flag, so the invariant check still fires unchanged for a genuine monotonicity lie - verified against the reproducer of #111421, which aborts identically before and after this change. The new parameter is trailing and defaulted, so every call site that does not need it compiles unchanged; the ones that keep the default (the Parquet reader,StorageHive, the minmax and set skip indexes, the statistics part pruner,StorageMergeTreeTextIndex, the partition-minmax checks andmayBeTrueInRange) all consume onlycan_be_true, so none of them can derive an exactness claim the flag would have to correct.This mirrors the pre-existing escape at the top of the same function, which already stops filling exact ranges when any of the participating conditions is relaxed, for the same reason: an analysis that was weakened cannot support
BoolMask::can_be_false. The difference is only in granularity -isRelaxed()is a property of the whole condition and is therefore checked once per part, while whether a chain throws depends on the endpoint values and so is decided per analysed range.The third part is a second, pre-existing bug in the same function, fixed here because these changes make it reachable.
KeyCondition::checkInHyperrectanglereports each atom's per-granule verdict to the partial-disjunction bitset from a counter incremented at the bottom of its per-element loop, whileMergeTreeDataSelectExecutorindexes that bitset positionally, both when writing it and when re-evaluating the expression inmergePartialResultsForDisjunctions. Every one of the loop's seven early exits skips both the report and the increment, so from the first skipped element on, the counter trails the element's real position in the RPN and one atom's verdict is read out of another atom's bit. The bitset starts out all-true, so an unwritten position reads as "this atom may be true": the merged expression is not the query's and a granule that cannot match survives. On master that exit is reachable only for an honestly non-monotonic chain; this change adds three more routes to it (a throwinggetMonotonicityForRange, a throwing explicit-field transform, a throwing whole-column transform), which are exactly the queries it makes work. The position is now derived from the loop index and reported through one helper that every path out of the body calls, so the callback runs exactly once per element with that element's own index; chasing the seven exits with an extra increment each would leave the next added one broken again. The effect is under-pruning, not a wrong result, so04648asserts the combined granule count for that shape: 6/8 with the position keyed on the RPN index, 7/8 with it shifted. The sibling reporting loops inMergeTreeIndexBloomFilterText,MergeTreeIndexConditionTextandMergeTreeIndexBloomFilteruse the same counter pattern but have no early exit inside the loop, so they are unaffected and unchanged.Neither related link is a
Closes:. #90461 is the closed umbrella tracker for this consistency check's false positives, and this change fixes one precondition it did not model rather than the whole class. The review comment on #107586 is where the defect surfaced; it is a comment, not an issue.Deliberately out of scope, so a reader is not left wondering:
KeyCondition.cpphas a third analysis-time function execution, inapplyFunctionChainToColumn, and it is left throwing. That one transforms the query's own literal (a single row) rather than the part's index column, which is a different input class from the one this change is about, and the constructor already documents throws from that build-time path as a known hazard routed around byuse_primary_key = 0rather than by a catch. Its sibling constant pathapplyDeterministicDagToColumnis guarded, so a follow-up may want to converge the two; it is not bundled here.intDivreportsis_always_monotonicfor a range containing the signed-domain minimum when the effective divisor is-1, which mis-prunes a matching row atInt32/Int64width and silently returns a wrongcount(). It is fixed separately in Fix wrong results for intDiv by an effective -1 in key analysis #112151, and this PR does not assert result correctness for those shapes. The two do not overlap: that fix is keyed onInt32/Int64dividends, while everyintDivcase here uses anInt8orInt16key, so neither changes the other's assertions whichever merges first.Workflow [PR]
Sync PR [sync-upstream/pr/112231]