Repository navigation
Fix quadratic JSON subcolumn skip-index matching over a large dotted constant - #113289
Conversation
…constant
tryMatchJSONSubcolumnToIndex reads a filter column name as
<json_column>.<path>. It did not know where the split is, so it
enumerated every dot split of the name via
Nested::getAllColumnAndSubcolumnPairs and per split built a
fmt::format("{}({})", fn, prefix) lookup key and scanned index_columns
linearly.
The name embeds a folded constant verbatim: for
position(repeat('a.', K), s) = 1 constant folding turns repeat(...) into
a COLUMN node, and appendColumnNameWithoutAlias recursively appends child
names, so the RPN key node's name is the literal string
position('a.a.a...', s). Its length is therefore user-controlled, and the
total formatted bytes are sum(prefix_i) = O(length^2) for a dot-dense
name. Reported as hours of query plan optimization at 100% of one core,
with the thread leaked because nothing on that path observes
cancellation.
Note the matched node is a FUNCTION node, not a constant, so
isConstant() is false for it and a constant-node early-out would not
fire.
Invert the search: scan index_columns, keep entries shaped fn(X), and
test each X against the name by prefix plus dot. Cost becomes
O(|index_columns|), independent of the name's length and dot count, and
no pair vector is materialised.
Selection is preserved exactly. The old loop walked dot positions in
increasing order, so it accepted the first (shortest) prefix whose
fn(prefix) is present, and std::find resolved duplicates to the lowest
position; the new code implements shortest-X-wins with lowest-position
tie-break. The guards carry over one-for-one, and everything after
selection is untouched.
This is not bloom_filter-specific: tokenbf_v1, ngrambf_v1 and text reach
the same helper through eight call sites, and both overloads forward to
the changed function, so all four index types are fixed at once. The set
index never calls the helper and was never affected.
The reporter's repro goes from 42.7s to 0.16s on a debug build. All 80
existing EXPLAIN indexes = 1 cases in 04024_json_skip_index_* pass
unchanged, which is the equivalence proof. Three new cases pin the
previously untested selection when one index has both JSONAllPaths(a) and
JSONAllPaths(`a.b`) so that a.b.<path> matches both; their reference was
generated before the fix so it encodes the existing behavior.
The new cost test asserts allocated bytes from system.query_log rather
than wall clock: a wall-clock ratio is dominated by debug-build client
startup and silently passed on the unfixed binary. Four arms make the
test discriminate between candidate fixes rather than merely reddening,
including a long non-JSON index_columns entry and a table that does have
a JSONAllPaths index.
Closes: ClickHouse#113003
…tings The test asserted the literal EXPLAIN line "Granules: 0/1". That denominator is the granule count of the 1000-row insert before the skip index, so it is ceil(rows / index_granularity). The tables were created without a SETTINGS clause, which is exactly the condition under which clickhouse-test injects a randomized index_granularity drawn from randint(1, 65536), so any draw below ~999 changed the asserted line: 0/125 at 8, 0/1000 at 1. Measured failure rate about 1.5% per run, which a plain 50-run batch cannot distinguish from clean. Pin index_granularity on all four tables, matching the 04024_json_skip_index_* siblings, and regenerate the reference. Verified by forcing --index_granularity 8: the unpinned form fails the reference diff and the pinned form passes. Add no-fasttest and no-parallel-replicas to match the same siblings. The test also passed with the parallel-replicas settings forced, so that tag guards a plausible rather than an observed failure. Also add the current_database = currentDatabase() predicate to the system.query_log lookup. Without it the test was the only violation of the various_checks.sh rule in the whole tree, which fails Style check. The allocated-bytes oracle still reddens on the pre-fix binary at a 3.03x ratio, so narrowing the lookup did not blind it.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex), plus my own cold review of the
Beyond the findings, I independently re-derived the behavioural equivalence of the inverted scan Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260804-085300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-42:20260804-070700 |
|
cc @CurtizJ @Avogar, could you review this? Skip-index condition building matched a filter column name against |
|
Workflow [PR], commit [8c7d6e2] Summary: ✅
AI ReviewSummaryThis PR fixes the quadratic Final Verdict✅ No blocking issues found in the current diff. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code |
CI finish ledger - 8c7d6e2CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 157 success, 17 skipped, 0 failures.
Three CIDB rows on this commit carry
Verified from the paginated check-runs API and the per-job report JSON rather than the status rollup, which truncates on this repo. I am not re-pinging reviewers. Session id: cron:our-pr-ci-monitor:20260804-143000 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
I found it good. @Avogar to double check, but ok to merge tomorrow.
Backport #113289 to 26.5: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
…ching over a large dotted constant
Backport #113289 to 26.7: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
…ching over a large dotted constant
Backport #113289 to 26.6: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
…-index matching over a large dotted constant
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query plan optimization stall when a
WHEREclause contains a large string constant with many dots and the table carries abloom_filter,tokenbf_v1,ngrambf_v1ortextskip index. Matching a filter column name againstJSONAllPaths(...)index columns enumerated every dot split of the name, which made skip-index condition building quadratic in the constant's length. Closes #113003.Description
Closes: #113003
What breaks. A
SELECTwhoseWHEREcontains a large dotted string constant, over a table with a skip index, spends unbounded time in query plan optimization. The reporter measured 9.2 hours at 100% of one core withmax_execution_time = 300set, on 26.4.3.37 and 26.7.1.1315. Nothing on that path observes cancellation, somax_execution_timefires andKILL QUERYis inert, noQueryStartrow is written, and the handler thread is leaked until restart. Workaround wasSETTINGS use_skip_indexes = 0.Root cause.
tryMatchJSONSubcolumnToIndexreads a filter column name as<json_column>.<path>. Not knowing where the split is, it enumerated every dot split of the name and per split formatted a lookup key and scanned the index columns. The name embeds a folded constant verbatim (position('a.a.a...', s)), so its length is user-controlled, giving O(length^2).The change. Scan the index columns instead: keep entries shaped
JSONAllPaths(X)and test eachXagainst the name by prefix-plus-dot. Cost no longer depends on the name. Selection is deliberately unchanged (shortest matchingX, ties to the first entry), which reproduces what walking dot positions left to right did.This is not
bloom_filter-specific:tokenbf_v1,ngrambf_v1andtextreach the same helper, so all four are fixed at once.Validation. The reporter's repro goes from 42.7s to 0.16s on a debug build. All 80 existing
EXPLAIN indexes = 1cases in04024_json_skip_index_*pass unchanged; 3 new cases pin the previously untested ambiguous case where two index columns match one name. The new cost test asserts allocated bytes rather than wall clock, and was verified to fail on the pre-fix binary.The cancellation gap is real and separate; it ships as a follow-up.
Version info
26.7.4.40,26.6.3.61,26.5.7.47