Skip to content

Use cached serializations for Dynamic fields - #113344

Merged
alexey-milovidov merged 22 commits into
ClickHouse:masterfrom
rorylshanks:optimize-dynamic-field-serialization-cache
Sep 27, 2026
Merged

alexey-milovidov merged 22 commits into
ClickHouse:masterfrom
rorylshanks:optimize-dynamic-field-serialization-cache

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

SerializationDynamic::deserializeBinary decodes the data type of each Field and then calls getDefaultSerialization. This enters the globally locked SerializationObjectPool for every value.

This is particularly expensive when reading nested paths from JSON columns stored using map_with_buckets. Reading a nested path from an Array(JSON) value reconstructs the complete path value and deserializes every inner Dynamic field, repeatedly acquiring the global serialization-pool lock.

Use the existing thread-local cache returned by getDataTypesCache to obtain the serialization instead. Apply the same change symmetrically to SerializationDynamic::serializeBinary. Pass the already decoded type to the cache in both Dynamic serialization and ColumnObject shared-data hashing, avoiding type-name reparsing on a cache miss.

The change was tested with one million rows from the JSONBench Bluesky dataset. The benchmark read data.commit.record.facets[].features[].tag from a JSON column using map_with_buckets.

Mode Before After Improvement
max_threads=1 8.34 QPS 10.62 QPS 27%
max_threads=16 10.75 QPS 16.19 QPS 51%
8 concurrent queries with max_threads=4 43.57 QPS 96.83 QPS 122%

The advanced shared-data format already reads requested substreams directly and normally bypasses this field-level deserialization path.

A performance test in tests/performance/dynamic_field_serialization_cache.xml generates one million rows whose nested value path alternates between string, integer, array, and object values. With the 2026-09-23 CI AMD release binaries, seven local runs measured 1.751 s before and 0.936 s after (46.5% lower median latency). Reversing the server order measured 1.739 s before and 0.928 s after (46.7% lower latency). The previous 100,000-row version measured 4.4% slower locally with the same binaries.

Changelog category (leave one):

  • Performance Improvement

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

Improve nested JSON path read performance with map_with_buckets by reusing thread-local serializations for Dynamic values.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f6fffd]

Summary: ✅


AI Review

Summary

This PR switches Dynamic binary field and row serialization paths, plus ColumnObject shared-data hashing, to reuse thread-local serializations when the type is already decoded, and adds deep-type regression coverage together with a targeted performance workload for the JSON map_with_buckets read path. I did not find any unresolved review findings in the current diff: the previously missing cold-cache Field coverage is now present, the performance claim is backed by the benchmark evidence in the PR, and current CI is green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0f6fffd.

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

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

Full report · Diff report

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

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 0f6fffdd0d68d4a71bfa556c196f1fcf6c54fbdb 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 Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only Dynamic and JSON (Object) value serialization: data-type serialization lookups now go through the types cache, with the type object passed along. It also adds gtests and a new performance test. The one flagged row is clickbench Q9, at +10.8% (432 ms vs 390 ms). That result falls inside master's recent 367–442 ms range, and the query runs over plain columns that never reach the changed Dynamic/JSON paths, so leaving it suppressed is the right call. Neither clickbench nor tpch_adapted_1_official shows an effect that can be traced to this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 9 not_sure 390 432 +10.8% <0.0001 The +10.8% delta (432 ms vs 390 ms) sits inside master's recent 367–442 ms range. This query never touches the Dynamic/JSON serialization code the PR changes, so the suppression stands.

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: ee02e7f6-1b18-4064-b136-95d574089840
  • MIRAI run: 8415a7a0-1391-4f79-9c6c-9e0e9ec2f8a5
  • PR check IDs:
    • clickbench_1932962_1790417965
    • clickbench_1932975_1790417965
    • clickbench_1932981_1790417965
    • tpch_adapted_1_official_1932987_1790417965
    • tpch_adapted_1_official_1933019_1790417965
    • tpch_adapted_1_official_1933033_1790417966

@rorylshanks

Copy link
Copy Markdown
Contributor Author

🕵 The previous CI run had two unrelated failures. The docs-example width mismatch is fixed by #117827 and is now included via merge commit e8859ef. @groeneai, please investigate the targeted AST fuzzer failure in a separate PR: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113344&sha=d4e8cd794e59e838df0be3197a7cdd5fc65a5927&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29. It fails on sum(t.m['k1']) over Nullable(Tuple(Map(...))); this PR only changes Dynamic serialization paths, and no matching open issue or fix PR was found.

@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the AST fuzzer (amd_debug, targeted) red on d4e8cd7 (Bad cast from type DB::ColumnNullable to DB::ColumnVector<unsigned long> on SELECT count() IGNORE NULLS, sum(t.m['k1']) FROM t_tuple_map_version__fuzz_48, STID 1499-34b9) and will follow up in this thread with a separate PR or with my findings.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Investigated. This is not caused by your PR and is unrelated to Dynamic serialization.

Attribution: it reproduces on pristine master (2f4969d631ba82762d234e05880ba2bda0a59f67, debug) with none of your diff applied, and the fuzzed table has no Dynamic or JSON column, so the fuzzed dynamic_serialization_version table setting is inert.

Root cause is optimize_functions_to_subcolumns, not aggregation. In a Nullable(Tuple(...)) a member whose own type cannot be inside Nullable (here Map) is exposed as a bare Map, but that member's leaf subcolumns are wrapped by the outer null map. FunctionToSubcolumnsPass rewrites t.m['k1'] to the subcolumn t.m.key_k1 and hardcodes its type as the map's value type, so the two disagree:

  • query tree: COLUMN t.m.key_k1, result_type: UInt64
  • ReadFromMergeTree header: t.m.key_k1 Nullable(UInt64)

sum is therefore instantiated with no null adapter and assert_cast receives a ColumnNullable.

SET enable_nullable_tuple_type = 1;
CREATE TABLE t_fz (key Date32, t Nullable(Tuple(m Map(LowCardinality(String), UInt64))))
ENGINE = MergeTree ORDER BY key;
INSERT INTO t_fz SELECT number, tuple(map('k1', number)) FROM numbers(3);
INSERT INTO t_fz SELECT 100, NULL;
SELECT sum(t.m['k1']) FROM t_fz;          -- LOGICAL_ERROR, server abort in debug and sanitizer builds
SELECT t.m['k1'] FROM t_fz ORDER BY key;  -- 0, 1, 2, \N  under a UInt64 column

With SETTINGS optimize_functions_to_subcolumns = 0 the same two queries give 3 and 0, 1, 2, 0, so the plain SELECT is a wrong result in its own right, independent of the abort.

Fixing PR: #115777 (external, open). It replaces the pass's nullability check with a stricter guard that compares the hardcoded type against the resolved storage type and applies it to the map-key rewrite, so Nullable(UInt64) != UInt64 skips the rewrite. I am not opening a competing PR, since that would change the same functions it is already rewriting. This red should clear on your branch once it merges.

rorylshanks and others added 5 commits September 5, 2026 21:18
Pass the decoded type to the existing serialization cache so a cache miss
does not reparse its name. Cover a deeply nested shared value with a cold
cache in the existing binary-encoding tests.

Review: ClickHouse#113344 (comment)
hash.update(type_name);
auto tmp_column = value_type->createColumn();
getDataTypesCache().getSerialization(type_name)->deserializeBinary(*tmp_column, buf, getFormatSettings());
getDataTypesCache().getSerialization(type_name, value_type)->deserializeBinary(*tmp_column, buf, getFormatSettings());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only fixes the ColumnObject branch. The sibling Dynamic hash path in src/Columns/ColumnDynamic.cpp:906-914 still decodes the shared-variant type and then calls type->getDefaultSerialization()->deserializeBinary(...), so updateHashWithValue still pays the global serialization-pool lookup once per row for Dynamic values stored in the shared variant.

That method is on the hot path for ColumnsHashing::hash128, Block::updateHash, arrayDistinct, and other hash-based operators, so queries like DISTINCT / uniq* / hash joins over a Dynamic(max_types=0) key still miss the optimization this PR is introducing. Please switch that sibling branch to getDataTypesCache().getSerialization(type->getName(), type) as well, and add a cold-cache regression for it.

@rorylshanks rorylshanks Sep 26, 2026 •

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.

🕵 Thanks — agreed that ColumnDynamic::updateHashWithValue has the same pattern for values stored in the shared variant. This PR is scoped to Field binary (de)serialization of Dynamic values (the nested JSON path read with map_with_buckets) plus passing already-decoded types to lookups that already went through the cache. Switching the ColumnDynamic hashing path to the cache changes a different hot path (DISTINCT/uniq*/hash joins over Dynamic) and deserves its own benchmark and test, so I'd prefer to keep it for a follow-up PR rather than extend this one.

Round-trip deeply nested values through `SerializationDynamic::serializeBinary`
and `SerializationDynamic::deserializeBinary` for `Field`, so both changed call
sites run on a cache miss with a type whose name cannot be reparsed.

Review: ClickHouse#113344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 a606bff 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
qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 5, 2026
Query #0 (max_threads=16, 1M rows) was over the report floors in 32% of
amd and 13% of arm master runs between 2026-10-25 and 2026-11-04, and the
two servers' medians differed by more than 10% in 47% of amd and 22% of
arm reports, with a within-run CV of about 1%. Both servers execute the
same instructions (84.1-84.5 G per process on amd), but one of them can
need up to 30% more cycles for the whole life of the process. Every
reading thread copies the pooled serialization pointer per value, so the
per-row cost and the per-process spread grow with the number of reading
threads.

2 is the smallest thread count that still measures ClickHouse#113344: with one
reading thread its merge is 1-8% slower than its parent. With the default
merge_tree_min_rows_for_concurrent_read (163840 rows, 20 marks) and
merge_tree_min_bytes_for_concurrent_read (240 MiB, 24 marks) a second
thread gets its own share of a single part only from 48 granules on, so
32 granules were read by one thread. With both settings 0 each thread
reads 16 granules. 262144 rows keep a run at about 1 s on amd; at the
arm/amd ratio of other 2-thread queries (p90 1.45x) arm stays under the
2 s slow-query limit.

Local validation, two official master servers pinned to the same 8 cores
of one NUMA node, both with max_threads 8, as in the amd job: 12 A/A
cycles with fresh server processes. The new query differed by at most
3.1% between the servers (stat_threshold median 0.016, max 0.032). User
CPU per 1000 rows across the 24 processes was 7.43-7.98 ms (max/min
1.075). In the same process pairs the old query differed by up to 15.2%
with non-overlapping runs (max/min 1.31). Parent 199f114 vs merge
a606bff of ClickHouse#113344: the merge is 1.29-1.36x faster in 3 of 3
cycles. Every run used 2 reading threads (cpu/wall 1.95-1.98) and read
262144 rows. Median run 1.04 s.

The rig differs from CI in two ways. It sets remap_executable=0, and it
reads each server binary into the page cache of the pinned node right
before each start, because the box has six NUMA nodes and CI runners
have one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... 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