Repository navigation
Don't merge clauses with FUNCTION_UNKNOWN in ConditionSelectivityEstimator - #118137
Conversation
A predicate the estimator cannot analyse - a comparison between two columns, an unsupported function, an `IN` set that is not built - becomes a `FUNCTION_UNKNOWN` atom, which `finalize` estimates with `default_unknown_cond_factor`. `tryToMergeClauses` accepted such an atom as mergeable. Merging only carries ranges across, and an unknown atom has none, so it was absorbed without trace: the merged clause got the ranges of the other side alone, and the unknown predicate ended up contributing a selectivity of 1. Where both sides were unknown, the merged clause had no ranges at all and `finalize` returned the AND identity, so the estimate degraded to the full table - a relation was estimated *less* selectively the more unanalysable conditions were added to it. Leave `FUNCTION_UNKNOWN` unmergeable so it takes the branch that finalizes both sides and multiplies them, as every other non-mergeable atom already does. Two unknown conjuncts now estimate at `default_unknown_cond_factor` squared instead of 1. The defaults compound under the usual independence assumption, which is the same treatment a range atom on a column without statistics gets. Found while investigating a reported join-order change, where the full-table estimate came from this path rather than from the `IN` predicate that appeared to cause it. Co-Authored-By: Claude Opus 5 <[email protected]>
Review feedback on the previous commit: the assertions only checked that the estimate was below the table size, which catches the old "degrades to the whole table" failure but does not state the invariant, and `toUInt64OrZero` returns 0 when the extraction misses - so a broken test would have passed vacuously. Capture each estimate and compare them against one another instead of against a fixed number, so the assertions survive a change to the default factors, and use `toUInt64OrNull` plus an explicit non-zero check so a failed extraction shows up as a null rather than as a pass. Cover disjunction as well: `tryToMergeClauses` gates both `FUNCTION_AND` and `FUNCTION_OR`, and dropping an unknown atom is worse in a disjunction, where the merged clause finalized to the `OR` identity. On the table used here the previous behaviour estimated `unknown OR unknown` at 0 rows, and `range OR unknown` exactly as the range alone. Pin the join-order settings the estimates are read from. Settings randomization turns the optimizer off (`query_plan_optimize_join_order_limit = 0`), replaces the statistics with random cardinalities (`query_plan_optimize_join_order_randomize`), and lets measured row counts override them (`use_hash_table_stats_for_join_reordering`); without pinning, the test failed every one of 20 randomized runs. Verified that all five assertions still fail without the estimator fix and pass with it, and that the test passes 20 runs with settings randomization and 10 without. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [7720820] Summary: ✅
AI ReviewSummaryThis PR tightens Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 7720820.
Changed lines: Changed C/C++ lines covered: 53/61 (86.89%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units372 translation units recompiled, 3451 s compile time in total, 372 of them have a recent master baseline. |
FUNCTION_UNKNOWNFUNCTION_UNKNOWN in ConditionSelectivityEstimator
|
Some of the test issues apparently triggered by the added tests. Fixing here: #118756 |
The test read its five estimates through five `WITH` aliases, each wrapping an `EXPLAIN` subquery. With the old analyzer, `ApplyWithAliasVisitor` propagates an outer `WITH` alias by cloning it into every descendant subquery, and an alias whose subquery contains a further `SELECT` is expanded again at each level, so five such aliases expand exponentially: the CI job that runs with the old analyzer grew to tens of gigabytes and was killed by the OOM reaper, and the AST fuzzer - which draws its queries from the tests a change touches - hit the same shape. Insert each estimate into a small table instead. The assertions are unchanged, and so is the reference; only the way the estimates are collected differs. Verified that four of the five assertions still fail without the estimator fix, so the test has lost none of its power, and that a run now leaves the server's resident memory where it found it under both analyzers. The underlying expansion is bounded separately, in `ApplyWithAliasVisitor`; this commit only stops the test from relying on the construct. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Leaving `FUNCTION_UNKNOWN` unmergeable stopped it from vanishing, but it also made the estimate depend on the order the conjuncts were written in. An unmergeable operand sends both sides down the branch that finalizes them, so a range separated from an earlier range on the same column by an unknown atom could no longer merge with it, and the two bounds were estimated as independent factors instead of as their intersection: WHERE b > 1000 AND b > c AND b < 2000 -> P(b > 1000) * f * P(b < 2000) WHERE b > 1000 AND b < 2000 AND b > c -> P(1000 < b < 2000) * f On a 100000-row table with `b` uniform over `[0, 50000)` that is 426 rows versus 217, and the join order changes with it. `master` does not have this: an unknown atom was mergeable there, so it never interrupted a chain of ranges. An unknown atom carries no range, so a merge cannot represent it as one - but under `AND` it does not have to. Its selectivity is a constant factor, so keep it aside in `absorbed_and_selectivity` and let `finalize` apply it once the ranges it was interleaved with have been merged and estimated together. All six orderings of the predicate above now estimate 217. This is only valid under `AND`: `P(a OR unknown)` is not `P(a) * f`, so under `OR` an unknown atom stays unmergeable and is finalized as its own operand, and a clause that has already absorbed one refuses to merge into a disjunction. `NOT` is handled by finalizing such a clause first, since `NOT (a AND u)` is `NOT a OR NOT u` rather than the flipped ranges times the same factor. Two unknown conjuncts still estimate at `default_unknown_cond_factor` squared, and a predicate with no unknown atom is untouched. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
`indexHint` keeps a copy of the conditions that were moved to `PREWHERE`, so that index analysis can still see them, and returns 1 for every row. `RPNBuilder` maps it to `FUNCTION_AND` and descends into that copy, which is what consumers analysing indexes need. `ConditionSelectivityEstimator` is not one of them: the conditions are already in the expression it is estimating, so it counted each of them a second time. A conjunction therefore came out more selective than the product of its parts: b < 1000 1998 rows of 100000 b > c 33000 b < 1000 AND b > c 217 expected 1998 * 33000 / 100000 = 659 and how much more depended on how many hints the plan happened to carry, so the same predicate written with its conjuncts in a different order, or parenthesised differently, could get a different estimate and a different join order. Give `RPNBuilder` an `expand_index_hint` flag, on by default. The estimator passes it off and gets an `ALWAYS_TRUE` leaf, which is what `indexHint` evaluates to anyway; `KeyCondition` and the skip-index conditions are unaffected. `master` mostly hid this: an unknown atom was mergeable there, so a duplicated one was absorbed and contributed 1. Once an unknown atom is estimated rather than absorbed, every duplicate costs another `default_unknown_cond_factor`. With this, all six orderings and all eight parenthesisations of the predicates in `05079` and in the report below estimate the same, including one grouping that `master` itself gets wrong. Related: #119249 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Whether to descend into `indexHint` never varies between two uses of the same `RPNBuilder` specialisation: analysing indexes always wants the hint's contents, estimating selectivity never does. Carrying it as a constructor argument made every call site restate the same answer, and let them disagree. Declare it once as `RPNBuilderTraits<RPNElement>::expand_index_hint`, specialised for `ConditionSelectivityEstimator::RPNElement` next to the explicit instantiations, where all the consumers are listed together. The constructors and the estimator's call sites go back to what they were. The flag cannot instead live on the `indexHint` node itself. Two consumers need opposite treatment of the same node, which a property of the node cannot express, and the provenance of the hint is not the relevant signal either: a hint written by hand in a query is derived from nothing, yet still returns 1 for every row and still has to be estimated at selectivity 1. No behaviour change: the same predicates estimate the same as in the previous commit, and the same broad `prewhere`/`index`/`skip_index` suite has the same failures as without the change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
The comment justified the trait by saying a hint is "a condition that filters nothing", which overstates it. A hint removes no rows - the function evaluates to 1 for every row - but it is not inert: it takes part in index analysis and prunes the read set, so a relation under one really can yield fewer rows than a selectivity-based estimate suggests. On a 100000-row table ordered by `b`, granularity 8192, both of these read 8192 rows from storage; only the first then removes any: WHERE b < 1000 8192 read, 1000 fed onward, estimated 999 WHERE indexHint(b < 1000) 8192 read, 8192 fed onward, estimated 100000 `ALWAYS_TRUE` is right about the number of rows the condition removes, which is what a selectivity estimate is. The 12x gap in the second line is not something the trait could fix: `ConditionSelectivityEstimator` estimates `total_rows * selectivity`, and `total_rows` sums whole parts, so mark ranges the index did not select are counted anyway - for every predicate, not just hints. It stays invisible for an executable predicate because the filter removes those rows regardless, which is why the first line is correct. Pruning is carried by a separate estimate, `RowEstimateSource::PrimaryIndex`, used only when column statistics are missing. Comment only; no behaviour change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
`86f1341` made a conjunction absorb an unknown atom as a constant factor, and had to handle `NOT` specially: such a clause is a conjunction times that factor, and `NOT (a AND u)` is `NOT a OR NOT u`, not the flipped ranges times the same factor. It is finalized before the negation so `NOT` applies to a plain selectivity. Nothing exercised that. The test asserts the estimate for a negated clause and the estimate for the clause itself add up to the table, since `P(NOT x) = 1 - P(x)`, and does the same for a plain range as a control - the control goes down the other branch, which negates by flipping the ranges. Dropping the special case makes only the first assertion fail, which is what makes the control worth having. On the fixture the negation comes out at 32340 rather than 99340: the absorbed factor stays applied to the complement, so the result is `(1 - 0.02) * 0.33` instead of `1 - 0.02 * 0.33`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
`FUNCTION_NOT` negates an unfinalized element by swapping its ranges with its not-ranges and flipping `AND` to `OR`. An element with no ranges has nothing to swap, and the switch has no case for `FUNCTION_UNKNOWN`, so a negated unknown atom came out of `NOT` byte for byte unchanged and went on to report the selectivity of the un-negated predicate: b > c 33000 rows of 100000 NOT (b > c) 33000 should be 67000 It also spread: the negated atom was absorbed by a surrounding conjunction as if it were positive, so `NOT (b > c) AND b < 1000` estimated 659 instead of 1339. `master` loses the negation the same way - the switch predates this branch - but absorbed it into nothing rather than into a factor. Finalize such an element before negating, alongside the clause-with-an-absorbed-factor case that was already handled. That alone would make it unmergeable afterwards, and the ranges on either side of it would stop merging, which is the order-dependence this branch removed two commits ago. So absorption is widened at the same time: any operand carrying no ranges is a bare factor and is absorbed under `AND`, whether or not it has been finalized. That covers `LIKE` too, which is finalized with a default selectivity and no ranges. It was splitting ranges the same way: b > 1000 AND s LIKE '%7%' AND b < 2000 391 -> 199 b > 1000 AND b < 2000 AND s LIKE '%7%' 199 -> 199 `05082` asserts a negated unknown is the complement of the un-negated one, composes with a range as its own estimate, and does not split the ranges around it. The three fail separately: without any fix the first fails; with only the `NOT` change and no widened absorption the third fails. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
`ALWAYS_TRUE` and `ALWAYS_FALSE` carry no ranges, so the previous commit's `isConstantFactor` matched them and `FUNCTION_NOT` finalized them instead of letting the switch flip the tag. `finalize` only sets `selectivity`, so the element came out with a number saying one thing and a `function` saying the opposite - and the `AND`/`OR` folding reads the tag, not the number: NOT (indexHint(b < 1000)) AND b < 1000 1998 rows estimated, 0 true NOT (indexHint(b < 1000)) OR b < 1000 0 rows estimated, 2000 true The conjunction was estimated as the range alone because the stale `ALWAYS_TRUE` made the fold drop the negated operand, and the disjunction collapsed onto that operand's zero selectivity for the same reason. Exclude both tags from `isConstantFactor`. They are not factors to be absorbed but operands the folding recognises by tag, and `NOT` already flips them correctly. Everything the previous commit fixed still holds: a negated unknown is still its complement, and ranges on either side of one still merge. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
`finalize` folds `absorbed_and_selectivity` into `selectivity` but left it populated, so a clause that was finalized in place and then took part in another conjunction had it applied twice: once carried over by the merge, once inside the result it was already part of. `FUNCTION_NOT` is how a clause gets finalized in place. For NOT (b > c AND a > c) AND b < 1000 the negated pair is `1 - f^2` and the conjunction should be `(1 - f^2) * P(b < 1000)`, but the merge carried `f^2` over as well and the estimate came out an order of magnitude low - 193 rows against 1780 on the fixture. Take the factor at the top of `finalize` and clear it there. Every exit then leaves the clause as a plain number, which is what a later merge must use and all it must use. Doing it once at the top rather than at each exit also covers the two that return early. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AY5AruBhLm6D56ddssiXXQ
Changelog category (leave one):
Following up this investigation.
Workflow [PR]
Sync PR [sync-upstream/pr/118137]