Skip to content

Fix quadratic JSON subcolumn skip-index matching over a large dotted constant - #113289

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113003-json-subcolumn-index-match-quadratic
Aug 12, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113003-json-subcolumn-index-match-quadratic

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

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 query plan optimization stall when a WHERE clause contains a large string constant with many dots and the table carries a bloom_filter, tokenbf_v1, ngrambf_v1 or text skip index. Matching a filter column name against JSONAllPaths(...) 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 SELECT whose WHERE contains 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 with max_execution_time = 300 set, on 26.4.3.37 and 26.7.1.1315. Nothing on that path observes cancellation, so max_execution_time fires and KILL QUERY is inert, no QueryStart row is written, and the handler thread is leaked until restart. Workaround was SETTINGS use_skip_indexes = 0.

Root cause. tryMatchJSONSubcolumnToIndex reads 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 each X against the name by prefix-plus-dot. Cost no longer depends on the name. Selection is deliberately unchanged (shortest matching X, ties to the first entry), which reproduces what walking dot positions left to right did.

This is not bloom_filter-specific: tokenbf_v1, ngrambf_v1 and text reach 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 = 1 cases in 04024_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

  • Backported to: 26.7.4.40, 26.6.3.61, 26.5.7.47

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

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
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
resulting code performed before reading the implementation notes. 2 review rounds, 6 findings
total across both rounds; the final round returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test asserted a literal Granules: 0/1 without pinning index_granularity, which the test runner randomizes over randint(1, 65536) and injects into the CREATE AGREE, fixed @ 8c7d6e2 The denominator is ceil(1000 / index_granularity), so the literal held only for large draws. Pinned index_granularity = 1 on all four tables; reference 0/1 -> 0/1000. An explicit SETTINGS in the CREATE wins by construction (ClientBase::addMergeTreeSettings only emplaces a setting when absent). Proven both directions under --index_granularity 8: unpinned FAILS, pinned passes; 4 adversarial granularity arms pass
2 ⚠️ Same exposure reported from the tag angle (test determinism under randomized settings) AGREE, fixed @ 8c7d6e2 Same fix. I narrowed the scope: the 1.5x allocation ratio itself was never at risk (2.83x-3.04x before the fix vs 1.0003x after, on a server-side counter that is not randomized), only the granularity literal
3 ⚠️ The cost test would still pass against a hypothetical matcher that declined all sufficiently long names, so it does not prove the matcher stays live DISAGREE That variant is not constructible here: there is no length bound anywhere in the new code, and the single length-dependent operation is one starts_with bounded by the index column's own length. Such a variant would also break the 80 existing EXPLAIN indexes = 1 cases in 04024_json_skip_index_* plus the 3 new ambiguous cases, which is the liveness proof and already runs in the same batch. Re-verified against the source this round, not inherited
4 💡 Missing no-fasttest and no-parallel-replicas tags that all four sibling tests carry AGREE, fixed @ 8c7d6e2 Tags added. Recorded honestly: no-parallel-replicas is convention alignment, not a measured flake fix. Forcing the exact settings that tag suppresses left the test passing
5 💡 The changelog entry wrapped Closes #113003 in backticks, which is not the convention in CHANGELOG.md and suppresses the issue auto-link AGREE, fixed Backticks removed from the changelog entry before the final review round ran
6 ⚠️ I suspected randomized use_skip_indexes_on_data_read / explain_query_plan_default could reshape the asserted EXPLAIN lines DROPPED Self-withdrawn on measurement: skip statistics are recorded independently of the data-read mode, and my sub-claim about the two reference lines was wrong in substance. They come from two different EXPLAIN invocations, so their coexistence is correct

Beyond the findings, I independently re-derived the behavioural equivalence of the inverted scan
rather than accepting it. The old loop walked dot splits in ascending prefix length and returned at
the first match, so its selection was shortest-prefix-wins with ties resolving to the lowest index
position; the new scan reproduces exactly that. Three details that could each have changed behaviour
silently do not: the ^ and empty-path guards remain after selection rather than becoming continue
(so a longer match cannot win), and the leading-dot and empty-suffix exclusions are preserved by the
size bounds. I also enumerated the invariant carriers independently first (10 call sites, 4 index
families, all funnelling through the one helper) before comparing against the plan.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20260804-085300

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t WHERE position(repeat('a.', 400000), s) = 1 over the 4-line table in the issue: 42.7s on a debug build, every run, no randomization needed.
b Root cause explained? Yes. tryMatchJSONSubcolumnToIndex enumerated every dot split of the filter column name and per split formatted a lookup key plus scanned index_columns linearly. The name embeds the folded constant verbatim (position('a.a.a...', s)), so its length is user-controlled, giving O(length^2). Confirmed by a no-dots control at identical length (0.010s vs 3.069s) and by use_skip_indexes = 0 (0.033s).
c Fix matches root cause? Yes. The enumeration over the name is removed, not bounded or capped: the search is inverted to scan index_columns instead. No magic constant, no new setting, no behavior gate.
d Test intent preserved / new tests added? Yes. All 80 existing EXPLAIN indexes = 1 cases in 04024_json_skip_index_* pass unchanged. Added 3 cases pinning the previously untested ambiguous selection, plus a new cost test.
e Both directions demonstrated? Yes. The repro goes 42.730s to 0.160s. The new test FAILS on the pre-fix binary (allocated 23479344 bytes, more than 150% of the no-dots control (7744048 bytes), a 3.03x ratio) and passes on the fixed one.
f Fix is general across code paths? Yes, which is why the fix sits in the shared helper rather than at the call sites. Measured pre-fix at 100000 dots: bloom_filter 2.749s, tokenbf_v1 2.573s, ngrambf_v1 2.568s, text 2.779s, versus set 0.005s (never calls the helper). A four-index-type defect, not bloom_filter-only. Eight call sites and both overloads are covered by the one change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Matrix run on both binaries with byte-identical output: present path, absent path (prunes), sub-object ^ (correctly unmatched), typed subcolumn j.a.b.:Int64, dotted JSON column name, tuple member t.json, single-char column name, ambiguous two-entry index, and an adversarial sibling column whose name string-prefix-matches the JSON column but has no dot after it. Boundaries are structural: the length guards reject fn(), a name equal to the column, and a name ending at the dot.
h Backward compatible? Yes, trivially. No setting, no format, no on-disk or API change, so no SettingsChangesHistory.cpp entry. Pruning decisions are bit-identical, which the 83 EXPLAIN indexes = 1 cases demonstrate.
i Invariants and contracts preserved? Yes. The contract is nullopt or a (json_column_name, path, header_position) triple; header_position indexes index_columns and is only ever assigned a valid loop index. Selection order is preserved deliberately (shortest matching column, ties to the first entry) and is now pinned by a test. No allocation, lock or error path: both string_views point into arguments that outlive the call, and the result is copied before returning.

Session id: cron:clickhouse-impl-slot-42:20260804-070700

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Avogar, could you review this? Skip-index condition building matched a filter column name against JSONAllPaths(...) index columns by enumerating every dot split of the name, and the name embeds a folded constant verbatim, so a large dotted string constant made index analysis quadratic in its length. This inverts the search to scan the index columns instead, preserving the selection order exactly (shortest matching JSON column, ties to the first entry).

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c7d6e2]

Summary: ✅


AI Review

Summary

This PR fixes the quadratic tryMatchJSONSubcolumnToIndex path by scanning index header entries instead of enumerating every dot split in the filter-column name. I did not find a correctness or compatibility regression in the current code: the new matcher preserves the previous shortest-prefix/first-entry selection, the changed helper is the shared path for the affected skip-index implementations, and the PR includes focused coverage for dotted identifiers, tuple subcolumns, the ambiguous-prefix case, and the planning-cost regression.

Final Verdict

✅ No blocking issues found in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8c7d6e2

CI is fully finished on this head and there is nothing to own: 174/174 check-runs completed, 157 success, 17 skipped, 0 failures. Config Workflow and Finish Workflow both completed successfully.

Check / test Reason Owner / fixing PR
(none) no failing check on this commit not applicable

Three CIDB rows on this commit carry test_status = FAIL while their enclosing check reports success, so I checked each one rather than reading the aggregate:

  • Bugfix validation (functional tests, amd64) and (aarch64) / 04024_json_skip_index_bloom_filter - this is the intended semantics of that check: the pre-existing test has to fail against master for the bugfix to be validated. Both jobs report Failed: 0, Passed: 2 and the new cost test 04780_json_subcolumn_index_match_not_quadratic reddens on the unfixed binary exactly as designed.
  • Build (arm_release) / Post Hooks - build_profile_hook.py could not upload build-profile telemetry (LogCluster query failed with code 500). The enclosing build reports Failures: 0/4 and the packages were produced; this is the telemetry sink, not this change.

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

@Avogar Avogar self-assigned this Aug 5, 2026

@alexey-milovidov alexey-milovidov 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.

I found it good. @Avogar to double check, but ok to merge tomorrow.

@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
@Avogar
Avogar added this pull request to the merge queue Aug 12, 2026
@Avogar Avogar added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 12, 2026
Merged via the queue into ClickHouse:master with commit 9992cbc Aug 12, 2026
180 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 12, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 13, 2026
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
Backport #113289 to 26.5: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 14, 2026
Backport #113289 to 26.7: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 18, 2026
Backport #113289 to 26.6: Fix quadratic JSON subcolumn skip-index matching over a large dotted constant
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…-index matching over a large dotted constant
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Query planner stuck for hours in bloom_filter index analysis when WHERE references a large scalar subquery Map, query cannot be killed

6 participants