Skip to content

Do not fail a query when key analysis cannot apply a monotonic chain - #112231

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-key-analysis-throwing-monotonic-chain
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-key-analysis-throwing-monotonic-chain

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #90461
Related: #107586 (comment)

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 into CHANGELOG.md):

Fixed a valid MergeTree query 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 example SELECT count() FROM t WHERE a > -50 AND intDiv(a, toInt8(-1)) = 0 on an Int8 key containing -128 raised ILLEGAL_DIVISION, and a similar filter using toUnixTimestamp64Nano on a DateTime64 key raised DECIMAL_OVERFLOW. Index analysis now treats such a failure as "cannot prune this range" instead of failing the query.

Description

KeyCondition applies 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: intDiv throws for a zero divisor and for the signed minimum divided by an effective -1, and toUnixTimestamp64Nano throws DECIMAL_OVERFLOW near the DateTime64 maximum. 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.

applyFunction now reports the failure instead of letting the exception escape, and applyMonotonicFunctionsChainToRange maps it to std::nullopt, the signal all four of its call sites (both KeyCondition::checkInHyperrectangle overloads and both MergeTreeSetIndex::checkInRange overloads) 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, and FieldRef'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 in applyDeterministicDagToColumn, in the same file, already does exactly this, with a comment naming the same bug class (ORDER BY toUUID(p) where p is a String).

That alone is not sufficient. matchesExactContinuousRange asks only whether every chain function is always monotonic, and markRangesFromPKRange validates that promise against the ranges it actually produced, raising LOGICAL_ERROR: Inconsistent KeyCondition behavior in debug and sanitizer builds when contradicted. Exactness however requires both that the chain is always monotonic and that it was successfully applied: the nullopt fallback 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 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 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 and mayBeTrueInRange) all consume only can_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::checkInHyperrectangle reports each atom's per-granule verdict to the partial-disjunction bitset from a counter incremented at the bottom of its per-element loop, while MergeTreeDataSelectExecutor indexes that bitset positionally, both when writing it and when re-evaluating the expression in mergePartialResultsForDisjunctions. 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 throwing getMonotonicityForRange, 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, so 04648 asserts 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 in MergeTreeIndexBloomFilterText, MergeTreeIndexConditionText and MergeTreeIndexBloomFilter use 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.cpp has a third analysis-time function execution, in applyFunctionChainToColumn, 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 by use_primary_key = 0 rather than by a catch. Its sibling constant path applyDeterministicDagToColumn is guarded, so a follow-up may want to converge the two; it is not bundled here.
  • A separate, independent defect found while investigating this one: intDiv reports is_always_monotonic for a range containing the signed-domain minimum when the effective divisor is -1, which mis-prunes a matching row at Int32/Int64 width and silently returns a wrong count(). 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 on Int32/Int64 dividends, while every intDiv case here uses an Int8 or Int16 key, so neither changes the other's assertions whichever merges first.

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

groeneai and others added 6 commits July 27, 2026 10:25
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
six approach-review rounds against the plan. Each round's findings were adjudicated against code and
measurement, and the accepted ones were fixed in a further commit before the next round. The final
round returned no findings.

Rounds: 6 approach rounds (5 findings) and 6 diff rounds (40 findings: 28 accepted, 6 rejected
with evidence, 6 dropped as already-correct). Five fix commits sit on top of the original fix.

Accepted and fixed

