Skip to content

Reuse cached JSON subcolumn serializations - #110957

Merged
alexey-milovidov merged 33 commits into
ClickHouse:masterfrom
rorylshanks:optimize-json-subcolumn-serialization-cache
Sep 27, 2026
Merged

alexey-milovidov merged 33 commits into
ClickHouse:masterfrom
rorylshanks:optimize-json-subcolumn-serialization-cache

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

IMergeTreeDataPart already stores column and subcolumn serializations. Readers rebuilt the parent JSON serialization for requested paths instead of reusing safe cached subcolumn serializations.

Reuse cached serializations when supportsPooling permits sharing, including typed paths under JSON wrappers. Derive unstored paths from the cached parent. Non-poolable serializations retain per-reader construction. Wide readers skip unused full-parent serializations, and compact readers construct each full parent at most once.

Compact parts with substream marks still construct one unused full-parent serialization per requested parent. Removing that remaining work is scoped to #111020. This change reduces reconstruction; it does not eliminate every parent reconstruction.

Measured CI results from tests/performance/json_subcolumn_serialization_cache.xml, run on 2026-09-10: master d8d2f9942e4bd888c42b7c27f3f62231b491d33d versus PR b5af97e4a163f340855413923d52aa8574068006. Values are client_time in milliseconds. These are results from that revision, not a new measurement of the latest merge.

Layout AMD before → after Time reduction ARM before → after Time reduction
Wide 145.3 → 62.6 57.0% 173.9 → 75.9 56.4%
Compact, without substream marks 306.7 → 180.8 41.1% 365.8 → 220.3 39.8%
Compact, with substream marks 254.4 → 79.9 68.6% 302.5 → 98.6 67.4%

Measured queries and CI reports. The workload reads two typed paths from a 512-path JSON schema across 96 parts with max_threads = 1; the results describe that workload.

The Iceberg pre-epoch pruning exception in the integration report also caused the following connection failures. The latest merge includes the revert in #119298; #119302 contains the follow-up fix for that independently tracked regression.

Related: #113099
Related: #111020
Related: #119298
Related: #119302

Changelog category (leave one):

  • Performance Improvement

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

Reduce serialization construction when reading JSON subcolumns from MergeTree parts by reusing safe cached subcolumn serializations.


Workflow [PR]
Sync PR [sync-upstream/pr/110957]

Version info

  • Merged into: 26.10.1.784-master (included in 26.10 and later)

@scanhex12 scanhex12 self-assigned this Aug 25, 2026
@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label Aug 25, 2026
@scanhex12
scanhex12 requested a lite review from Copilot August 25, 2026 12:42
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0190e68]

Summary: ✅


AI Review

Summary

This PR reuses safe cached JSON subcolumn serializations in MergeTree readers, extends that reuse to wrapped object-bearing carriers, and adds focused compact-part correctness and performance coverage. I did not find a new correctness, safety, or performance-contract violation in the current PR head; the earlier review threads are either fixed in the code or the remaining compact-with-substream-marks work is now explicitly scoped out in the PR description.

Missing context / blind spots
  • ⚠️ The latest full PR / build matrix is still pending, so this pass is based on the current diff, the full thread history, and the currently visible checks (Fast test, Style check, and Build profile diff). A green CI run on the new compact-reader paths would close the remaining validation gap.
Final Verdict

✅ No new review findings at the current 0190e688af24ff9b509bc496b20d0a25060a7696 PR head. I would not post additional inline comments from this pass.

LLVM Coverage Report

Measured on commit 0190e68.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 80/80 (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 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 0190e688af24ff9b509bc496b20d0a25060a7696 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 41 analysed

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

This PR changes how MergeTree picks and caches serializations for JSON/Object subcolumns, mostly for compact parts without substream marks. No ClickBench or TPC-H column goes through that path. The four flagged ClickBench improvements (Q18 -14.8%, Q31 -12.9%, Q32 -45.3%, Q34 -5.9%) are all GROUP BY-heavy queries with lower CPU, which points to the gap between the 26.9 master base and the newer source build rather than this diff. Q18, Q31 and Q34 are downgraded to not sure. Q32 stays an improvement only because the hard override locks it, and it should not be credited to this PR.

clickbench

🟢 1 improved · ⚠️ 3 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1376 753 -45.3% <0.0001 aggregation: The -45.3% is large enough that the hard override locks this verdict. The query reads no JSON columns, so this diff does not explain it; it more likely comes from the base being built from older master.
⚠️ 18 not_sure 1101 938 -14.8% <0.0001 aggregation: This GROUP BY query reads only plain columns from the hits table. The PR changes only JSON/Object subcolumn serialization and compact-part reading, so the -14.8% cannot come from this diff.
⚠️ 31 not_sure 309 269 -12.9% <0.0001 aggregation: This is a high-cardinality GROUP BY over numeric columns with no JSON types. None of the changed reader code for JSON subcolumns or compact parts runs here, so the -12.9% is not a PR effect.
⚠️ 34 not_sure 1259 1185 -5.9% <0.0001 aggregation: This GROUP BY on URL reads plain String columns. Only the JSON/Object serialization path changed, so the -5.9% is not attributable to this PR.

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

🟢 No significant changes

Debug info
  • StressHouse run: c5bc8aa0-6e14-42ce-8559-47b2cbd2f37e
  • MIRAI run: eb00288b-86a2-482d-83d9-7f8abd18792e
  • PR check IDs:
    • clickbench_1936092_1790419248
    • clickbench_1936098_1790419248
    • clickbench_1936104_1790419248
    • tpch_adapted_1_official_1936111_1790419248
    • tpch_adapted_1_official_1936126_1790419248
    • tpch_adapted_1_official_1936162_1790419248

Route the full parent lookup through the part serialization cache for every `JSON` subcolumn.

Related: ClickHouse#110957
Measure declared typed-path reads from many wide parts so serialization setup remains visible.

Related: ClickHouse#110957
Detect `JSON` behind supported wrapper types so MergeTree readers reuse the part cache without changing unrelated subcolumn serialization.
@rorylshanks

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110957&sha=90a374d351eb9475c2ad4bde5c6f17cafce082a6&name_0=PR&name_1=AST%20fuzzer%20(amd_debug%2C%20targeted%2C%20old_compatibility) and provide a fix in a separate PR. It still reproduces after restoring the non-JSON serialization path to master behavior; related type-mismatch tracking: #113891. If the fix is already in progress, link it here.

Comment thread src/DataTypes/DataTypeObject.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. This is a pre-existing defect on master, not caused by this PR, so your A/B holds.

I reproduced it on master at 82cfa6a421bb9c1e99185e960e92565543455b3c, with a debug build that contains none of this PR's code (containsObjectType is absent from the binary, while SharedPartColumns::buildSerializationGroup is present), and got the same message:

Unexpected return type from materialize. Expected Array(Nullable(Float64)). Got Array(Nullable(Tuple(String, Float64))).

Minimal repro:

SET enable_nullable_tuple_type = 1;
CREATE TABLE t (`id` UInt64, `arr.id` Array(UInt64), `arr.nested` Array(Tuple(a String, b Float64)))
ENGINE = MergeTree ORDER BY id
SETTINGS share_nested_offsets = 1, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT number, range(number % 3), arrayMap(x -> tuple(toString(x), toFloat64(x)), range(number % 3)) FROM numbers(100);
ALTER TABLE t DROP COLUMN `arr.nested`;
ALTER TABLE t ADD COLUMN `arr.nested` Array(Nullable(Tuple(a String, b Float64)));
SELECT sum(length(nb)) FROM (SELECT id, `arr.nested`.b AS nb, `arr.id` AS aid FROM merge(currentDatabase(), '^t$'));

The read hands the parent column's data back under the subcolumn's name and declared type. Four conditions are each necessary, and removing any one of them returns a correct result: share_nested_offsets = 1; the Nested member dropped and re-added with a different type; the re-added element type being Nullable(Tuple(...)) (Nullable inside the tuple, an element reorder, LowCardinality inside, and a plain element retype all stay correct); and reading through merge(), whose converting step is what type-checks the block, since the direct read is correct and returns [NULL], [NULL,NULL]. It is a logical error, so release builds raise Code: 49 and only debug and sanitizer builds abort.

Why only this PR's CI shows it: the targeted fuzzer matched 0 of your 7 changed lines against coverage and fell back to a keyword match on Shared, taken from SharedPartColumns.cpp, which pulled 04756_nested_sibling_shared_offsets_prefetch.sql into the fuzzed set.

[find_tests] done in 0.31s: 0/7 lines matched, 0 unique tests selected
[find_tests] keyword-fallback: 50 tests matching keywords ['Shared'] (from 75 candidates)

That fixture is not fuzzed anywhere else, which is why this type pair has 0 hits on master and 0 on any other PR over 120 days of CIDB. It is test selection, not causation.

Independently of the repro, your diff cannot reach this column. Every behavioural hunk is gated on containsObjectType, which is false for Array(Nullable(Tuple(String, Float64))), and the one ungated change (the tryGetSerialization probe now placed first in LoadedMergeTreeDataPartInfoForReader::getSerialization) is equivalent to master here, because IMergeTreeDataPart::getSerialization(name) is tryGetSerialization(name) plus a throw on null.

The fix belongs in the wide-part subcolumn read path in IMergeTreeReader, where I have #115964 open for a neighbouring case. I will link the fix for this shape here. #113891 is a different type pair, so I am not treating it as the same defect.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #116553

Two corrections to my comment above, since the defect turned out wider than my first reading.

The site is not IMergeTreeReader. getBaseTypeOfArray stops descending at the Nullable between the array and the tuple, and fillMissingColumns stripped the whole tuple-element path from the subcolumn name regardless of how much the descent had consumed, so the default column for the missing member was built with the parent type. The descent now reports the prefix it consumed and the caller leaves the remainder to IDataType::getSubcolumn.

merge() is also not necessary. The direct read is affected too, it only looked correct because nothing type-checks the block there and a NULL tuple prints like a NULL scalar; SELECT materialize(...) on the same table fails identically, and ENGINE = Memory reaches it as well. So what is necessary is the shared offsets, the member re-added with a wrapper between the array and the tuple, and a read of its subcolumn.

Issue 113891 is still a different site and I do not claim it is fixed.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Check regular subcolumns in the part metadata before invoking the existing
serialization-based presence check. Preserve the existing lookup for dynamic
paths and the custom serialization handling for `Quantize`.

Cover both compact mark formats, renamed columns, and dotted-name collisions.
Extend the existing performance test to both compact layouts. Local medians
improved by 21% without substream marks and 55% with them; dynamic-path and
wide-part controls showed no significant change. Builds and six focused
checks passed.

Related: ClickHouse#110957
Related: ClickHouse#113099 (review)
Reuse the same parent serialization, deserialization state, and cached
column for full-column and subcolumn requests without substream marks.
Copy only the current granule when the cached full column spans earlier
granules. Cover both request orders and block boundaries, and add a
mixed full-column/subcolumn performance query.

ClickHouse#110957 (comment)
Related: ClickHouse#111020

ClickHouse#110957
rorylshanks and others added 3 commits September 13, 2026 14:25
Reading a full `JSON` column caches the accumulated output block. Slice
that cached parent to the current granule before extracting shared paths,
so subsequent subcolumn reads do not repeatedly scan earlier rows.

Add functional coverage for shared paths across granules and block
boundaries, plus a focused performance test. With compatible existing
build dependencies, seven local runs improve the full-parent/shared-path
median from 4.4583 s to 0.28334 s. The subcolumns-only control has no
statistically significant change. Both functional regressions pass.

ClickHouse#110957 (comment)
@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit 13595b6 Sep 27, 2026
172 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@rorylshanks @scanhex12 @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

alexey-milovidov added a commit that referenced this pull request Sep 28, 2026
…ations-in-mergetree-readers

Resolved conflicts with #110957 (`JSON` subcolumn serialization cache): the
general part-serialization path of this PR (`tryGetSerializationFromPart`)
covers the `containsObjectType` branch added on master, so that branch is
dropped. Kept master's sharing of `serializations_of_full_columns` for
full-column requests in `Compact` parts and its `withRegularSubcolumns`
presence checks in `MergeTreeReaderCompact`, combined with `hasSubcolumnInPart`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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 comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... 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.

6 participants