Repository navigation
Fix performance regression in text serialization of JSON and Dynamic columns - #115852
Conversation
…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]>
|
Workflow [PR], commit [54efb0d] Summary: ❌
AI ReviewSummaryThis PR removes the worst Findings
Tests
Final VerdictStatus:
LLVM Coverage ReportMeasured on commit 54efb0d.
Changed lines: Changed C/C++ lines covered: 123/133 (92.48%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units12 translation units recompiled, 35 s compile time in total, 12 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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_officialFlagged queries (2 of 22)
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
|
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.
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)
- 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)
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.
| 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()) |
There was a problem hiding this comment.
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.
…ation of JSON and Dynamic columns
Backport #115852 to 26.8: Fix performance regression in text serialization of JSON and Dynamic columns
Backport #115852 to 26.7: Fix performance regression in text serialization of JSON and Dynamic columns
Backport #115852 to 26.6: Fix performance regression in text serialization of JSON and Dynamic columns
|
follow up #117655 |
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.
…t serialization of JSON and Dynamic columns
…t serialization of JSON and Dynamic columns
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]>
Closes: #115796
Related: #96563
SerializationDynamic::serializeTextImplgot the serialization of the wholeVarianttype forevery value, which builds the serializations and names of all the variants and goes through the
globally locked
SerializationObjectPool.SerializationJSONcalls 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.toStringover a 1M-rowJSONtable, 200k rows,max_threads = 4:JSON, 10 dynamic pathsJSON(max_dynamic_paths=0)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix performance regression introduced in 26.4 when writing
JSONandDynamiccolumns in text formats.Workflow [PR]
Sync PR [sync-upstream/pr/115852]
Version info
26.8.3.13,26.7.7.8,26.6.5.25