Skip to content

Do not share the reference counter of cached serializations between threads - #122464

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:data-types-cache-per-thread-serialization-refcount
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:data-types-cache-per-thread-serialization-refcount

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122356
Related: #120403

Changelog category (leave one):

  • Performance Improvement

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

Multi-threaded queries that serialize or deserialize Dynamic and JSON values one by one use less CPU: the serializations cached per thread no longer share one reference counter between all threads. For example, generateRandom over a JSON(max_dynamic_paths = 4) column uses 40% less CPU with 12 threads.

Description

SimpleDataTypesCache and DataTypesCache are thread-local, but serializations are pooled, so every thread's cache entry holds a copy of the same shared_ptr. Per-value callers such as SerializationDynamic::serializeBinary copy the returned pointer for every value: two atomic operations per value on one control block that all threads of the query write.

The caches now store the pooled serialization through a shared_ptr with a control block of its own (aliasing constructor), so these copies write only the caching thread's counter. The pointee, pooling and getPtr are unchanged. Returning a reference instead would not be safe: a nested (de)serialization, e.g. of Array(Dynamic), can clear the DataTypesCache map while the caller still uses the entry.

On arm, query 1 of generate_random_json fails Performance Comparison (arm_release) on unrelated PRs, e.g. PR #122356, 3/6: 0.974 s -> 2.204 s. Master too: aed77575, 2/6 flags it slower, 0.963 s -> 2.028 s. In their CPU profiles all the extra time is self time of SerializationDynamic::serializeBinary, which contains the two atomic operations on that counter.

On x86_64 (release build, clickhouse local, 16 pinned cores, 10 interleaved runs, max_threads = 12), query 1 takes 6.88 s of CPU instead of 11.54 s, and queries 0, 2, 3 and 4 stay within 0.3%. With one thread, query 1 takes 5.54 s of CPU on both builds. The main remaining cost at 12 threads is the per-lookup lock of the query context in DataTypesCache::clearIfQueryContextChanged, which the open #120403 removes.

Not covered: query 1 of json_to_string (JSON(max_dynamic_paths = 0)), whose per-value path does not use these caches.


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

groeneai and others added 3 commits September 26, 2026 17:21
…hreads

`SimpleDataTypesCache` and `DataTypesCache` are thread-local, but the
serializations they store are pooled (`SerializationObjectPool`), so
every thread's entry held a copy of the same `shared_ptr`: one control
block per type for the whole process. Per-value callers copy the
returned pointer for every value (`SerializationDynamic::serializeBinary`,
reached per shared-data value of a `JSON` column), which is two atomic
operations per value on a cache line written by every thread of the
query.

Store the pooled serialization through a `shared_ptr` with a control
block of its own (aliasing constructor), so these copies write only the
caching thread's counter. The pointee is unchanged: pooling, `getHash`,
`getPtr` (`shared_from_this` stays bound to the pooled control block)
and pointer comparisons are the same, and the holder keeps the pooled
object alive.

