Skip to content

Reuse resolved column metadata in performRequiredConversions - #113008

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
rorylshanks:avoid-repeated-subcolumn-resolution
Aug 9, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
rorylshanks:avoid-repeated-subcolumn-resolution

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

IMergeTreeReader already resolves and stores columns_to_read during construction, but performRequiredConversions() called getColumnInPart() again for every read block.

For dynamic JSON subcolumns, this repeatedly enumerated the full JSON serialization and entered SerializationObjectPool. In production-derived PostHog profiles, this path accounted for 40,849 of 48,346 (84.5%) dynamic-subcolumn resolution/pool-contention CPU samples.

Reuse columns_to_read[pos] instead of resolving the same column again.

Before/after benchmark

Measured on this branch vs. the same tree with only src/Storages/MergeTree/IMergeTreeReader.cpp reverted to the merge-base (master) version, RelWithDebInfo, aarch64. Dataset: CREATE TABLE t (json JSON) ENGINE = MergeTree ORDER BY tuple(), 1M rows of toJSONString(map('key' || toString(number % 400), number)), single part after OPTIMIZE TABLE ... FINAL. Query: SELECT json.key0, ..., json.key31 FROM t FORMAT Null SETTINGS max_threads = 1 (32 dynamic subcolumns), 10 timed runs after warmup:

median min
before (master performRequiredConversions) 0.308 s 0.306 s
after (this PR) 0.275 s 0.274 s

That is a stable ~12% end-to-end speedup. A perf record -g profile of the before binary on the same query attributes 12.65% of CPU samples to performRequiredConversions, of which 12.49% is the inlined getColumnInPart (i.e. SerializationObjectPool::getOrCreate, SerializationObjectDynamicPath construction, SerializationObject::enumerateStreams), matching the measured win; in the after binary this subtree is gone.

The new test tests/performance/json_subcolumns_required_conversions.xml covers this path in CI.

Changelog category (leave one):

  • Performance Improvement

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

Improves MergeTree read performance for JSON subcolumns by reusing resolved subcolumn metadata during required conversions.

Version info

  • Merged into: 26.8.1.1035 (included in 26.8 and later)

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [305a49e]

Summary: ✅


AI Review

Summary

This PR replaces the per-block getColumnInPart lookup in IMergeTreeReader::performRequiredConversions with the already-populated columns_to_read[pos] cache and adds a focused performance test for the JSON-subcolumn path. I did not find a correctness, compatibility, or coverage issue in the current diff: columns_to_read is built from the same getColumns() list at reader construction and is already the source of truth for the on-disk column/type mapping throughout the rest of the read pipeline, so reusing it here only removes redundant metadata resolution.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.80% 91.90% +0.10%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR is a one-line micro-optimization in the merge-tree reader that only affects the required-conversions path exercised by JSON subcolumns and on-disk type mismatches (with a matching perf test). Neither flagged query touches that path: ClickBench Q17 is a fixed-column aggregate and TPC-H Q7 is a join over fixed-type columns. Both deltas (+12.4% and +11.6%) land inside master's current variance band and were correctly kept as not_sure by the envelope gate, so they read as run-to-run variance, not a PR effect. Q17 shows a trending master signal worth keeping an eye on independently of this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 541 608 +12.4% <0.0001 This PR only speeds up the required-conversions read path (JSON subcolumns / on-disk type mismatches), which a plain aggregate SELECT on fixed-type columns never exercises, so the +12.4% falls inside master's variance band as run-to-run noise. History is trending, so watch Q17 on master.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 562 627 +11.6% <0.0001 The changed code (per-block column resolution during type conversion) isn't hit by this join query over fixed-type columns, and the +11.6% sits within master's current variance band, so this reads as run-to-run variance rather than a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 3960dd55-4e48-4779-8d5f-85e65d103e93
  • MIRAI run: 7f19b7ed-630b-4830-a0f5-a6c6855e4110
  • PR check IDs:
    • clickbench_7290_1786006915
    • clickbench_7296_1786006914
    • clickbench_7307_1786006914
    • tpch_adapted_1_official_7324_1786006914
    • tpch_adapted_1_official_7346_1786006914
    • tpch_adapted_1_official_7361_1786006915

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 305a49e96 with master 7a9ada8cf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of de947727b; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 689.45 MiB 686.43 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

33 object files changed (+153.04 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/TemporarySecretFile.cpp.o new 39.80 KiB +39.80 KiB
src/CMakeFiles/dbms.dir/Storages/StorageMySQL.cpp.o 521.85 KiB 557.30 KiB +35.46 KiB (+6.79%)
src/Common/mysqlxx/CMakeFiles/mysqlxx.dir/SSLParams.cpp.o new 27.15 KiB +27.15 KiB
src/Common/mysqlxx/CMakeFiles/mysqlxx.dir/PoolFactory.cpp.o 60.58 KiB 80.05 KiB +19.47 KiB (+32.14%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline.

Job report

rorylshanks and others added 5 commits August 3, 2026 10:03
The test stresses the per-block column resolution in
`IMergeTreeReader::performRequiredConversions`: selecting 32 dynamic
JSON subcolumns previously re-resolved each subcolumn via
`getColumnInPart` on every read block, repeatedly enumerating the JSON
serialization and entering `SerializationObjectPool`. Reusing
`columns_to_read[pos]` gives a stable ~12% end-to-end speedup on this
query (median 0.308 s -> 0.275 s, single thread, 1M rows, 400 dynamic
paths).

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The AST fuzzer (amd_debug, targeted) failure — Logical error: ColumnBLOB should be converted to a regular column before usage — is unrelated to this PR (a one-line change in IMergeTreeReader::performRequiredConversions that does not touch block marshalling). It is a known master-wide fuzzer finding:
Related: #113165
Related: #111945
A fix is already in progress: #111997

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113008&sha=bf9369f35fc4359f2dc5d50d76a61c994d430ba7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Context: Logical error: Inconsistent KeyCondition behavior is unrelated to this PR (a one-line change in IMergeTreeReader::performRequiredConversions; the exception is raised during primary-key index analysis, before any reading happens). It is the debug-only exact-range consistency check in MergeTreeDataSelectExecutor that catches functions reporting inaccurate monotonicity. The repro is a toDate monotonic chain over an IN set on a LowCardinality(UInt16) key:

EXPLAIN ESTIMATE SELECT count() != 1048576 FROM t PREWHERE toDate(x) IN (toDate(65537), toDate(65537))

CIDB shows the same finding on master (pull_request_number = 0) and on dozens of unrelated PRs over the last month. The auto-generated tracking issue with the same STID was closed earlier this year while the finding still recurs:
Related: #98075
Possibly covered by the in-progress key-analysis work:
Related: #112231

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Reproduced on today's master (91687a7d), so this is not a stale base: bf9369f3 already contains both earlier fixes for this check, #109023 and #111964 (behind_by = 0 for each).

Minimal repro. LowCardinality is the discriminator, not the 65537 saturation:

SET allow_suspicious_low_cardinality_types = 1;  -- LowCardinality(UInt16) is refused by default
CREATE TABLE t (x LowCardinality(UInt16)) ENGINE = MergeTree ORDER BY x;
INSERT INTO t SELECT number % 65536 FROM numbers(1048576);
EXPLAIN ESTIMATE SELECT count() FROM t WHERE toDate(x) IN (toDate(5));  -- aborts

The same query on a plain UInt16 key does not abort and prunes to one mark. toDate(x) = toDate(5) aborts too, so it is not specific to IN.

What the log shows: the surviving range is the whole part, [0, 128), with exact subrange [1, 127). So on a LowCardinality key column the monotonic chain is not applied at all and every range answers "unknown", while matchesExactContinuousRange still promises an exact continuous range. Results are correct (16 rows with the index, 16 without it, 16 against a full scan), so this is a debug-only false positive of the consistency check, not mis-pruning.

#112231 does not cover this carrier. Its guard is keyed on a chain that throws; here nothing throws, the chain is refused as non-monotonic, and that PR deliberately treats the honest non-monotonic answer as "not a failure".

I am fixing this in a separate PR and will link it here.

One refinement on the census: since #111964 merged, the pull_request_number = 0 rows are release branches only (26.7, 26.6). head_ref = 'master' has been 0 since 2026-07-27. The live recurrence is PR-side, 283 rows across 228 PRs in 30 days.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Root-caused, and the fix is already in progress: #111050 (approved, awaiting merge).

KeyCondition builds monotonic-function chains against a LowCardinality-stripped key type
(KeyCondition.cpp:2903), so monotonicity must always be queried on that stripped type.
matchesExactContinuousRange does exactly that, via the chain's own built argument type, and so
promises an exact continuous range. But of the four callers of
applyMonotonicFunctionsChainToRange, only one strips; the other three pass the key column's raw
type. ToDateMonotonicity then matches none of its WhichDataType cases for
LowCardinality(UInt16), falls through to the !isNativeNumber(type) bail-out and reports
is_monotonic = false, so the chain is refused, every granule answers "unknown", and the surviving
range is the whole part. The debug canary is right; the promise and the delivery were asked
different questions.

A/B that isolates it, on master 91687a7d610e6, LowCardinality(UInt16) ORDER BY x, 1048576 rows:

predicate use_lightweight_primary_key_index_analysis call site result
toDate(x) IN (toDate(5)) 1 (default) Set.cpp:749 abort
toDate(x) IN (toDate(5)) 0 Set.cpp:894 abort
toDate(x) = toDate(5) 1 (default) KeyCondition.cpp:5970 abort
toDate(x) = toDate(5) 0 KeyCondition.cpp:5529 (strips) OK, Granules: 1/128

The one site that strips is the one that works. #111050 adds that strip inside the callee, so all
four agree; it keeps interior links unstripped on purpose, because each is built against the
previous function's result type.

Three things worth noting beyond the reported repro:

  • LowCardinality is the discriminator, not the 65537 saturation: toDate(5) aborts identically.
    It is not IN-specific either (plain = aborts, via FUNCTION_IN_RANGE), nor
    EXPLAIN ESTIMATE-specific (a plain SELECT count() aborts), and multi-function chains such as
    toStartOfMonth(toDate(x)) are affected too.
  • There is a release-build cost, not just a debug abort: pruning is silently lost entirely.
    Granules: 128/128 on the LowCardinality key against 1/128 for the same predicate on a plain
    UInt16 key, so 128x the granules read on that fixture.
  • No wrong results. use_primary_key = 0, the full-scan countIf ground truth, and the plain
    UInt16 control all return 16.

Also, allow_suspicious_low_cardinality_types is checked only at CREATE
(parseColumnsListForTableFunction.cpp:54-67), so a reader of an existing table reaches this with
default settings.

On your other pointer: #112231 does not cover this one. Its guard keys on
chain_application_failed, which is set only when applying a chain throws. Here nothing throws,
the chain is refused as non-monotonic, and that PR deliberately excludes that route. Its two
LowCardinality cases are throwing-intDiv.

I am not opening a separate PR, since that would duplicate #111050. If you would rather have the
toDate case pinned explicitly, I will add it to #111050 as a regression test.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113008&sha=bf9369f35fc4359f2dc5d50d76a61c994d430ba7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The remaining red, Stress test (amd_debug), is unrelated to this PR: the harness aborted before running the tests because SYSTEM RELOAD CONFIG and the follow-up verification query in install_thread_pool_fault_injection timed out (returned non-zero exit status 159). This exact failure mode is fixed by the pending CI fix:
Related: #113248

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit 2c065f1 Aug 9, 2026
180 checks passed

<!-- Reading many dynamic JSON subcolumns stresses the per-block column resolution
in IMergeTreeReader::performRequiredConversions. -->
<query>SELECT json.key0, json.key1, json.key2, json.key3, json.key4, json.key5, json.key6, json.key7, json.key8, json.key9, json.key10, json.key11, json.key12, json.key13, json.key14, json.key15, json.key16, json.key17, json.key18, json.key19, json.key20, json.key21, json.key22, json.key23, json.key24, json.key25, json.key26, json.key27, json.key28, json.key29, json.key30, json.key31 FROM t_json_subcolumns_conversions FORMAT Null SETTINGS max_threads = 1</query>

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.

@rorylshanks why we have max_threads=1 here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was added by @alexey-milovidov not me, I am not sure the reasoning behind this setting
c8b1c3d

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 pr-performance Pull request with some performance improvements 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.

5 participants