Skip to content

Fix performance regression in text serialization of JSON and Dynamic columns - #115852

Merged
fm4v merged 8 commits into
masterfrom
fix-dynamic-text-serialization-per-value-pool-lookup
Sep 2, 2026
Merged

fm4v merged 8 commits into
masterfrom
fix-dynamic-text-serialization-per-value-pool-lookup

Conversation

@Avogar

@Avogar Avogar commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Closes: #115796
Related: #96563

SerializationDynamic::serializeTextImpl got the serialization of the whole Variant type for
every value, which builds the serializations and names of all the variants and goes through the
globally locked SerializationObjectPool. SerializationJSON calls it once per JSON path per row.

Resolve the exact variant by its global discriminator and take its serialization from the
thread-local DataTypesCache, like the row-level binary serializer already does.

toString over a 1M-row JSON table, 200k rows, max_threads = 4:

master this PR 26.2
JSON, 10 dynamic paths 6.4 s 0.26 s 1.0 s
JSON(max_dynamic_paths=0) 8.2 s 1.79 s 2.4 s

Changelog category (leave one):

  • Performance Improvement

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

Fix performance regression introduced in 26.4 when writing JSON and Dynamic columns in text formats.


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

Version info

  • Backported to: 26.8.3.13, 26.7.7.8, 26.6.5.25

…rialization

`SerializationDynamic::serializeTextImpl` obtained the serialization of the
whole `Variant` type for every value, and `SerializationJSON` calls it once per
JSON path per row. `DataTypeVariant::doGetSerialization` builds the
serializations and names of all variants to compute the pool key and then goes
through the globally locked `SerializationObjectPool`, so a 200k-row scan of a
10-path `JSON` column did ~2*10^6 pool lookups under a shared mutex.

Resolve the exact variant by its global discriminator instead and take its
serialization from the thread-local `DataTypesCache`, the way the row-level
binary serializer already does. The whole-`Variant` serialization is no longer
needed, so `NULL` is handled directly with the same `SerializationNullable`
helpers `SerializationVariant` used.

`toString` over a 1M-row `JSON` table, 200k rows, `max_threads = 4`, three
interleaved rounds on the same data:

| | master | patched | 26.2 |
| --- | --- | --- | --- |
| `JSON`, 10 dynamic paths | 6.32-6.50 s | 0.25-0.28 s | 1.00-1.12 s |
| `JSON(max_dynamic_paths=0)` | 7.84-8.92 s | 1.78-1.79 s | 2.31-2.43 s |

Output is byte-identical to master over all 1M rows in both configurations.

Closes: #115796

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [54efb0d]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-4e52) FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb

AI Review

Summary

This PR removes the worst JSON and Dynamic text-serialization pool lookups by adding a thread-local type cache, query-scoped invalidation, and special handling for non-poolable serializers. I found one remaining major gap: Dynamic rows whose logical type is JSON still rebuild SerializationJSON per row in the text path, so the Dynamic half of the performance claim is still incomplete.

Findings

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationDynamic.cpp:955-968] SerializationDynamic::serializeTextImpl now goes through DataTypesCache for both the shared-variant and exact-variant branches, but DataTypesCache intentionally rebuilds a fresh serializer whenever supportsPooling() == false. SerializationJSON is non-poolable, so Dynamic values stored as exact or shared JSON still allocate a new SerializationJSON per row. That leaves a legitimate Dynamic text-output path paying the same hot getDefaultSerialization() cost the PR is supposed to remove.
  • Suggested fix: reuse a query-local or column-local cache for non-poolable serializers on this path as well, for example by making ColumnDynamic::getVariantSerialization usable from the const text-output path and covering decoded shared-variant types.
Tests
  • ⚠️ The added tests/performance/json_to_string.xml benchmark exercises plain JSON and JSON(max_dynamic_paths=0), but not Dynamic. The cloud benchmark bot also says its suites do not hit this path, so there is still no focused proof that the advertised Dynamic improvement holds end to end. A minimal proof would be a small Dynamic benchmark with a typed JSON variant, ideally with both exact-variant and shared-variant rows.
Final Verdict

Status: ⚠️ Request changes

  • Eliminate the remaining per-row SerializationJSON rebuild in Dynamic text serialization, and add focused Dynamic performance coverage for that path.

LLVM Coverage Report

Measured on commit 54efb0d.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 123/133 (92.48%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 54efb0d8f with master f3a460fe0 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR is a targeted optimization of JSON/Dynamic text serialization (DataTypesCache scoping/sizing plus per-variant serialization in SerializationDynamic), and adds a json_to_string perf test where any real effect should appear. None of the flagged ClickBench or TPC-H queries serialize JSON/Dynamic columns, so all four deltas are off-path and downgraded to not_sure - including the ClickBench Q17 -46.4% "improvement," whose source median lands exactly at the floor of master's variance band [240-567 ms], marking it as master's fast tail rather than a PR effect. The two TPC-H regressions are small in absolute terms (+14 ms and +36 ms, the latter on very noisy measurements) and cannot plausibly be driven by this serialization change. No credible regression or improvement is attributable to this PR.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 448 240 -46.4% <0.0001 ClickBench Q17 has no JSON/Dynamic columns, so this JSON/Dynamic text-serialization change can't touch its path; the 240 ms source median sits at the floor of master's variance band [240-567 ms], so the -46.4% is run-to-run variance.
⚠️ 28 not_sure 1120 1052 -6.1% <0.0001 Already not_sure; the small -6.1% delta is on an off-path query (no JSON/Dynamic serialization) with mixed test signals, so no action is warranted.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 81 +20.9% <0.0001 TPC-H Q7 is a join/aggregation over numeric and string columns and never exercises the JSON/Dynamic serialization this PR changes, so the +20.9% (+14 ms) reads as run-to-run variance, not a PR effect.
⚠️ 17 not_sure 64 100 +56.2% <0.0001 TPC-H Q17 touches none of the JSON/Dynamic serialization paths this PR modifies, and its source measurements were very noisy, so the +56.2% (+36 ms) is not attributable to this change.

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: cc5c6745-c415-4640-9eb8-379218afeded
  • MIRAI run: 9afa4588-a2d5-4e8e-9930-88bc4bbb42d1
  • PR check IDs:
    • clickbench_803929_1788302450
    • clickbench_804041_1788302467
    • clickbench_804158_1788302477
    • tpch_adapted_1_official_804262_1788302496
    • tpch_adapted_1_official_804268_1788302496
    • tpch_adapted_1_official_804290_1788302496

DataTypesCache is thread_local and persists across unrelated queries
served by the same worker thread, keyed only by type name. But a type
name does not uniquely determine a type/serialization: DateTime without
an explicit timezone captures the query's session_timezone setting at
construction (DateLUT::instance() reads it from the current thread's
query context). A cache entry built under one query's session_timezone
could therefore be served to a later, unrelated query, rendering
DateTime values in the wrong timezone (01825_json_type_ghdata_insert_select
flaked on this in CI: same settings, same data, correct or wrong result
depending only on which queries a worker thread had previously served,
9/9 passes on isolated rerun).

This mirrors a known hazard already documented on SerializationJSON,
which disables pooling for the same reason (cached DateTimeNode objects
picking up the wrong timezone across queries).

Clear the cache whenever the owning thread's query context changes,
tracked via a weak_ptr and compared with owner-based identity so it is
immune to context object address reuse. This keeps full caching within
a single query (preserving this PR's performance fix) while preventing
reuse across queries.
Comment thread src/DataTypes/DataTypesCache.cpp Resolved
fm4v added 2 commits September 1, 2026 17:55
The thread-local DataTypesCache kept only 16 non-simple entries and cleared the whole map when full, while Dynamic allows up to 255 named variants plus an unbounded set of types in the shared variant. Interleaving more than 16 distinct non-simple variant types made every lookup clear and rebuild the cache, and on the shared-variant text path each miss additionally re-parsed the type name through DataTypeFactory even though the decoded type was already in hand.

Grow the cache to 256 entries (matching ColumnDynamic::SERIALIZATION_CACHE_MAX_SIZE) and add a getSerialization overload that reuses an already constructed type on a cache miss instead of a DataTypeFactory lookup. Use it on both text serialization paths of SerializationDynamic.

Addresses review comment: #115852 (comment)
A functional test cannot deterministically force the same pool thread to serve two queries, so test the invalidation directly: DateTime without an explicit timezone captures the current query's session_timezone at construction, which makes the captured timezone of the cached type observable. The test verifies that entries are reused within one query and rebuilt under a new query context with a different session_timezone.

Addresses review comment: #115852 (comment)
Comment thread src/DataTypes/DataTypesCache.cpp Resolved
- gtest_data_types_cache.cpp: include Common/DateLUTImpl.h; the test
  chained TimezoneMixin::getTimeZone() (returns const DateLUTImpl&)
  into DateLUTImpl::getTimeZone() (returns const std::string&), but
  only the forward declaration was visible, failing Build (arm_tidy).

- DataTypesCache: clearIfQueryContextChanged() invalidated only on
  Context identity, but clickhouse-client keeps one long-lived
  client_context for the whole session and mutates session_timezone
  in place between queries (ClientBase::onTimezoneUpdate and the
  use_client_time_zone seeding), which identity alone can't detect.
  Now also track the session_timezone value itself and clear the
  cache when it changes, in addition to the context-identity check.

- Add a regression test for the in-place mutation case, alongside
  the existing query-context-change test.

Addresses #115852 (comment)
Comment thread src/DataTypes/DataTypesCache.cpp Resolved
fm4v added 2 commits September 1, 2026 20:15
SerializationJSON reports supportsPooling() == false because it holds
mutable per-use state in its extraction tree, and reuse across queries
"leads to incorrect behaviour" (see the comment in
SerializationJSON::create). But DataTypesCache::getCacheElement cached
type->getDefaultSerialization() unconditionally, so a Dynamic value
holding a nested JSON now had its serialization pinned in the
thread-local cache and reused across queries via the SerializationDynamic
text fast path this PR added - the exact kind of sharing supportsPooling()
exists to prevent, and query-scoped invalidation alone can't fix it since
clickhouse-client keeps one client context (hence one query scope) for
its whole session.

Cache only the type when its default serialization is non-poolable,
leaving Element::serialization null; getSerialization then rebuilds a
fresh serialization on every lookup for those types, matching what
happened before this PR. The type itself is a plain immutable value
object (confirmed DataTypeObject::doGetSerialization is rebuilt fresh
every call, never memoized), so caching it is safe and keeps the
type-name-parse speedup even for JSON. Poolable types are unaffected.

Add a regression test asserting JSON's type is pooled but its
serialization is not.

Addresses #115852 (comment)
CI: Unit tests (asan_ubsan/msan/tsan) failed with "No test result file" -
the gtest binary aborted on DataTypesCache.ReusesEntriesWithinOneQuery
with Logical error: '!current_thread', since the binary's main thread
already has a MainThreadStatus attached and ThreadStatus's constructor
asserts none is already current.

Reset current_thread before constructing the local ThreadStatus and
restore it afterward via a small RAII guard declared just before it,
matching the existing FileCacheTest fixture pattern in
src/Interpreters/tests/gtest_filecache.cpp.
Comment on lines +955 to +968
SerializeNull serialize_null)
{
const auto & dynamic_column = assert_cast<const ColumnDynamic &>(column);
const auto & variant_column = dynamic_column.getVariantColumn();
auto global_discr = variant_column.globalDiscriminatorAt(row_num);

if (global_discr == ColumnVariant::NULL_DISCRIMINATOR)
{
serialize_null(ostr);
return;
}

/// Check if this row has value in shared variant. In this case we should first deserialize it from binary format.
if (variant_column.globalDiscriminatorAt(row_num) == dynamic_column.getSharedVariantDiscriminator())
if (global_discr == dynamic_column.getSharedVariantDiscriminator())

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.

⚠️ Dynamic(JSON) still does a per-row SerializationJSON rebuild here.

DataTypesCache::getSerialization(type_name, type) now returns type->getDefaultSerialization() on every lookup when the default serializer has supportsPooling() == false, and SerializationJSON is exactly that case. As a result, both the shared-variant branch above and this exact-variant branch still construct a fresh SerializationJSON for every Dynamic row whose logical type is JSON, which is the same hot operation the original regression report called out.

ColumnDynamic already has a per-column serialization_cache for these type-name lookups, but this text-output path bypasses it. Can we make the text path reuse a query-local or column-local cache for non-poolable serializers as well (including decoded shared-variant types)? The added perf test only covers plain JSON, so this remaining Dynamic(JSON) path is still unproven.

@fm4v
fm4v added this pull request to the merge queue Sep 2, 2026
Merged via the queue into master with commit 73ba47d Sep 2, 2026
171 of 174 checks passed
@fm4v
fm4v deleted the fix-dynamic-text-serialization-per-value-pool-lookup branch September 2, 2026 08:33
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 2, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #115852 to 26.8: Fix performance regression in text serialization of JSON and Dynamic columns
fm4v added a commit that referenced this pull request Sep 2, 2026
Backport #115852 to 26.7: Fix performance regression in text serialization of JSON and Dynamic columns
fm4v added a commit that referenced this pull request Sep 2, 2026
Backport #115852 to 26.6: Fix performance regression in text serialization of JSON and Dynamic columns
@fm4v

fm4v commented Sep 2, 2026

Copy link
Copy Markdown
Member

follow up #117655

raimannma pushed a commit to raimannma/ClickHouse that referenced this pull request Sep 2, 2026
Follow-up to ClickHouse#115852, which merged
before a last review comment was addressed:
ClickHouse#115852 (comment)

Making DataTypesCache::getCacheElement skip caching the serialization for
types with supportsPooling() == false (e.g. SerializationJSON) reintroduced
the exact performance regression the original PR fixed, but only for
Dynamic(JSON): a fresh SerializationJSON was rebuilt on every row again in
SerializationDynamic's text fast path.

That restriction was more conservative than necessary. supportsPooling()'s
contract, and SerializationJSON's own documented failure mode, are both
specifically about reuse *across queries* (e.g. a cached DateTimeNode
capturing the wrong session_timezone). The cache already prevents exactly
that: it is thread-local and is cleared on every query-context change and
on session_timezone mutation. Reuse *within* one query is an established,
trusted pattern already relied on elsewhere for the same objects, via
ColumnDynamic's own per-column serialization_cache.

I considered instead routing SerializationDynamic's text path through that
per-column cache directly, but a ColumnDynamic instance is not always
exclusive to one query: StorageMemory and the query result cache can hand
the very same column instance to concurrently-running queries, and it has
no invalidation hook at all, so pooling from the read side there would
both race and reintroduce cross-query staleness. The thread-local cache
with query/timezone-scoped invalidation is the safe place for this.

Extend the added perf test with a Dynamic column holding JSON values, and
replace the gtest asserting non-pooling with one asserting pooling within
a query and invalidation across queries.
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…t serialization of JSON and Dynamic columns
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…t serialization of JSON and Dynamic columns
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 5, 2026
Queries 0 and 2 of `tests/performance/json_to_string.xml` are a level shift
on amd: within one server the 7 runs agree (in-run CV median ~1%), but the
two servers' medians are more than 10% apart in 25.5% / 23.6% of 286-288 amd
master runs (2026-10-25 15:00 .. 2026-11-04 11:00 UTC), 29 / 35 runs over the
report floors, and the learned max_diff is 0.40, so a regression below ~40%
is invisible. Query 1 is quiet on amd (1.0%).

The level is drawn per server process, not per binary: master runs chain the
same official build as the candidate of run k and the reference of run k+1,
and consecutive log-ratios are uncorrelated (lag-1 r -0.04 / +0.01 over 353
pairs). Both servers do the same work (1 part, 62 marks, 500000 rows every
run), and the slow server burns proportionally more user CPU (r 0.96-0.97).
Queries 0 and 2 move together (r 0.89), no other query of the same jobs
above r 0.23. For every value of every JSON path,
SerializationDynamic::serializeTextImpl copies a SerializationPtr from the
thread-local DataTypesCache; those are copies of the pooled serialization,
so all query threads write the same reference counter, 8 times per row.
With one thread there is no cross-thread traffic on it.

Locally (two servers of the same master build 989ecd8, each pinned to
8 physical cores of one NUMA node with max_threads = 8 as in the amd job,
24 restarts):
- Before, the multi-threaded form burns ~1.9x the CPU for the same rows
  (query 0: 1.09-1.32 s user CPU per run on 5.3-6.6 busy cores, after: 0.60 s
  on one core).
- The slower server's median over the faster one's, median over restarts:
  queries 0 / 2 3.4% / 2.4% before (max 12.3% / 21.2%), 0.3% / 1.0% after
  (max 4.7% / 2.5%); query 1, which is unchanged, 1.3% / 1.7% in the same
  two runs. Paired on the same two processes, the gap before
  exceeds the gap after in 20/24 (query 0, sign test p 0.0008) and 19/24
  (query 2, p 0.003) restarts; query 1: 9/24 (p 0.92).
- After: 0 of 48 query-restarts over the report floors (before: 1 of 48).
  Medians 0.618 s / 0.628 s per run.
- The CI rate itself does not reproduce on that machine: before, 1 of 24
  restarts had queries 0 or 2 more than 10% apart with a CPU burn gap.

The test still catches what it was added for (ClickHouse#115852): at max_threads = 1,
26.8.2.7 is 4.38x / 4.32x slower than 26.8.3.105 on queries 0 / 2 (median of
`clickhouse local --time`).

Nothing else changes: same fixture, same per-value toString path, query 1
untouched, no product change. The product side of the shared counter is
ClickHouse#122464.

Related: ClickHouse#100759

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

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport v26.5-must-backport v26.6-must-backport v26.7-must-backport v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSON -> text serialization is ~4.4x slower since 26.4 (getDefaultSerialization is called per value and now goes through the global serialization pool)

5 participants