Skip to content

ZSTD codec reuses its contexts - #122854

Merged
alexey-milovidov merged 20 commits into
masterfrom
small-perf-wins-from-lowlevel-pattern-audit-2026-09-11
Oct 19, 2026
Merged

alexey-milovidov merged 20 commits into
masterfrom
small-perf-wins-from-lowlevel-pattern-audit-2026-09-11

Conversation

@NIKTONIKTO717

@NIKTONIKTO717 NIKTONIKTO717 commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

The ZSTD codec takes compression and decompression contexts from a per-CPU pool instead of creating them for every block. OPTIMIZE of 160 MB with ZSTD(3): −8%; high-entropy SELECT: −10%.

Each call resets its context with ZSTD_reset_session_and_parameters; above 2 * getNumberOfCPUCoresToUse contexts 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):

  • Performance Improvement

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

Faster compression and decompression with the ZSTD codec, most noticeably for incompressible data.


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

Version info

  • Merged into: 26.11.1.206-master (included in 26.11 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2195b2f]

Summary: ✅


AI Review

Summary

The PR reuses ZSTD contexts through bounded per-CPU pools and accounts for borrowed compression contexts against the query. One new concurrency performance concern needs verification before approval.

Findings

⚠️ Majors

  • src/Compression/CompressionCodecZSTD.cpp:75: Every warm borrow/return modifies the shared num_idle, while adjacent Pool objects can also share cache lines. A standalone benchmark using the exact helper and bundled libzstd 1.5.8 measured 241.5 ns/block versus 123.0 ns/block for the previous ZSTD_decompress call with two pinned workers and 4 KiB high-entropy blocks. These are aggregate throughput measurements, with medians from three rounds of one million blocks per worker. Aligning the pools reduced the result to 168.5 ns/block; also removing the shared counter reduced it to 109.7 ns/block. This indicates contention even with warm local contexts. The benchmark excludes ClickHouse's allocator hooks and memory tracking, so an end-to-end regression remains unconfirmed. Validate the current implementation in a full build and remove the regression if confirmed.
Tests
  • ⚠️ Add a focused before/after measurement of concurrent ZSTD reads using small blocks and 64 KiB blocks, with ClickHouse's normal allocator and memory tracking. The added performance test uses one thread, and the earlier multithreaded measurements predate the current pool helper.
Final Verdict

⚠️ Request changes — verify concurrent performance on the current head and address any confirmed regression from shared counter updates or pool layout.

LLVM Coverage Report

Measured on commit 2195b2f.

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

Changed lines: Changed C/C++ lines covered: 60/66 (90.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2195b2ffc with master 54c2b7d7b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 76cb67e41; 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.

Object file sizes

4 object files changed (+20.98 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_compression.dir/Compression/CompressionCodecZSTD.cpp.o 99.00 KiB 119.98 KiB +20.98 KiB (+21.19%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

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 · ⚠️ 3 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 126 -42.7% <0.0001 cpu: -42.7% with CPU time down about 47%, so less work was done. Reusing ZSTD decompression contexts explains this only if the scanned column is ZSTD-compressed, and the size looks large for that alone. Worth rerunning to confirm.
⚠️ 12 not_sure 253 282 +11.7% <0.0001 aggregation: +11.7% falls inside master's current variance band (234-293 ms). CPU rose about 10%, but nothing ties this to ZSTD context pooling, so the suppression stands.
⚠️ 13 not_sure 352 398 +13.1% <0.0001 aggregation: +13.1% falls inside master's current variance band (335-407 ms). This is a string GROUP BY, and the diff gives no concrete reason it would get slower, so the suppression stands.
⚠️ 31 not_sure 257 295 +14.8% <0.0001 +14.8% falls inside master's current variance band (229-348.5 ms), and CPU time is flat. This looks like wall-clock variance, not a change in work done.

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: f09948b3-812b-49d7-b2ba-bf417771a9db
  • MIRAI run: 1d637e76-30b6-40e6-b22e-fbf75a2e2a01
  • PR check IDs:
    • clickbench_73531_1791935942
    • clickbench_73537_1791935941
    • clickbench_73563_1791935941
    • tpch_adapted_1_official_73599_1791935942
    • tpch_adapted_1_official_73621_1791935941
    • tpch_adapted_1_official_73644_1791935942

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All good.

alexey-milovidov and others added 2 commits October 12, 2026 19:25
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and addressed the AI review:

  • Major (unbounded decompression pool): fixed in 66427df, ZSTD_DCtx returns now use the same 2 * getNumberOfCPUCoresToUse count cap as compression contexts.
  • Blocker (LockMemoryExceptionInThread around the codec call): no change. libzstd allocates through malloc, and the malloc interceptor (src/Common/malloc.cpp, Memory::trackMemoryFromC) never throws, so the lock does not disable any MEMORY_LIMIT_EXCEEDED check inside ZSTD_compress2 / ZSTD_decompressDCtx. It only affects the C++ allocations in this scope: the pool stack push in the deleter, which must not throw.

The failed Storage memory check (PR binary not found .../clickhouse-examples) and the Integration tests (amd_llvm_coverage, 1/8) error were infrastructure failures, not caused by this PR. CI reruns on the new commit.

@NIKTONIKTO717

Copy link
Copy Markdown
Member Author

I think Storage memory check might fail here in CI, but is (at least from my perspective) expected, and the difference should be caused strictly by extra memory because of keeping pool of contexts. But as far as I understand, Storage memory check compares each PR only with the master it is based on, so after merging, master simply becomes the new baseline and future PRs won't fail because of this.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red job on ddbd658 is Storage memory check (02_insert_data.sql +67,600 B, 03_add_secondary_indexes.sql +102,416 B). It is caused by this PR on purpose: the report puts the whole delta on the contexts kept in the pool: ZSTD_compressBegin_internal workspace (+57,344 B), CompressionCodecZSTD::doCompressData (+6,152 B), and the SimpleObjectPool deleter (+4,104 B). Master has 0 B on these stacks. The profiler's warm-up pass does not hide it because the pools are per CPU, so the measured pass can land on other CPUs and create new contexts there. The retained memory has a limit (at most 2 * getNumberOfCPUCoresToUse contexts, and none above 2 MiB), so a human needs to decide whether to accept this check failure. No code change was made.

@NIKTONIKTO717

Copy link
Copy Markdown
Member Author

🕵 The only red job on ddbd658 is Storage memory check (02_insert_data.sql +67,600 B, 03_add_secondary_indexes.sql +102,416 B). It is caused by this PR on purpose: the report puts the whole delta on the contexts kept in the pool: ZSTD_compressBegin_internal workspace (+57,344 B), CompressionCodecZSTD::doCompressData (+6,152 B), and the SimpleObjectPool deleter (+4,104 B). Master has 0 B on these stacks. The profiler's warm-up pass does not hide it because the pools are per CPU, so the measured pass can land on other CPUs and create new contexts there. The retained memory has a limit (at most 2 * getNumberOfCPUCoresToUse contexts, and none above 2 MiB), so a human needs to decide whether to accept this check failure. No code change was made.

I believe this is expected and acceptable. I already have in process PR which would make this task pass/accept it if labels memory and pr-performance are specified in PR. (#125623)

@NIKTONIKTO717 NIKTONIKTO717 added the ci-force-all Do not skip any jobs when running label Oct 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Yes, it is acceptable.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (the branch was behind); the build and 05243_zstd_codec_pooled_context_parameters pass locally.

CI failures on the previous head (8b09a5a):

  • Storage memory check (02_insert_data.sql +100 KB, 05_multiple_tables.sql +68 KB): expected with this change — pooled ZSTD contexts intentionally stay resident after the query (a decompression context is about 100 KB), and the pools are per CPU, so a scenario run on a different CPU creates a new context. This is the trade-off of the PR and needs a human decision, not a code fix.
  • Stress test (arm_release) hung check: the hung query is an exponentially nested plus expression over a view, CPU-bound in expression evaluation, no ZSTD frames in the stack traces. Related: Uninterruptible CPU-bound function evaluation over a large value #112203
  • 04907_url_function_no_retry_after_cancel (LLVM coverage builds): retry backoff timing on cancellation, unrelated to compression. Related: url function is unstoppable (and it is not good:) #66656
  • LLVM Coverage diff report: infrastructure (Could not find baseline coverage file after checking 100 commits).

@groeneai, investigate the failures of 04907_url_function_no_retry_after_cancel (https://s3.amazonaws.com/clickhouse-test-reports/PRs/122854/8b09a5a9df1fd45ffb02dabdc66e0d0c2a01893f/pr/result_pr.json) and the stress-test hung check (https://s3.amazonaws.com/clickhouse-test-reports/PRs/122854/8b09a5a9df1fd45ffb02dabdc66e0d0c2a01893f/pr/stress_test_arm_release/hung_check.log) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and fixed the Fast test failure of 05346_distributed_insert_connection_buffers_freed_by_same_query (2367a3b), which failed on every Fast test run of this PR.

Cause: network_compression_method is ZSTD by default, so the Distributed INSERT in the test compresses with pooled contexts. When an INSERT takes a pooled context whose workspace is too small, ZSTD_resetCCtx_internal frees the workspace allocated by another INSERT, and the test counts that as a cross-query free. Reproduced locally with the server limited to two CPUs (8 1, stack ZSTD_compress2 <- CompressionCodecZSTD::doCompressData <- Connection::sendData). This sharing is intentional (the query is charged for a pooled context only while it uses it), and the test checks the connection buffers, which do not depend on the codec. So the test now sends data with network_compression_method = 'LZ4', and gives 8 0 in repeated runs.

I resolved the thread about the 2 * getNumberOfCPUCoresToUse cap: it was answered above, and the PR is approved.

alexey-milovidov and others added 2 commits October 17, 2026 13:12
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and reduced the Storage memory check regression (17f42e3).

The only red job on 2367a3b was Storage memory check (03_add_secondary_indexes.sql +102,416 B, report). The heap diff showed a new 98 KB ZSTD_DCtx from MergeTreeMarksLoader::loadMarksImpl that stayed in a pool during the measured (second) pass. The pools were strictly per-CPU, so a thread that landed on a CPU with an empty pool created and kept a new context, even though an idle context from the warm-up pass sat in another CPU's pool. Now, when the current CPU's pool is empty, an idle context is taken from another CPU's pool before a new one is created. The number of resident contexts now follows the peak concurrency rather than the number of CPUs threads happen to run on.

Built locally; 05212_compression_codec_zstd_long_range_mode passes, and so does a concurrent insert and select on ZSTD columns.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the review on the peer search of the ZSTD context pools (b43e4d6): a stolen context now stays in the borrowing CPU's pool, and the search is skipped when no context is idle. 05212_compression_codec_zstd_long_range_mode, 01622_codec_zstd_long and 03353_codec_zstd_doubledelta_data_corruption pass locally, and so does a concurrent read and write of a ZSTD column.

The only failure on 796b49f is unrelated: FunctionsStress.stress in Unit tests (asan_ubsan, function_prop_fuzzer), where a worker was stuck for 122 s on SELECT range(CAST(26638232 AS UInt32)).

@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.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #126210. The stuck worker at 796b49ff (122 s on range(CAST(26638232 AS UInt32))) has the same stack as the other occurrences: __asan_stack_malloc_1 <- PODArray::operator[] <- ColumnArray::compareAtImpl <- FunctionsStressTestThread::executeFunction.

The ASan fake stack of a worker fills up with frames left behind by exceptions from failed overload resolution, after which every per-element compareAt scans the full class-1 fake stack (details: #120908 (comment)). #126210 adds a fake-stack GC point at the top of the worker loop (test harness only). CI on it has finished; it is waiting for a review.

CIDB: 22 occurrences since 2026-10-15 (3 on master), 0 in the 640 runs of 2026-10-14.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Fixed the Style check failure on b43e4d6 (std::vector in CompressionCodecZSTD.cpp without a -WithMemoryTracking alternative): the idle list of the process-wide ZSTD context pool is now marked STYLE_CHECK_ALLOW_STD_CONTAINERS, because it should not be charged to whichever query grows it (e15c0fd). Also merged master. All other checks on b43e4d6 were green so far.

Resolved the review thread about the peer search, which was addressed in b43e4d6. Thanks @groeneai for linking #126210 for the unrelated FunctionsStress.stress failure.

{
std::lock_guard lock(pool->mutex);
pool->idle.emplace_back(context);
++num_idle;

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.

⚠️ Major: Verify concurrent small-block performance of the new pool

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It didn't show up in the perf test.

@alexey-milovidov alexey-milovidov Oct 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
@NIKTONIKTO717

NIKTONIKTO717 commented Oct 18, 2026 •

Copy link
Copy Markdown
Member Author

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:

  • 66427df (cap on the decompression pool): A decompression context is only 94 KiB, fixed. thread holds it only while it decompresses one block. As far as I understand, now it's capped per CPU quota, so I'd prefer to change it to getNumberOfLogicalCPUCores instead as a reasonable compromise.

  • 17f42e3, b43e4d6, e15c0fd (stealing/sharing between CPUs): During the process of creating this changes, I tested multiple version and I deliberately chosen version where each CPU has own pool of context. I based this decision on some testing, where I found sharing them between cpus end up spending more time with context memory moving between cores then saving by not allocating it. Anyway, I believe this should be decided based on experiment, because current version introduces regression on INSERT (into ZSTD(3) Uint64 col) going from 9.46s to 10.71s after 17f42e3 change. Same with SELECT on the same column goes down from 5.19 to 4.17 after initial changes but after those 3 commits it looses half of the improvement and is 4.76s. I believe that overhead of having counter and sharing them is bigger than a benefit. 17f42e3 is as far as I understand is "fix" for Storage memory check, which was considered before as "acceptable" since there is always in memory pool with contexts.

@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.)

@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Oct 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@NIKTONIKTO717

(comming soon)

I double-checked, but couldn't find what is wrong.

@alexey-milovidov

Copy link
Copy Markdown
Member

We can merge it first and revert in a follow-up PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 19, 2026
Merged via the queue into master with commit ed21581 Oct 19, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the small-perf-wins-from-lowlevel-pattern-audit-2026-09-11 branch October 19, 2026 14:28
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
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]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 21, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the stress-test hung check above: #125117 (the evaluatePartialResult walk) is merged. For the out-of-memory in filter push-down that came after it (#123724), three alternative fixes were requested on that issue: #134010 (option A) and #134034 (option B) are open, and the third will be linked there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-force-all Do not skip any jobs when running comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... 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