This is the arm slow mode of query 1 of `generate_random_json`
(`JSON(max_dynamic_paths = 4)`) that reds `Performance Comparison
(arm_release)` on unrelated PRs: in the CPU profiles of the slow runs all
the extra time is self time of `SerializationDynamic::serializeBinary`,
which contains the two atomic operations on that counter.
https://s3.amazonaws.com/clickhouse-test-reports/PRs/122356/8f85022f252b47a25fe2d5b487c61b95f6fb9303/pr/performance_comparison_arm_release_master_head_3_6/report.html
(ClickHouse#122356)
https://s3.amazonaws.com/clickhouse-test-reports/REFs/master/aed775756f2aef4c5871dfb15eed8065c9bb177a/masterci/performance_comparison_arm_release_master_head_2_6/report.html

Measured on x86_64 (release build, `clickhouse local`, 16 pinned cores,
10 interleaved runs), query 1 at `max_threads = 12`: CPU 11.54 s ->
6.88 s, wall 1.067 s -> 0.641 s; queries 0, 2, 3, 4 within 0.3%. With
one thread query 1 takes 5.54 s of CPU on both builds; what remains at
12 threads is the per-lookup lock of the query context in
`DataTypesCache::clearIfQueryContextChanged` (removed by ClickHouse#120403).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`DataTypesCache.ThreadsDoNotShareSerializationReferenceCounter` took one
serialization per thread, so an implementation that creates the owner at
every lookup instead of once per cache entry passed it, although it copies
the pooled `shared_ptr` per value again. Take a second serialization in the
same thread and assert that it shares the owner of the first one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Narrow the helper comment in DataTypesCache.cpp to pooled serializations: SerializationJSON does not support pooling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 2 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new gtest did not check that two lookups in one thread share the cached counter, so an owner created per lookup would still pass it (gtest_data_types_cache.cpp:165-171) AGREE, fixed @ 581b148 same-thread owner check added; wrapping at lookup time instead of at insertion now fails it (:173), the fix reverted still fails :172
2 💡 The helper comment says every serialization is pooled, but supportsPooling() == false ones (e.g. SerializationJSON) are not (DataTypesCache.cpp:23) AGREE, fixed @ 79d7a2d comment narrowed to pooled serializations; wrapping an unpooled one is harmless (one allocation per cache miss, same ownership)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260926-193400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on x86 with the CI amd_release binary: query 1 of generate_random_json at max_threads = 12 uses 2.3x the CPU of max_threads = 1 in every run (5/5), while queries 0 and 4 stay at 1.0x. The arm slow mode itself cannot be reproduced on x86; the CI CPU profiles of 4 arm runs put all its extra time in the same function.
b Root cause explained? Serializations are pooled, so the thread-local caches hold copies of one shared_ptr per type for the whole process. SerializationDynamic::serializeBinary copies and releases it per value: two atomic operations per value on a control block written by every thread of the query.
c Fix matches root cause? Yes. The caches store the pooled serialization through a shared_ptr with its own control block (aliasing constructor), so the per-value copies write only the caching thread's counter. No test, threshold or harness change.
d Test intent preserved / new tests added? New gtest DataTypesCache.ThreadsDoNotShareSerializationReferenceCounter: it checks the same pooled object, one owner per thread (two lookups in one thread share it) and different owners across threads. The existing performance test generate_random_json covers the speed.
e Both directions demonstrated? Yes. Same-config release A/B at 12 threads: query 1 CPU 11.54 s -> 6.88 s, wall 1.067 s -> 0.641 s; DataTypesCache::getSerialization self time 5.43 s -> 0.25 s (its 1-thread value). The gtest fails with the source change reverted, and also with the counter created at lookup time instead of at insertion; it passes with the change.
f Fix is general across code paths? Yes, one change at the two insertion points covers every per-value copy of a cached serialization (the SerializationDynamic binary, hash and text paths and ColumnObject shared-data hashing). The per-lookup query-context lock is left to #120403; query 1 of json_to_string uses another path and is not covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, it applies to every type the caches store (simple types, Nullable, Array, LowCardinality, Variant, DateTime, poolable or not). The gtest covers a simple and a wrapped type; 852 Dynamic/JSON/Variant stateless tests pass, the remaining failures are environmental and identical on the base binary.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? Yes. The pointee is the pooled object, so pooling, getHash, getPtr (still bound to the pooled control block) and pointer comparisons are unchanged; the holder keeps the pooled object alive and is dropped at thread exit exactly like the pooled pointer before. Queries 0, 2, 3, 4 are within 0.3%.

Session id: cron:clickhouse-impl-slot-5:20260926-154200

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79d7a2d]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 4/6) FAIL
test_keeper_4lw_reconfiguration/test.py::test_no_remove_itself FAIL cidb
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
optimize_time_filter_with_preimage #6 FAIL dashboard
and_function #0 slower query history

