Skip to content

Fix exception in ConditionSelectivityEstimator for IN with a single s… - #99614

Merged
rschu1ze merged 12 commits into
masterfrom
fix-statistics-in-single-param
Mar 23, 2026
Merged

rschu1ze merged 12 commits into
masterfrom
fix-statistics-in-single-param

Conversation

@qoega

@qoega qoega commented Mar 16, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

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

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

Fixed an exception (Bad get: has Tuple, actual type String) in ConditionSelectivityEstimator when a query uses IN with a single scalar query parameter (e.g. WHERE col IN ({p:String})) on a table that has column statistics and use_statistics is enabled.

Version info

  • Merged into: 26.4.1.171

…calar parameter

When the old query analyzer (`enable_analyzer = 0`) is used and a query
contains `IN ({param:Type})` with a single scalar parameter, the second
argument of `in`/`notIn` is an `ASTLiteral` whose `Field` value is a plain
scalar (e.g. `String`), not a `Tuple`.

`extractAtomFromTree` has two branches for `in`/`notIn`:
- The ActionsDAG path (`!getASTNode()`) explicitly wraps set elements in a
  `Tuple` — safe.
- The AST literal path (`getASTNode()` non-null) calls `tryGetConstant`,
  which returns the raw scalar `Field` unchanged.

Both paths then call the `"in"` atom handler, which unconditionally calls
`value.safeGet<Tuple>()`. This throws `LOGICAL_ERROR` ("Bad get: has Tuple,
actual type String") when the value is not a `Tuple`, causing the
`MergeTreeWhereOptimizer` to propagate an exception during selectivity
estimation.

Fix: before dispatching to the atom handler, wrap the `Field` in a
single-element `Tuple` when `is_in_operator` is true and the value is not
already a `Tuple`. `IN (x)` with a single value is semantically identical to
`= x`, so the resulting single-range estimate is correct.

Added a regression test `04039_statistics_in_single_param` that reproduces
the failure with `enable_analyzer = 0`, `use_statistics = 1`, a column with
`uniq` statistics, and a single `{param:String}` bound to IN.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@qoega
qoega requested a review from hanfei1991 March 16, 2026 13:35
@CLAassistant

CLAassistant commented Mar 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
3 out of 4 committers have signed the CLA.

✅ qoega
✅ rschu1ze
✅ alexey-milovidov
❌ Ubuntu


Ubuntu seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [22cfc86]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel, 2/2) failure
02931_rewrite_sum_column_and_constant FAIL cidb IGNORED
Docker keeper image failure
clickhouse/clickhouse-keeper:head-amd64 failure cidb IGNORED
docker library image test (clickhouse/clickhouse-keeper:head-amd64) failure cidb IGNORED
Unit tests (asan_ubsan) error IGNORED

AI Review

Summary

This PR fixes a BAD_GET exception in ConditionSelectivityEstimator when IN receives a single scalar value by normalizing non-Tuple RHS values into a Tuple before in/notIn atom handling. The C++ change is small and targeted, but the regression test coverage is insufficient for the exact reported scenario and for the symmetric NOT IN path, so changes are still required.

Missing context

  • ⚠️ No CI logs/results were provided in this review context, so I could not validate runtime behavior beyond code inspection.

Findings

  • ⚠️ Majors
    • [tests/queries/0_stateless/04039_statistics_in_single_param.sql:22] The PR description says the exception happens for query-parameter form (IN ({p:String})), but the test only covers string literals (IN ('alice')). This leaves the reported regression surface under-protected.
      • Suggested fix: add parameterized checks, e.g. SET param_p='alice'; SELECT ... WHERE category IN ({p:String}); and a non-matching parameter value.
    • [tests/queries/0_stateless/04039_statistics_in_single_param.sql:23] The fix normalizes input for both in and notIn paths, but tests only cover IN.
      • Suggested fix: add at least one NOT IN regression case (preferably also in parameterized form) to protect both operators.

Tests

  • ⚠️ Add a parameterized regression query for IN ({p:String}) with a matching and a non-matching value.
  • ⚠️ Add a NOT IN regression query (ideally parameterized) to cover the symmetric path touched by the fix.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Extend regression coverage to include query-parameter IN ({p:String}).
    • Add NOT IN coverage for the same scalar-to-Tuple normalization path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 16, 2026
@hanfei1991 hanfei1991 self-assigned this Mar 16, 2026
@@ -0,0 +1,31 @@
-- Regression test: `IN` with a single query parameter bound as a scalar must not throw

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.

I cannot reproduce this test failure on master branch

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checking.

I started with a query that generated

Code: 170. DB::Exception: Bad get: has String, requested Tuple. (BAD_GET) (version 26.3.1.4481 (official build))

0. ./ci/tmp/build/./src/Common/Exception.cpp:141:1: DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x0000000013b67990
1. ./src/Common/Exception.h:171:100: DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000d7dc258
2. ./src/Common/Exception.h:57:54: DB::Exception::Exception(PreformattedMessage&&, int) @ 0x000000000d7dbb4c
3. ./src/Common/Exception.h:189:77: DB::Exception::Exception<std::basic_string_view<char, std::char_traits<char>>, std::basic_string_view<char, std::char_traits<char>>>(int, FormatStringHelperImpl<std::type_identity<std::basic_string_view<char, std::char_traits<char>>>::type, std::type_identity<std::basic_string_view<char, std::char_traits<char>>>::type>, std::basic_string_view<char, std::char_traits<char>>&&, std::basic_string_view<char, std::char_traits<char>>&&) @ 0x00000000173d645c
4. ./ci/tmp/build/./src/Core/Field.cpp:872:15: DB::NearestFieldTypeImpl<__decay(DB::Tuple), void>::Type& DB::Field::safeGet<DB::Tuple>() & @ 0x00000000173d8104
5. ./src/Core/Field.h:439:43: DB::ConditionSelectivityEstimator::$_9::__invoke(DB::ConditionSelectivityEstimator::RPNElement&, String const&, DB::Field const&) @ 0x0000000019e64b18
6. ./ci/tmp/build/./src/Storages/Statistics/ConditionSelectivityEstimator.cpp:316:13: DB::ConditionSelectivityEstimator::extractAtomFromTree(std::shared_ptr<DB::StorageInMemoryMetadata const> const&, DB::RPNBuilderTreeNode const&, DB::ConditionSelectivityEstimator::RPNElement&) const @ 0x0000000019e6174c
7. ./contrib/llvm-project/libcxx/include/__functional/function.h:508:12: ? @ 0x0000000019d3a92c
8. ./src/Storages/MergeTree/RPNBuilder.cpp:510:5: DB::ConditionSelectivityEstimator::estimateRelationProfile(std::shared_ptr<DB::StorageInMemoryMetadata const> const&, DB::RPNBuilderTreeNode const&) const @ 0x0000000019e60518
9. ./ci/tmp/build/./src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:357:72: DB::MergeTreeWhereOptimizer::analyzeImpl(std::list<DB::MergeTreeWhereOptimizer::Condition, std::allocator<DB::MergeTreeWhereOptimizer::Condition>>&, DB::RPNBuilderTreeNode const&, DB::MergeTreeWhereOptimizer::WhereOptimizerContext const&, std::set<long, std::less<long>, std::allocator<long>>&) const @ 0x0000000019cc1214
10. ./ci/tmp/build/./src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:325:13: DB::MergeTreeWhereOptimizer::analyzeImpl(std::list<DB::MergeTreeWhereOptimizer::Condition, std::allocator<DB::MergeTreeWhereOptimizer::Condition>>&, DB::RPNBuilderTreeNode const&, DB::MergeTreeWhereOptimizer::WhereOptimizerContext const&, std::set<long, std::less<long>, std::allocator<long>>&) const @ 0x0000000019cc10e8
11. ./ci/tmp/build/./src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:386:5: DB::MergeTreeWhereOptimizer::optimizeImpl(DB::RPNBuilderTreeNode const&, DB::MergeTreeWhereOptimizer::WhereOptimizerContext const&) const @ 0x0000000019cbf17c
12. ./ci/tmp/build/./src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp:134:28: DB::MergeTreeWhereOptimizer::optimize(DB::SelectQueryInfo&, std::shared_ptr<DB::Context const> const&) const @ 0x0000000019cbe67c
13. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:839:33: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, std::optional<DB::Pipe>, std::shared_ptr<DB::IStorage> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, std::shared_ptr<DB::PreparedSets>)::$_0::operator()(bool) const @ 0x000000001868efd8
14. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:961:5: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, std::optional<DB::Pipe>, std::shared_ptr<DB::IStorage> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, std::shared_ptr<DB::PreparedSets>) @ 0x000000001868728c
15. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:330:7: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&) @ 0x0000000018683800
16. ./contrib/llvm-project/libcxx/include/__memory/unique_ptr.h:773:30: DB::InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context>, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&) @ 0x00000000186bb708
17. ./contrib/llvm-project/libcxx/include/__memory/construct_at.h:38:49: DB::interpretSubquery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context const>, std::vector<String, std::allocator<String>> const&, DB::SelectQueryOptions const&) @ 0x0000000018b5944c
18. ./src/Interpreters/interpretSubquery.cpp:37:12: DB::ActionsMatcher::makeSet(DB::ASTFunction const&, DB::ActionsMatcher::Data&, bool) @ 0x0000000018554198
19. ./ci/tmp/build/./src/Interpreters/ActionsVisitor.cpp:783:28: DB::ActionsMatcher::visit(DB::ASTFunction const&, boost::intrusive_ptr<DB::IAST> const&, DB::ActionsMatcher::Data&) @ 0x000000001854a8ac
20. ./src/Interpreters/InDepthNodeVisitor.h:71:13: DB::InDepthNodeVisitor<DB::ActionsMatcher, true, false, boost::intrusive_ptr<DB::IAST> const>::doVisit(boost::intrusive_ptr<DB::IAST> const&) @ 0x0000000018546b20
21. ./src/Interpreters/InDepthNodeVisitor.h:61:9: DB::ExpressionAnalyzer::getRootActions(boost::intrusive_ptr<DB::IAST> const&, bool, DB::ActionsDAG&, bool) @ 0x000000001852ccec
22. ./ci/tmp/build/./src/Interpreters/ExpressionAnalyzer.cpp:1242:5: DB::ExpressionAnalysisResult::ExpressionAnalysisResult(DB::SelectQueryExpressionAnalyzer&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, bool, bool, bool, std::shared_ptr<DB::FilterDAGInfo> const&, std::shared_ptr<DB::FilterDAGInfo> const&, DB::Block const&) @ 0x0000000018535a08
23. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:1212:23: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, std::optional<DB::Pipe>, std::shared_ptr<DB::IStorage> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, std::shared_ptr<DB::PreparedSets>)::$_0::operator()(bool) const @ 0x0000000018690360
24. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:961:5: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, std::optional<DB::Pipe>, std::shared_ptr<DB::IStorage> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&, std::shared_ptr<DB::StorageInMemoryMetadata const> const&, std::shared_ptr<DB::PreparedSets>) @ 0x000000001868728c
25. ./ci/tmp/build/./src/Interpreters/InterpreterSelectQuery.cpp:330:7: DB::InterpreterSelectQuery::InterpreterSelectQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context> const&, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&) @ 0x0000000018683800
26. ./contrib/llvm-project/libcxx/include/__memory/unique_ptr.h:773:30: DB::InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery(boost::intrusive_ptr<DB::IAST> const&, std::shared_ptr<DB::Context>, DB::SelectQueryOptions const&, std::vector<String, std::allocator<String>> const&) @ 0x00000000186bb708
27. ./contrib/llvm-project/libcxx/include/__memory/unique_ptr.h:773:30: std::unique_ptr<DB::IInterpreter, std::default_delete<DB::IInterpreter>> std::__function::__policy_func<std::unique_ptr<DB::IInterpreter, std::default_delete<DB::IInterpreter>> (DB::InterpreterFactory::Arguments const&)>::__call_func[abi:fe210105]<DB::registerInterpreterSelectWithUnionQuery(DB::InterpreterFactory&)::$_0>(std::__function::__policy_storage const*, DB::InterpreterFactory::Arguments const&) (.llvm.13550722137974535855) @ 0x00000000186c071c
28. ./contrib/llvm-project/libcxx/include/__functional/function.h:508:12: ? @ 0x000000001866cce4
29. ./ci/tmp/build/./src/Interpreters/executeQuery.cpp:1696:66: DB::executeQueryImpl(char const*, char const*, std::shared_ptr<DB::Context>, DB::QueryFlags, DB::QueryProcessingStage::Enum, std::unique_ptr<DB::ReadBuffer, std::default_delete<DB::ReadBuffer>>&, boost::intrusive_ptr<DB::IAST>&, std::shared_ptr<DB::ImplicitTransactionControlExecutor>, std::function<void ()>, DB::QueryResultDetails&) @ 0x0000000018b34db8
30. ./ci/tmp/build/./src/Interpreters/executeQuery.cpp:2082:11: DB::executeQuery(String const&, std::shared_ptr<DB::Context>, DB::QueryFlags, DB::QueryProcessingStage::Enum) @ 0x0000000018b30364
31. ./ci/tmp/build/./src/Server/TCPHandler.cpp:788:68: DB::TCPHandler::runImpl() @ 0x000000001a3932e8

…calar value

When the AST-based PREWHERE optimizer is used (active when
`query_plan_optimize_prewhere=0`), the `in` function's second argument is
an `ASTLiteral`. `RoundBracketsLayer::getResultImpl` returns a single-element
parenthesised expression as-is (not wrapped in a `tuple()` call), so `IN
('value')` produces `ASTLiteral{String}` as the second argument.

`extractAtomFromTree` has two branches for `in`/`notIn`:
- ActionsDAG path (`!getASTNode()`): explicitly wraps set elements in a
  `Tuple` — safe.
- AST literal path (`getASTNode()` non-null): calls `tryGetConstant`, which
  returns the raw `String` `Field` unchanged.

Both paths then call the `"in"` atom handler, which unconditionally calls
`value.safeGet<Tuple>()`. This throws `BAD_GET` ("Bad get: has String,
requested Tuple") when the value is a plain scalar.

Fix: before dispatching to the atom handler, wrap the `Field` in a
single-element `Tuple` when `is_in_operator` is true and the value is not
already a `Tuple`. `IN (x)` with a single value is semantically identical to
`= x`, so the resulting single-range estimate is correct.

Added a regression test `04039_statistics_in_single_param` that reproduces
the failure with `enable_analyzer=0`, `query_plan_optimize_prewhere=0` (to
force the AST path), `use_statistics=1`, a column with `uniq` statistics, and
`IN ('single_literal')`.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@qoega

qoega commented Mar 16, 2026

Copy link
Copy Markdown
Member Author

OPTIMIZE TABLE tab FINAL;

-- Single literal: before the fix this threw BAD_GET.
SELECT count() FROM tab WHERE category IN ('alice');

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.

The PR title/description says this fixes the query-parameter form (IN ({p:String})), but this regression test only covers a string literal (IN ('alice')). Please add a parameterized variant so we directly protect the reported failing path (e.g. SET param_p='alice'; ... WHERE category IN ({p:String})).

@rschu1ze

This comment was marked as resolved.


-- Single literal: before the fix this threw BAD_GET.
SELECT count() FROM tab WHERE category IN ('alice');
SELECT count() FROM tab WHERE category IN ('carol');

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.

The fix updates both in and notIn paths in ConditionSelectivityEstimator, but this regression test covers only IN.
Please add at least one NOT IN case (ideally with a query parameter form too), so both operators are protected from the same Tuple/scalar regression surface.

@clickhouse-gh

clickhouse-gh Bot commented Mar 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 24.50% 24.70% +0.20%
Branches 76.50% 76.50% +0.00%

PR changed lines: PR changed-lines coverage: 100.00% (8/8, 0 noise lines excluded)
Diff coverage report
Uncovered code

@rschu1ze

Copy link
Copy Markdown
Member

02931_rewrite_sum_column_and_constant: #100516

Unit tests (asan_ubsan): #100510

Docker keeper image: not sure how to fix 502 Bad Gateway

@rschu1ze
rschu1ze added this pull request to the merge queue Mar 23, 2026
Merged via the queue into master with commit 4c21912 Mar 23, 2026
145 of 148 checks passed
@rschu1ze
rschu1ze deleted the fix-statistics-in-single-param branch March 23, 2026 23:11
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants