Repository navigation
ZSTD codec reuses its contexts - #122854
alexey-milovidov merged 20 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [2195b2f] Summary: ✅
AI ReviewSummaryThe PR reuses Findings
Tests
Final VerdictLLVM Coverage ReportMeasured on commit 2195b2f.
Changed lines: Changed C/C++ lines covered: 60/66 (90.91%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+20.98 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR reuses ZSTD compression and decompression contexts from per-CPU pools instead of creating a new one for every block. That can only affect queries that read or write ZSTD-compressed columns. clickbench Q20 shows a clear improvement (-42.7%, 220 ms to 126 ms) and its CPU time roughly halves; the result is locked by the large-delta rule. Still, a gain this big is more than skipping per-block context setup would normally explain, and Q12 and Q13 did not get faster at the same time, so a confirming rerun is worthwhile. The slowdowns on Q12 (+11.7%), Q13 (+13.1%) and Q31 (+14.8%) fall inside master's normal variance band and cannot be tied to this change, so treating them as not significant is correct. No tpch_adapted_1_official queries were flagged. clickbench🟢 1 improved · Flagged queries (4 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_official🟢 No significant changes Debug info
|
…m-lowlevel-pattern-audit-2026-09-11
Apply the same count cap as for compression contexts, so that a burst of concurrent reads does not leave its `ZSTD_DCtx` objects resident in the pools for the lifetime of the server. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master and addressed the AI review:
The failed |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I think |
|
🕵 The only red job on ddbd658 is |
I believe this is expected and acceptable. I already have in process PR which would make this task pass/accept it if labels |
|
Yes, it is acceptable. |
|
🕵 Merged CI failures on the previous head (8b09a5a):
@groeneai, investigate the failures of |
|
🕵 Merged Cause: I resolved the thread about the |
… new one Threads roam over CPUs, so with strictly per-CPU pools a thread that lands on a CPU whose pool is empty created and kept a new context even though idle contexts were pooled on other CPUs. This made `Storage memory check` report a resident 98 KB `ZSTD_DCtx` from `MergeTreeMarksLoader::loadMarksImpl` in `03_add_secondary_indexes.sql`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122854&sha=2367a3b2f3735d434b510715fdd94eb874829578&name_0=PR&name_1=Storage%20memory%20check #122854 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The only red job on 2367a3b was Built locally; |
…k it A context taken from another CPU's pool went back to that pool, so a thread that moved to another CPU searched all pools again on every block. Now a context returns to the pool of the CPU that took it, and the search is skipped when no pool has an idle context. This replaces `SimpleObjectPool` with a small pool whose deleter is set by the borrower. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Addressed the review on the peer search of the The only failure on 796b49f is unrelated: @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122854&sha=796b49ff7efd824bbf10b6161162abb40ee6c777&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
The fix is already in progress: #126210. The stuck worker at The ASan fake stack of a worker fills up with frames left behind by exceptions from failed overload resolution, after which every per-element CIDB: 22 occurrences since 2026-10-15 (3 on master), 0 in the 640 runs of 2026-10-14. |
The pool is process-wide, so it is not charged to the query that grows it. Fixes the `Style check` failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122854&sha=b43e4d6aa35448e1fc147ccc651202129b8833bf&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Fixed the Resolved the review thread about the peer search, which was addressed in b43e4d6. Thanks @groeneai for linking #126210 for the unrelated |
| { | ||
| std::lock_guard lock(pool->mutex); | ||
| pool->idle.emplace_back(context); | ||
| ++num_idle; |
There was a problem hiding this comment.
Every return increments the process-wide num_idle, and every borrow decrements it, including when each worker has a warm local context. These writes contend on one cache line; the adjacent, unpadded Pool objects also allow their mutexes and idle lists to share cache lines across CPUs.
A standalone benchmark of this exact helper with the bundled libzstd 1.5.8, two pinned workers, and 4 KiB high-entropy blocks measured a median 241.5 ns/block versus 123.0 ns/block for the previous ZSTD_decompress call (aggregate throughput, three rounds of one million blocks per worker). Aligning each pool reduced that to 168.5 ns/block; also removing the shared counter reduced it to 109.7 ns/block. Contexts were warmed before measurement, so this does not require repeated peer searches.
This benchmark omits ClickHouse's allocator hooks and memory tracking, so it needs verification in a full build. The new performance test forces max_threads = 1, and the earlier multithreaded measurements predate this helper. Please measure concurrent small-block reads on the current head against the base, and address the shared writes/pool layout if the regression persists.
There was a problem hiding this comment.
It didn't show up in the perf test.
There was a problem hiding this comment.
🕵 Correction: I prepared a fix (9fd6c64) but could not push it here because the PR is already in the merge queue (GitHub rejects updates to queued branches). It is on the branch continue-pr-122854-zstd-pool-no-shared-writes (https://github.com/ClickHouse/ClickHouse/tree/continue-pr-122854-zstd-pool-no-shared-writes): each per-CPU pool is aligned to CH_CACHE_LINE_SIZE and keeps its own idle count (written only under its own mutex) instead of the process-wide num_idle, so borrowing/returning a warm context on the local CPU touches only that pool's cache lines. It can be sent as a follow-up after this PR merges, or picked up here if the PR is dequeued.
|
I'd like to suggest to revert 17f42e3, b43e4d6, e15c0fd and also 66427df . I'm not reverting them myself because I don't think I'm here the experienced person with a lot of knowledge, but I'd like to try to make this a human decision. For each of those short reasoning:
@alexey-milovidov please keep them if you prefer that. No need to answer, I'll consider that as "we will merge this one, and you can open a new PR and it will be decided there". (I'm currently doing these measurements on desktop CPU, but for illustration I hope will be enough. I wIll update them on Monday.) |
I double-checked, but couldn't find what is wrong. |
|
We can merge it first and revert in a follow-up PR. |
A context created for every page costs an allocation and a free of ~94 KiB per page, above jemalloc's thread cache, which is a large part of decoding a small page. The pages decoded by one `decodePrimitiveColumn` call now share one context, created on the first ZSTD page and freed when the call returns: a thread holds at most one context, and only while it decodes a column. The codec's per-CPU pools (ClickHouse#122854) were slower on this path under concurrency, and a context kept per thread would stay resident on every thread. Patch by @ snelheidai in ClickHouse#132935. Release builds, `clickhouse local`, pinned cores, 8-16 paired rounds, this commit vs its parent, wall time, 95% CI, on ClickBench hits_0..3 (4M rows) written by master as ZSTD: - 1024-row pages: sum(cityHash64(*)) -8.6% [-12.8, -4.2] at 4 threads, -4.0% [-5.8, -2.3] at 16, within noise at 64 (CPU -5.7% [-9.0, -2.3]); sum of 10 numeric columns -9.8% [-11.0, -8.6] on one thread. - default pages (up to 20000 rows): sum of 10 numeric columns -2.6% [-4.9, -0.3] on one thread; all other queries at 1, 4, 16 and 64 threads within noise. - Snappy files (unchanged path) and the performance test: within noise. Peak memory unchanged. All 2928 Parquet files in the repository give the same result and the same errors with both builds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The native Parquet reader decoded every ZSTD page through `ZstdInflatingReadBuffer`: a new `ZSTD_DCtx` per page and the streaming API. For frames without a content size (parquet-java, i.e. Spark, Hive and Iceberg Java, and ClickHouse 26.10 and older with the default codec), streaming also allocates input and window buffers per page and copies the output through the window. The page is fully in memory and its uncompressed size is known from the page header, so decode it one-shot with `ZSTD_decompressDCtx` straight into the page buffer, with a context from the per-CPU pools that the ZSTD codec already keeps for MergeTree reads (ClickHouse#122854). The pooled call is factored out of `CompressionCodecZSTD::doDecompressData` into `decompressZSTDWithPooledContext`, so both users share one pool and one cap. Decoding is strict, as for the LZ4_RAW, SNAPPY and GZIP (libdeflate) pages of the same switch and as in Arrow C++: a zstd error or a result size that differs from the page header throws `INCORRECT_DATA`. Streaming tolerated bytes after the last frame and silently truncated a page that decodes to more bytes than declared; frames without a content size declaring a window above 128 MiB, which streaming refused, now decode (one-shot allocates no window). Analysis and patch: ClickHouse#132935 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Follow-up on the stress-test hung check above: #125117 (the |
The
ZSTDcodec takes compression and decompression contexts from a per-CPU pool instead of creating them for every block.OPTIMIZEof 160 MB withZSTD(3): −8%; high-entropySELECT: −10%.Each call resets its context with
ZSTD_reset_session_and_parameters; above2 * getNumberOfCPUCoresToUsecontexts or 2 MiB a context is freed, not pooled. 16 threads: unchanged (global pool: +33%).Performance test: new
zstd_codec_context_reuse.xml.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Faster compression and decompression with the
ZSTDcodec, most noticeably for incompressible data.Workflow [PR]
Sync PR [sync-upstream/pr/122854]
Version info
26.11.1.206-master(included in26.11and later)