# Finding Fix
❌ The nullopt fallback makes matchesExactContinuousRange's promise reachable-and-false, so markRangesFromPKRange would raise LOGICAL_ERROR: Inconsistent KeyCondition behavior in debug and sanitizer builds for exactly the queries this change makes work Added the chain_application_failed status flag through both KeyCondition::checkInRange/checkInHyperrectangle overload families and both MergeTreeSetIndex::checkInRange overloads, consulted per analysed mark range
❌ The early exit the fallback takes also skips the partial-disjunction callback and its counter, so from the first skipped element on, one atom's per-granule verdict is read out of another atom's bit and a granule that cannot match survives The position is now the element's own index in the RPN, reported through one helper that every path out of the loop body calls
⚠️ The whole-column cache entry was emplaced with a null column before the execute that can throw, and FieldRef's constructor dereferences the column unconditionally, so a second probe over the same part could read a half-built entry Publish the entry only after a successful execute, plus an explicit sticky negative entry that later probes return on
⚠️ toUnixTimestamp64Nano overflows only past 2262-04-11 23:47:16.854 UTC, and CI randomizes both the server and the session timezone, so on roughly half of all runs that case asserted nothing about this change Pinned 'UTC' on the column type and on the comparison bound, with the margin recorded in the test comment
⚠️ The exact-range and granule-count controls depend on settings the CI runner randomizes (optimize_use_projections, optimize_use_implicit_projections, optimize_aggregation_in_order, parallel_replicas_local_plan, use_lightweight_primary_key_index_analysis), each of which measurably flips an assertion to 0 at its hostile value Statement-level SETTINGS on the statements that need them, so every other case still runs under whatever the runner drew
⚠️ Both primary key representations and both set-index call sites were left to a coin flip Each shape is emitted once per representation, with getSetting('use_lightweight_primary_key_index_analysis') in the output so the reference proves which ran
⚠️ The healthy-chain controls only proved pruning survived, never that the flag stays clear after a successful transform, so a regression that set it unconditionally would have kept every count correct while silently losing exact ranges for all chain-based predicates Four exact-count controls driven through a cleanly-applying chain, one per representation and per spelling
⚠️ Only the transform half of the change was pinned: with the try around getMonotonicityForRange removed, the whole test stayed green Added a Decimal64 case where plus by a constant overflows while deciding monotonicity; route confirmed by instrumenting all three catch sites, and with that guard removed the suite now stops exactly at the new case
💡 A comment justified the statement-level SETTINGS with a claim about session-SET-versus-runner precedence that is backwards, and another cited a test count that no predicate reproduces Both corrected; the count is gone rather than replaced
💡 This PR's description named a count of unchanged call sites that was arithmetically right but read as a claim about production code Replaced by naming the call sites that keep the default and why each is safe

Rejected, with evidence

# Finding Why not
❌ Fold the honest "not monotonic on this range" answer into the same failure signal That would disarm the consistency check for a genuine monotonicity lie. The two are kept distinct on purpose, and the check still fires unchanged, verified against an independent reproducer of #111421
⚠️ A fix plan asked to delete a randomization claim from the explain_query_plan_default comment The sentence quoted is one paragraph earlier and belongs to query_plan_merge_filters, where it is true (tests/clickhouse-test:1582, default true). The explain_query_plan_default block never made that claim, so there was nothing to delete and deleting the quoted line would have introduced an error
⚠️ The intDiv cases here might stop exercising the fallback if #112151 (a separate fix making intDiv(signed, -1) report non-monotonic) merges first #112151 gates on an Int32/Int64 dividend, because only those specializations take the FPE-suppressing vectorized path (src/Functions/intDiv.cpp:124-132 registers no Int8/Int16 dividend). Every intDiv case here uses an Int8 or Int16 key, so merge order changes nothing in either direction
⚠️ Three further reports that a control was dead Each was shown live by a mutation: reverting the specific line moves the reference by a measured number of rows

Noted, not blocking

  • KeyCondition.cpp has a third analysis-time function execution, in applyFunctionChainToColumn,
    left throwing and disclosed in the description; its sibling constant path is already guarded, so a
    follow-up may want to converge the two.
  • One more carrier reaches the guarded call rather than needing its own guard:
    LLVMFunction::getMonotonicityForRange (src/Interpreters/ExpressionJIT.cpp:253-289) recurses into
    nested monotonicity implementations and calls its own unguarded func->execute, so a throw from
    either is caught by the new try here.
  • The stateless test number 04648 is shared with an existing test and with Fix wrong results for intDiv by an effective -1 in key analysis #112151. Harmless:
    check_gaps_in_tests_numbers flags only consecutive gaps, never collisions.

Verification carried over each round

Deterministic failure on the merge base and success on the fix build for every bug case, with an
ENGINE = Memory twin as oracle; 50 randomized plus 50 non-randomized runs of the test through the
real harness, all passing; a per-round mutation matrix in which each pinned line and each of the
three catch sites is reverted individually and the reference is shown to move; and the server's
buildId() compared against the binary's ELF note before every measurement.

Session id: cron:clickhouse-review-slot-54:20260728-062700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (a Int8) ENGINE=MergeTree ORDER BY a SETTINGS index_granularity=1; INSERT INTO t VALUES (-128),(-100),(-50),(50); SELECT count() FROM t WHERE a > -50 AND intDiv(a, toInt8(-1)) = 0; - Code: 153 ILLEGAL_DIVISION on master, 100% of runs. The same query on ENGINE = Memory returns 0 and is the oracle showing the SQL is valid.
b Root cause explained? Yes. applyFunction evaluates the monotonic chain over the WHOLE in-memory index column of a part, so an index value that no analysed range contains can make the function throw and the exception escapes key analysis and fails the query. Separately, matchesExactContinuousRange derives an exactness promise from always-monotonicity alone, while the std::nullopt over-approximation the fix now returns is by construction not exact - so with the exception gone, the #ifndef NDEBUG consistency check in markRangesFromPKRange starts contradicting itself.
c Fix matches root cause? Yes. applyFunction reports the failure at the layer that produces the over-approximation, and the exactness gate consults the precondition the check did not model. No widened bound, no blanket no-random-* tag, no dataset reduction, no defensive check masking an upstream bug. The consistency check itself is neither deleted nor broadened.
d Test intent preserved / new tests added? New stateless test 04648_key_analysis_throwing_monotonic_chain (16 bug cases, 9 negative controls, and one two-skip-index disjunction case covering the RPN position accounting). No existing case was changed to make the new one pass. No existing test weakened or removed. The invariant check is narrowed by exactly one precondition and still fires for a genuine monotonicity lie - verified against the reproducer of #111421, which aborts identically before and after. Every setting the test's own coverage depends on is pinned per statement, and each pin was verified load-bearing by measuring its hostile value: without them the exact-range cases silently degrade into duplicates of the earlier ones, the DECIMAL_OVERFLOW case stops throwing under a randomized timezone, and the closing controls report 0. There is deliberately no blanket no-random-settings tag - the bug cases keep the randomized coverage that found two of the pins in the first place.
e Both directions demonstrated? Yes, statement by statement (the file aborts on master, so a whole-file diff would mask everything after the first case). All 16 bug cases: rc=153/rc=151/rc=407 on master, rc=0 with the expected count on the fix. Whole-file runs of the committed test: master rc=153 at case 1, the Piece-1-only mutant rc=134 Logical error: 'Inconsistent KeyCondition behavior', the fix rc=0 matching the reference. Nine mutation tests, each predicted before running; the ones that do not discriminate target code paths shown to be unreachable from SQL (reported as code-path arguments rather than as vacuous tests). With the Piece-2 gate removed, every pinned exact-range statement that asserts a count aborts - and all of them pass once the projection pins are removed, which is what proves the pins are what make the gate reachable. Reporting the flag on a SUCCESSFUL chain application flips exactly the four healthy-chain exact-count rows to 0 and leaves every pre-existing assertion in the file passing, including the raw-key exact-count control that structurally cannot see it. After the mutations the restored build had a bit-identical Build ID. A later round added a Decimal64 case for the third throw route, where plus throws while its monotonicity is being DECIDED rather than while the chain is applied: with only that guard removed the suite stops exactly at that case and every earlier case is byte-unchanged, and instrumenting all three catch sites confirms the new case reaches that route while the existing intDiv cases reach only the whole-column transform.
f Fix is general across code paths? Yes. Both KeyCondition::checkInHyperrectangle overloads, both KeyCondition::checkInRange overloads, both MergeTreeSetIndex::checkInRange overloads, the applyFunctionForField explicit-field path, getMonotonicityForRange, and the single_point partition path are all covered; the flag is passed at all three condition calls in markRangesFromPKRange (key, _part_offset, total offset) because they are combined into the single BoolMask the check consumes. Fixed at the source, not guarded at the crash site. The skip-index disjunction callback is keyed structurally rather than per branch: the position comes from the loop index, so all seven early exits in that loop report correctly and a future eighth cannot desynchronise it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Int8, Int16, UInt64, LowCardinality(Int8) and DateTime64(3, 'UTC') keys; intDiv by an effective -1, intDiv by zero, and toUnixTimestamp64Nano overflow; the = and IN spellings; index_granularity = 1 and the default granularity; single-key, multi-key and PARTITION BY shapes; binary search and generic exclusion search; and both primary-key representations - use_lightweight_primary_key_index_analysis selects between the two checkInRange/checkInHyperrectangle overload families this PR edits, so both the range and the IN exact-range shapes are emitted once per family (the set index has its own call site inside each family) with the value in effect asserted in the reference, and all four abort under the Piece-2-gate-removed mutant while only the two IN rows abort when the flag is dropped from MergeTreeSetIndex::checkInRange alone.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no SettingsChangesHistory.cpp entry, no serialization, format or protocol change, no experimental gate. Every new parameter is trailing and defaulted, so the 34 other call sites of these functions compile unchanged (verified by building with zero edits to them). Strictly fewer failures than before.
i Invariants and contracts preserved? Yes. applyMonotonicFunctionsChainToRange mutates only its by-value key_range copy, so returning {} discards it with no side effect. The cache entry is published only once complete and the sticky negative entry is recognised by the probe loop before any FieldRef is constructed on it - a mutation restoring master's ordering aborts, so this is load-bearing. That the negative entry actually bounds re-execution was measured, not argued: on two builds differing only in the line recording it, with identical instrumentation at the transform site, the whole-column transform is attempted 1 time (build 1ba129d09a5480fb) against 9 (build ef897abc7f718e30), with the same query result. The property has no SQL surface to assert on - KeyCondition.cpp emits no ProfileEvents, applyFunction is file-static, and no system table exposes that per-column cache - so the instrumented pair is the evidence rather than a test case. Only const Exception & is caught, never .... The honest "not monotonic on this range" answer deliberately does not set the flag, so the flag stays narrow. Omitting exact ranges is safe by the consumer's own contract, which only requires each listed range to lie inside some range. The flag is reset per analysed range, which only the binary search consults: the generic exclusion search derives exactness from the mask itself, so an over-approximated mask there already yields no exact range and no promise to contradict - now stated at the declaration. The success path is unchanged, pinned by a control asserting that a set-index chain which applies cleanly still prunes to the same granule count as its range sibling: making MergeTreeSetIndex::checkInRange decline analysis flips that plan to Granules: 100/100 while the IN result counts stay correct, which is why nothing else in the file could see that regression. The exactness half of the success path is pinned too: four controls drive the exact-count optimization through a cleanly applied chain, once per primary key representation and once per spelling, and reporting the flag after a successful transform is what flips them. The disjunction callback's contract - exactly one report per RPN element, at that element's own index - is now structural; shifting the reported position by one flips the new granule assertion in both primary key representations, and dropping the reports on the early exits flips it too. No lock or concurrency contract is touched.

Session id: cron:clickhouse-impl-slot-6:20260727-231000

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 (ILLEGAL_DIVISION for intDiv by an effective -1, DECIMAL_OVERFLOW for toUnixTimestamp64Nano); the chain application now degrades to "cannot prune this range", which also required teaching the exact-range path that an unapplied chain carries no exactness guarantee.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ab56c8]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) ERROR
test_parallel_replicas_over_distributed/test.py::test_parallel_replicas_over_distributed[test_multiple_shards_multiple_replicas-10-1] FAIL cidb
test_named_collections/test.py::test_concurrent_create_drop_race_condition FAIL cidb
test_hedged_requests/test.py::test_async_query_sending FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_input_with_old_setting FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_output_with_old_setting FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_input_with_format_schema_source[file] FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_input_with_format_schema_source[string] FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_input_with_format_schema_source[query] FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_output_with_format_schema_source[file] FAIL cidb
test_format_schema_source/test.py::test_protobuf_format_output_with_format_schema_source[string] FAIL cidb
9 more test cases not shown
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This 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 OR as exact and answer count() from _exact_count_projection instead of raising the original exception.

Findings
❌ Blockers
  • [src/Storages/MergeTree/KeyCondition.cpp:1597-1599, 1661-1666, 5234-5239] The three new catch (const Exception &) sites turn every DB::Exception into "cannot prune". That also swallows resource failures such as MEMORY_LIMIT_EXCEEDED / CANNOT_ALLOCATE_MEMORY; on the whole-column path it additionally leaves the negative cache entry behind for the rest of markRangesFromPKRange, so a transient OOM changes a failing query into a full scan. Suggested fix: rethrow resource/control/internal codes here and degrade only the data-domain exceptions that intentionally mean "this key value cannot be analyzed".
  • [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:2208-2212, 2411-2419] chain_application_failed is consulted only in the binary-search exact-range path. genericExclusionSearch still records exact ranges from !mask.can_be_false, so a failed chain under OR can still collapse to an exact mask, e.g. (true, true) | (true, false) == (true, false) for intDiv(a, toInt8(-1)) = 0 OR a <= 50. That lets _exact_count_projection return a count instead of raising ILLEGAL_DIVISION. Suggested fix: when exact ranges are being collected in generic search, force the range to stay inexact if any participating condition set chain_application_failed, or thread that flag into the generic-search exactness decision directly.
Tests
  • ⚠️ tests/queries/0_stateless/04648_key_analysis_throwing_monotonic_chain.sql still does not cover the generic-exclusion exact-count OR shape above, so the second blocker can merge green.
  • ⚠️ There is still no focused regression that proves MEMORY_LIMIT_EXCEEDED / CANNOT_ALLOCATE_MEMORY propagates through these new fail-soft paths instead of silently falling back to a full scan.
Final Verdict

❌ Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
result_column = func->execute(args, result_type, args.front().column->size(), /* dry_run = */ false)
->convertToFullColumnIfLowCardinality();
}
catch (const Exception &)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 &)
{

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.

@groeneai is it safe to ignore the exception here? Is the exception logged somewhere?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

@groeneai Do not swallow exceptions.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 271c59a

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy) / Build ClickHouse PR-caused clang-tidy error: src/Storages/MergeTree/KeyCondition.cpp:1833 — two performance-move-const-arg violations (std::move passed as a const reference argument, so no move happens); warnings are errors in this build fixed in this PR
Finish Workflow / Post Hooks new_tests_check.py gate: every per-arch Bugfix validation job is DROPPED or SKIPPED, so the new test was never measured against master HEAD — a consequence of the failure above, not a test-design defect fixed in this PR

Session id: cron:our-pr-ci-monitor:20260729-043000

@yariks5s yariks5s left a comment

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.

@groeneai Please check the CI, tidy build has failed.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 2ccb5ee.

The red was mine. ColumnWithTypeAndName's three-argument constructor takes every parameter by const reference (src/Core/ColumnWithTypeAndName.h:27), so the two std::move calls I had on KeyCondition.cpp:1833 could never move anything, and clang-tidy reports performance-move-const-arg twice for that one line. Dropping them is codegen-identical. Reproduced locally with clang-tidy-21 over the file: two errors at 1833:53 and 1833:79 before, zero after, and no other finding under the full enabled checkset. Test 04648 still matches its reference byte for byte.

Finish Workflow was the only other red and it should clear with this: it failed because every per-arch Bugfix validation job was dropped, so new_tests_check.py never measured the new test.

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 179. On master, and on ENGINE = Memory, it raises ILLEGAL_DIVISION, which is the correct answer. The mechanism is that a failed monotonic chain yields (true, true), and OR-ing that with an atom known true collapses it to (true, false); the generic exclusion search then records the range as exact, _exact_count_projection answers from the index, and no row is ever evaluated. My comment at MergeTreeDataSelectExecutor.cpp:2143 claims the generic search needs no chain_application_failed check because an over-approximated mask yields no exact range, and that reasoning is wrong for the disjunction case.

I am fixing that together with the exception classification I already owe @ PedroTadim and the review bot on this PR (classify on e.code() in all three new catches, rethrow anything that is not a data-domain error, keep ILLEGAL_DIVISION and DECIMAL_OVERFLOW degrading to "cannot prune"), and I will add this disjunction shape as a test case. So please hold off merging until that lands; the CI should be green meanwhile.

/// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 196/201 (97.51%) · Uncovered code

Full report · Diff report

Comment thread src/Interpreters/Set.h
@@ -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

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.

Not clear what returned mask is a mere over-approximation means. Please rewrite.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

@groeneai This test is waaaay too complex. Replace everything with a minimal reproducible example.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5ab56c88b with master b20c66c27 (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
Binary Master PR Δ
programs/clickhouse-stripped 710.36 MiB 707.30 MiB -3.05 MiB (-0.43%)

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 units

361 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.
The matched translation units cost +275.1 s (+8%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 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.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@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 19, 2026

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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants