Repository navigation
Description
Describe the unexpected behaviour
A SELECT whose WHERE clause references a large Map built by scalar subqueries (a few hundred thousand keys) can get stuck for hours inside query plan optimization, specifically in bloom_filter skip index condition building, on a partitioned table that has a bloom_filter index.
Because the query never leaves planning:
- max_execution_time fires and marks the query cancelled (system.processes shows is_cancelled = 1) but nothing in the planning path checks the flag, so it keeps running
- KILL QUERY does nothing
- no QueryStart row ever shows up in system.query_log
- one HTTPHandler thread sits at 100% CPU until the server is restarted, which is the only way to clear it
We first hit this in production with a machine generated analytics query that had max_execution_time = 300. It ran for 9.2 hours at full core before we noticed the box running hot. Every occurrence leaks a thread permanently.
How to reproduce
Reproduces on the official Docker images 26.4.3.37 and 26.7.1.1315, single node, default config.
CREATE DATABASE wedge_repro;
CREATE TABLE wedge_repro.t_ok
(
ts DateTime, s LowCardinality(String), ip String, b UInt64,
INDEX ix ip TYPE bloom_filter GRANULARITY 4
)
ENGINE = MergeTree PARTITION BY toYYYYMMDD(ts) ORDER BY (s, ts);
CREATE TABLE wedge_repro.t_hang AS wedge_repro.t_ok;
-- 8 daily partitions, ip is high cardinality (roughly unique per row)
INSERT INTO wedge_repro.t_ok
SELECT toDateTime('2026-01-01 00:00:00') + (number % 691200), 'proxy',
concat(toString(10 + intHash64(number) % 200), '.', toString(intDiv(intHash64(number), 200) % 256), '.',
toString(intDiv(intHash64(number), 51200) % 256), '.', toString(intDiv(intHash64(number), 13107200) % 250)),
if(number % 10 = 0, 0, (number * 2654435761) % 1000000 + 1)
FROM numbers(5000);
INSERT INTO wedge_repro.t_hang
SELECT toDateTime('2026-01-01 00:00:00') + (number % 691200), 'proxy',
concat(toString(10 + intHash64(number) % 200), '.', toString(intDiv(intHash64(number), 200) % 256), '.',
toString(intDiv(intHash64(number), 51200) % 256), '.', toString(intDiv(intHash64(number), 13107200) % 250)),
if(number % 10 = 0, 0, (number * 2654435761) % 1000000 + 1)
FROM numbers(400000);This is a per group median/MAD outlier query. Against t_ok (about 5k distinct keys) it completes in about 0.5s:
WITH
(SELECT mapFromArrays(groupArray(k), groupArray(v)) FROM
(SELECT toString(ip) AS k, toFloat64(quantile(0.5)(b)) AS v FROM wedge_repro.t_ok GROUP BY k)) AS med,
(SELECT mapFromArrays(groupArray(k), groupArray(v)) FROM
(SELECT toString(ip) AS k, toFloat64(quantile(0.5)(abs(b - med[k]))) AS v FROM wedge_repro.t_ok GROUP BY k)) AS mad
SELECT count() FROM wedge_repro.t_ok
WHERE s = 'proxy' AND if(abs(b - med[toString(ip)]) > 3 * mad[toString(ip)] * 1.4826, 1, 0) = 1
SETTINGS max_execution_time = 300;The identical query against t_hang (about 400k distinct keys) never returns:
WITH
(SELECT mapFromArrays(groupArray(k), groupArray(v)) FROM
(SELECT toString(ip) AS k, toFloat64(quantile(0.5)(b)) AS v FROM wedge_repro.t_hang GROUP BY k)) AS med,
(SELECT mapFromArrays(groupArray(k), groupArray(v)) FROM
(SELECT toString(ip) AS k, toFloat64(quantile(0.5)(abs(b - med[k]))) AS v FROM wedge_repro.t_hang GROUP BY k)) AS mad
SELECT count() FROM wedge_repro.t_hang
WHERE s = 'proxy' AND if(abs(b - med[toString(ip)]) > 3 * mad[toString(ip)] * 1.4826, 1, 0) = 1
SETTINGS max_execution_time = 300;The scalar subqueries themselves evaluate in a few seconds, the hang starts after that. Leaving it for 6+ minutes produces no timeout error despite max_execution_time = 300:
SELECT query_id, elapsed, is_cancelled FROM system.processes;
-- elapsed climbs past 300 with is_cancelled = 1 and never stops
SELECT count() FROM system.query_log WHERE query_id = '<id>';
-- 0, QueryStart is never written (it is logged after planning)KILL QUERY on the id has no effect either. Only a server restart clears the thread.
Variations we tried, each changing one thing from the hanging case:
| variant | result |
|---|---|
| ~5k keys (t_ok above) | 0.5s |
| no bloom_filter index | completes, about 1 min |
| SETTINGS use_skip_indexes = 0 | completes |
| unpartitioned table (single part), same 400k keys | planning finishes in tens of seconds, then executes |
| 5 parts, ~50k keys | tens of seconds |
| 5 parts, ~400k keys, 1 bloom index | hangs, hours or more |
So the cost looks roughly like map size times number of parts times whatever the per candidate matching does per entry, and at realistic sizes it might as well be infinite. There is no cancellation point anywhere in that phase. Note the timeout does work during the scalar subquery evaluation itself (with a low max_execution_time the query dies there and returns TIMEOUT_EXCEEDED normally), it is specifically the index analysis afterwards that cannot be interrupted.
Error message and/or stacktrace
No error is ever produced. Stack of the spinning thread captured via system.stack_trace during the original incident on 26.4.3.37:
fmt::v12::detail::copy_noinline / parse_format_string / vformat_to
DB::tryMatchJSONSubcolumnToIndex(...)
DB::tryMatchNodeToJSONIndex(DB::RPNBuilderTreeNode const&, std::vector<std::string> const&, std::string const&)
DB::tryMatchNodeToJSONIndex(DB::RPNBuilderTreeNode const&, DB::Block const&, std::string const&)
DB::MergeTreeIndexConditionBloomFilter::traverseTreeEquals(...)
DB::MergeTreeIndexConditionBloomFilter::traverseFunction(...)
DB::RPNBuilder<DB::MergeTreeIndexConditionBloomFilter::RPNElement>::traverseTree(...)
DB::RPNBuilder<DB::MergeTreeIndexConditionBloomFilter::RPNElement>::traverseTree(...)
DB::RPNBuilder<DB::MergeTreeIndexConditionBloomFilter::RPNElement>::RPNBuilder(...)
DB::MergeTreeIndexBloomFilter::createIndexCondition(...)
DB::ReadFromMergeTree::buildIndexes(...)
DB::ReadFromMergeTree::applyFilters(...)
DB::SourceStepWithFilterBase::applyFilters()
DB::QueryPlanOptimizations::optimizePrimaryKeyConditionAndLimit(...)
DB::QueryPlanOptimizations::optimizeTreeSecondPass(...)
DB::QueryPlan::optimize(...)
DB::QueryPlan::buildQueryPipeline(...)
DB::InterpreterSelectQueryAnalyzer::buildQueryPipeline()
DB::InterpreterSelectQueryAnalyzer::execute()
DB::executeQueryImpl(...)
DB::executeQuery(...)
DB::HTTPHandler::processQuery(...)
DB::HTTPHandler::handleRequest(...)
DB::HTTPServerConnection::run()
The top of the stack differs between snapshots (the fmt frames come and go), so it is progressing through an enormous amount of work rather than deadlocked on a lock. The table in the original incident also had a JSON column, hence the tryMatchJSONSubcolumnToIndex frames. A JSON column is not required, the plain columns table above hangs the same way.
Expected behavior
Two separate issues really:
- Index condition analysis should not do per part work proportional to the size of a folded scalar constant. The map here is on the value side of an arithmetic expression, it can never help prune a bloom filter, so ideally the matcher would give up on large constants immediately.
- Plan optimization should check the cancellation flag somewhere. Even if the analysis stays slow, max_execution_time and KILL QUERY should be able to stop it. As it stands, any pathological planning case turns into a permanently leaked thread at 100% CPU, and the only fix is restarting the server. This part seems worth fixing regardless of point 1.
Workaround for anyone else hitting this: SETTINGS use_skip_indexes = 0 makes the query complete with identical results.
Additional context
The triggering queries are machine generated (per group median/MAD baselines attached via scalar subquery maps, which we use instead of window functions to avoid buffering whole partitions). We can share the full 33 frame symbolized stack, the original 190 column schema, and timings if useful.
Version info
- Resolved by: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant #113289
- Backported to:
26.7.4.40,26.6.3.61,26.5.7.47
Activity
shankar-iyer commentedon Aug 2, 2026
Checking
shankar-iyer commentedon Aug 3, 2026
Reproduced.
It is about the number of dots in the string constant.
shankar-iyer commentedon Aug 3, 2026
@groeneai Check my repro above and fix it. I had a few alternates : should we not just check if the index_columns has a
JSONAllPathselement? Assign the PR to me.groeneai commentedon Aug 3, 2026
Acknowledged - I reproduced your repro and I am working the fix. I will follow up here with the PR and assign it to you.
On your alternative, one measurement first, because it changes the answer. Your repro's cost is quadratic in the dot count, not linear:
Same constant length with no dots (
repeat('ab', 200000)) is 0.43s, anduse_skip_indexes = 0is 0.41s. So the driver is the dot count, as you said.The mechanism is that
tryMatchJSONSubcolumnToIndexenumerates every dot split of the candidate column name viaNested::getAllColumnAndSubcolumnPairs(MergeTreeIndexJSONSubcolumnHelper.cpp:46), and for each split does anfmt::formatplus a linearstd::findoverindex_columns(:48-49). N dots gives N splits, each allocating a formatted string - hence the quadratic curve and thefmtframes in the reporter's stack.Where I would not stop at the
index_columns-contains-JSONAllPathsgate: it fixes your repro but not the original report. I measured both arms at 200k dots:JSONAllPathsindex (your repro): 10.5sJSONAllPaths(j)index present: 20.8sWith the index present the gate cannot short-circuit, and the cost roughly doubles because there are then two matcher call sites in play. The reporter's incident table did have a JSON column, so the gate would not have helped there - which is the shape that actually ran 9.2 hours.
So I would rather fix it at the source in
tryMatchJSONSubcolumnToIndex: the loop is enumerating splits of a constant expression's name, which can never be a JSON subcolumn reference. Bailing out before the split enumeration removes the cost in both arms and keeps the matcher's behaviour identical for real subcolumn references. Your gate is still worth having as a cheap guard, and I plan to include it, but as a complement rather than the primary fix.On the reporter's point 2 (nothing in plan optimization observes cancellation): I confirmed there is no
checkTimeLimit/isCancelledcall anywhere in theoptimizeTreeSecondPass->applyFilters->buildIndexespath, which is whymax_execution_timeandKILL QUERYare both inert here. That is a genuinely separate fix with its own risk profile, so I intend to ship it as a follow-up rather than bundle it - say the word if you would rather see both in one PR.groeneai commentedon Aug 4, 2026
@shankar-iyer PR is up: #113289
I cannot set the assignee or request a review from my account (fork contributor, GitHub rejects
both with a permissions error), so please assign yourself if you still want it on you.
On your proposed alternative: I adopted it as the degenerate case but generalized it, because a
gate on
index_columnscontaining aJSONAllPathselement cannot fix the arm where such an indexIS present. Measured pre-fix at 100000 dots: 2.567s with no JSON index, 5.159s with a
JSONAllPaths(j)index, so the cost roughly doubles in exactly the case the gate cannotshort-circuit. Since the original reporter's table did have a JSON column, gate-only would not
have prevented the 9.2-hour stall he hit. Inverting the search inside
tryMatchJSONSubcolumnToIndex(scanindex_columns, test each entry against the name byprefix-plus-dot) fixes both arms, and with no
fn(...)entry present the loop finds nothing andreturns immediately, which is your early-out for free.
Your repro goes from 42.7s to 0.16s on a debug build. Worth noting the defect is not
bloom_filter-specific:
tokenbf_v1,ngrambf_v1andtextreach the same helper, so the singlechange covers all four.
The cancellation half (the reporter's point 2) ships as a follow-up, as I said in my earlier
comment. There is currently no cancellation observation anywhere in
optimizeTreeSecondPass->applyFilters->buildIndexes, which is whymax_execution_timefires while the thread runs on and
KILL QUERYis inert. Say the word if you would rather haveboth in one PR.
Fix quadratic JSON subcolumn skip-index matching over a large dotted …
Do not report a thread's pre-attach untracked memory as the query's