AI Review

Summary

This PR changes SimpleDataTypesCache and DataTypesCache so cached serializations keep a per-thread shared_ptr control block while still pointing at the pooled ISerialization object. After reviewing the diff, the current code, and the prior PR discussion, I did not find a correctness, lifetime, concurrency, or compatibility issue that warrants a new review comment.

Final Verdict

✅ No new blocking or major findings.

LLVM Coverage Report

Measured on commit 79d7a2d.

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

Changed lines: Changed C/C++ lines covered: 10/11 (90.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@groeneai
groeneai requested review from Avogar and CurtizJ September 26, 2026 20:07
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR gives serializations cached in DataTypesCache a per-thread reference counter. That cache is reached from Dynamic, JSON and Object column code, not from the plain typed columns that ClickBench and TPC-H read. The Q18 regression (+22.7%) has been downgraded to not sure because the query never runs the changed code. Q28, Q32, Q33 and Q34 (+6.4% to +14.4%) fall inside master's normal range, and that deterministic call is consistent with the diff. All five are memory-heavy GROUP BY queries that slowed together while some source runs shared hosts, which points to benchmark host contention rather than this change.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 884 1085 +22.7% <0.0001 aggregation: This PR only changes reference counting for serializations cached in DataTypesCache, which Dynamic/JSON/Object columns use. Q18 is a GROUP BY over plain typed hits columns and never reaches that cache, so the +22.7% is not attributable to this diff.
⚠️ 28 not_sure 1059 1126 +6.4% 0.0005 aggregation: The +6.4% falls inside master's normal range, and the source run was noisy. The query does not use the changed serialization cache.
⚠️ 32 not_sure 730 836 +14.4% <0.0001 aggregation: The +14.4% falls inside master's normal range. This high-cardinality GROUP BY does not touch the DataTypesCache code this PR changes.
⚠️ 33 not_sure 1132 1263 +11.6% <0.0001 aggregation: The +11.6% falls inside master's normal range. This URL GROUP BY does not use the changed serialization cache.
⚠️ 34 not_sure 1138 1241 +9.1% <0.0001 aggregation: The +9.1% falls inside master's normal range, and the query does not reach the modified DataTypesCache path.

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: c4d86f45-a4ca-44a7-9b92-1b260bb2496e
  • MIRAI run: b015bf78-961f-466f-9cf3-01b9362fb177
  • PR check IDs:
    • clickbench_1995170_1790460477
    • clickbench_1995176_1790460477
    • clickbench_1995182_1790460477
    • tpch_adapted_1_official_1995193_1790460477
    • tpch_adapted_1_official_1995201_1790460477
    • tpch_adapted_1_official_1995216_1790460477

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79d7a2d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / and_function #0 the shard's own report calls it slower: 38 ms -> 48 ms (x1.25). The query is count() over numbers(10000000) with 100 != operands, so it never copies a cached serialization, which is all this PR changes. Since 2026-09-24 16:11Z the same red hit 28 other PRs on arm (29 in total, none on master or amd): about 3% of PR builds run this query ~25% slower, while the reference build was never slow in 1,610 runs over the last 4 days a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (arm_release, master_head, 5/6) / optimize_time_filter_with_preimage #6 dashboard confirmed_regression: 0.446 s -> 0.588 s (+31.7%). #6 is the Date month baseline arm, which runs with optimize_time_filter_with_preimage = 0: a long single-threaded scan whose time swings on arm runners for unrelated PRs and on master alike #122156 (mine, open), which removes that arm
Integration tests (amd_tsan, 4/6) / test_keeper_4lw_reconfiguration/test.py::test_no_remove_itself flaky, and it passed on the retry in the same job: a Keeper leader heartbeat stalled under TSAN, so one node briefly saw no live leader and refused the reconfigure command with Cannot reconfigure cluster because there is no active leader. This PR touches no Keeper code a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122156 (mine, open) for the preimage row, and a fix task is created for each of the other two rows (the same ones as above)

All 169 check runs completed (127 pass, 40 not selected, 2 red), Finish Workflow is green and
CH Inc sync passed. CIDB has no other FAIL or ERROR test row on this head. The shard's 3 too long
is informational: it never fails a shard on its own.

Session id: cron:our-pr-ci-monitor:20260927-003314

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the ledger above: the and_function #0 row is not a failure, and nothing is owed for it.

  • In master_head mode the in-tree slower verdict cannot fail the check. Only the dashboard's confirmed_regression rows (or run errors) do (ci/jobs/performance_tests.py), and on this run that is only optimize_time_filter_with_preimage #6, owned by Remove the disabled-optimization baseline arms from the preimage performance test #122156. Of the 29 PR runs with this slower row since 2026-09-24, 27 were green, and the dashboard scored and_function #0 as noise or did not flag it in all 29.
  • The +25% is code placement, not this change. The per-row loop is Set::executeImplCase for the NOT IN that the analyzer builds from the 100 !=. Its instructions are identical in all 14 arm builds I compared, and it is slow exactly when the function starts at 0x6c0 mod 2 KiB: 7 of 7 slow builds, none of the other 7. A fast build of another PR on the same master base has the same .text start as this one, with the function 64 bytes lower.
  • Official builds draw it too: master 606317db is slow and 71d98544, two commits earlier, is fast, with the same loop code 0xd00 bytes apart.

This is the placement class of #122350 (comment). Option (A) there would not have prevented this row, because the two PR builds above already share one .text start and one set of flags.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_keeper_4lw_reconfiguration/test.py::test_no_remove_itself row of the ledger above: #122495.

pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 27, 2026
…g briefly has no live leader

The test sends `rcfg` and assumes the receiving node sees a live leader at
that moment. A leader heartbeat gap longer than the election timeout makes a
follower clear its leader. The next heartbeat makes it a follower again
without marking the leader alive (NuRaft's same-term candidate branch calls
only become_follower(), and only update_target_priority() sets hb_alive_),
so for about one more heartbeat interval KeeperDispatcher refuses the command
with "Cannot reconfigure cluster because there is no active leader". Seen in
Integration tests (amd_tsan, 4/6) on PR ClickHouse#122464.

Both no-live-leader refusals (the entry check and the `leaders` precondition)
are raised before any action is applied, so add a helper that resends the
command on exactly these two messages, every 0.5 s for up to 30 s, and then
fails with the last refusal instead of returning it. All five rcfg calls use
it; the assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 18, 2026
…ate_random_json` on half and a third of their rows

No existing query number or text changes: 2 queries are disabled and 2 copies
appended as 5 and 6.

Query 1 (`JSON(max_dynamic_paths = 4)`, 3M rows) and query 2 (`Dynamic`, 300M
rows) take 1.30 / 1.99 s on MasterCI amd and 0.95 / 1.44 s on arm: generateRandom
work on 8 / 12 threads, a third of query 1's CPU being the shared reference
counter contention that ClickHouse#122464 removes.

The copies are the same queries with LIMIT 1500000 and LIMIT 100000000: the same
seeds, schema and block size (1003 / 27777 rows), so each stream generates fewer
identical blocks and the work per row is unchanged.

On the official master builds 2731aee and d076efd, per-row user time of the
copies is 0.975-1.000 of the originals' (clickhouse local) and 0.999-1.008 under
perf.py; query 1's copy keeps 0.951 / 0.987 of the original's per-row CPU growth
from 1 to 8 threads (the contention), query 2's copy stays at 1.00-1.02 (none).

Projected copy medians 0.65 / 0.67 s amd and 0.48 s arm: about 24 s (amd) and
17 s (arm) less query time per master perf job.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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-data-types Type system & core datatypes used across query planning/execution. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant