Repository navigation
Add PCO compression codec (linking the pcodec Rust crate) - #110613
Conversation
Adds a new experimental compression codec `PCO` that links the pcodec (`pco`) Rust crate — the reference implementation — rather than reimplementing it in C++. pcodec is a lossless codec specialized for sequences of fixed-width numbers and often beats `Gorilla`/`FPC`/`ZSTD`/`ALP` on numeric columns. This is the Rust-library counterpart to the native C++ port explored in #106222. Runtime CPU dispatch: `pco` has no explicit SIMD and relies on the compiler autovectorizing its per-batch loops, which only happens when the crate is built with the relevant instruction sets enabled. That does not work for ClickHouse, which compiles all Rust once at a fixed baseline for a portable binary. So `pco` is taken from a ClickHouse fork patched to add runtime CPU-feature dispatch of its hot loops (the same mechanism as C++ `TargetSpecific.h`): the vectorizable loops are compiled at the baseline and again for `x86-64-v3` (AVX2 + BMI1/2) and `x86-64-v4` (AVX-512), and the widest variant the CPU supports is selected at runtime. On aarch64 the baseline already includes NEON. The patch is merged into the fork via its own PR (https://github.com/alexey-milovidov/pcodec/pull/1) and the crate is added as the `contrib/pcodec` submodule, linked through a thin FFI wrapper crate (`rust/workspace/pco`). Its one not-yet-vendored dependency, `rand_xoshiro`, was added to `contrib/rust_vendor` in ClickHouse/rust_vendor#72. The codec supports all fixed-width numeric types of 1/2/4/8 bytes via their underlying representation (`Int8`..`Int64`, `UInt8`..`UInt64`, `Float32`, `Float64`, and the types backed by them). The on-disk block stores a 2-byte header (element width + partial-tail byte count), the raw partial-value tail, and a payload that is a standalone `.pco` stream, wire-compatible with the reference pcodec; when compression would not shrink a block the raw bytes are stored instead (a per-block flag), so the output never expands by more than the header and `getMaxCompressedDataSize` is tight. The codec is gated behind `allow_experimental_codecs`. Because it needs the column type, it can only be specified per column: `requiresColumnTypeToCompress` rejects it in `TTL ... RECOMPRESS` and the untyped compression settings that resolve codecs without a type, `CompressionCodecMultiple` propagates the experimental / column-type-requiring properties so a chain such as `CODEC(Delta, PCO)` is still gated, and a codec-only `ALTER MODIFY COLUMN` validates against the existing column type. Tests: `04512_pco_codec` round-trips every supported numeric and backed type; `04513_pco_codec_gating` covers the experimental gate, the `TTL RECOMPRESS` rejection, and the codec-only `ALTER`; the FFI wrapper has Rust unit tests. `docs/en/interfaces/specs/NativeFormat.md` documents the `0x9d` method byte. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
Close the `allow_experimental_codecs` bypass and the late-failure of the untyped MergeTree compression settings. `default_compression_codec`, `marks_compression_codec` and `primary_key_compression_codec` are resolved without a column type, so they never went through the column-codec experimental gate: `default_compression_codec = 'PCO'` silently worked (re-resolved with the real type at write time), and the marks/primary-key settings only failed at the first write. `MergeTreeSettingsImpl::checkCompressionCodecSettings` (called from `sanityCheck`, i.e. CREATE and ALTER MODIFY SETTING) now rejects an experimental codec in all three settings and a codec that `requiresColumnTypeToCompress` in the two applied to untyped streams. `CompressionCodecMultiple` already propagates both properties, so a chain such as `PCO, ZSTD(1)` is rejected too. Extends `04513_pco_codec_gating`. Also drops a redundant cast in `CompressionCodecPco.cpp` and an unused include in `pco.h`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Point contrib/pcodec at https://github.com/ClickHouse/pcodec (the fork of pcodec/pcodec in the ClickHouse organization) instead of a personal fork. The runtime CPU-dispatch patch is merged there via ClickHouse/pcodec#1; the pinned commit is identical in content, so nothing else changes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolve conflicts with master's new SZ3 codec: - CompressionInfo.h: SZ3 took method byte 0x9d, so PCO moves to 0x9e. - registerCompressionCodecs.h / CompressionFactory.cpp: keep both registrations. - CompressionFactoryAdditions.cpp: keep master's lossy-codec (SZ3) checks and the PCO requiresColumnTypeToCompress rejection side by side. - MergeTreeSettings.cpp: keep checkCompressionCodecSettings (it calls the factory, which already rejects lossy SZ3 built untyped, and additionally rejects experimental / column-type-requiring codecs); drop the now-redundant duplicate include and inline check master added. - 01222_system_codecs.reference: both SZ3 (157) and PCO (158) rows, count 16. - NativeFormat.md: PCO documented at 0x9e alongside SZ3 at 0x9d. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [ed5287d] Summary: ✅
AI ReviewSummaryAdds the beta Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block. Correct the dependency's scratch-buffer initialization, update |
Rust
|
| column | ratio C++ | ratio Rust | enc C++ MB/s | enc Rust | dec C++ MB/s | dec Rust |
|---|---|---|---|---|---|---|
| WatchID (random Int64) | 1.03 | 1.03 | 88 | 102 | 2051 | 1860 |
| UserID | 5.47 | 5.46 | 231 | 227 | 1584 | 1739 |
| EventTime | 6.18 | 6.18 | 102 | 126 | 1798 | 1633 |
| RefererHash (hash) | 1.62 | 2.49 | 132 | 110 | 1553 | 947 |
| URLHash (hash) | 1.34 | 2.04 | 119 | 97 | 1553 | 925 |
| CounterID (sorted key) | 778 | 774 | 430 | 385 | 2424 | 1702 |
| RegionID | 9.65 | 9.65 | 179 | 161 | 1000 | 964 |
| ClientIP | 3.94 | 3.94 | 181 | 159 | 909 | 1013 |
| ResolutionWidth | 6.08 | 6.09 | 105 | 102 | 488 | 506 |
| Age | 10.58 | 10.58 | 125 | 119 | 571 | 597 |
Full-hits, 17-column, multi-threaded INSERT (encode): C++ 23.3s → Rust 18.8s.
Compression — equal or better, never meaningfully worse. 13 of 17 numeric columns are identical (±1%). On the two 64-bit hash columns the Rust encoder is ~1.5× better (RefererHash 2.49× vs 1.62×, URLHash 2.04× vs 1.34×): the upstream encoder runs the full mode search and finds the common-multiplier/GCD structure that the C++ port's cheaper sampling missed. That is exactly where #106222's own evaluation had PCO losing to GCD+ZSTD (2.54 / 2.04) — the real crate closes the gap.
Speed — on par. Encode is within ~15% per column and faster overall on the full multi-threaded load (18.8s vs 23.3s). Decode is within ~15% on most columns (Rust is faster on several: ClientIP, ResolutionWidth, Age, UserID). Rust decodes the two hash columns slower (≈940 vs 1550 MB/s) because it chose the denser IntMult-mode stream — a ratio/speed trade, not raw slowness.
Caveats.
- All on aarch64, so both codecs use their scalar/NEON baseline; the Rust crate's new runtime CPU dispatch (and the C++ port's
TargetSpecific) only add AVX2/AVX-512 on x86-64, which this host cannot exercise. x86 numbers would differ. - Methodology note for anyone reproducing: ClickHouse compiles vendored Rust at
opt-level=0unlessSANITIZEis the empty string, so aDebug/RelWithDebInfobuild ships an unoptimized codec that decodes ~12× slower. A fair benchmark needs the Rust[profile.release]atopt-level=3.
Net: on hits, the Rust library matches the C++ port on speed and beats it on the hardest (hash) columns — supporting linking the real crate over maintaining a reimplementation.
When `USE_PCO` is disabled (e.g. Rust disabled, as in the Fast test build), the `#else` branch of `CompressionCodecPco.cpp` defines a no-op `registerCodecPco` stub without including `registerCompressionCodecs.h`, so the compiler never sees the prototype declared there. Under `-Weverything -Werror` this trips `-Wmissing-prototypes` and fails the build.
# Conflicts: # docs/en/interfaces/specs/NativeFormat.md # src/Compression/CompressionInfo.h # tests/queries/0_stateless/01222_system_codecs.reference
The `markdownlint` `MD040` rule requires every fenced code block to declare a language. The PCO per-column codec frame diagram added to `docs/en/interfaces/specs/NativeFormat.md` opened a bare ``` fence, which failed the `Docs check` job's markdown linter. Mark it as `text`, consistent with the other ASCII diagrams in the spec. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review feedback: `temporary_files_codec` was another untyped compression surface that bypassed the `PCO` validation. `getCodec` in `TemporaryDataOnDisk` builds the codec from the bare setting string via `CompressionCodecFactory::get`, so `SET temporary_files_codec = 'PCO'` (or a chain containing it) was accepted and the first external sort/join/aggregation spill later threw the confusing `Codec 'PCO' was created without a numeric column type and cannot compress`. Validate the resolved codec in `getCodec`, mirroring the `marks_compression_codec` / `primary_key_compression_codec` checks in `MergeTreeSettingsImpl::checkCompressionCodecSettings`: reject an experimental codec, and a codec that requires the column type to compress, with a clear `BAD_ARGUMENTS` message naming the setting. Temporary files hold raw, untyped serialized data, so such codecs can never work there. Extend `03772_temporary_files_codec.sql` with spill regressions for `temporary_files_codec = 'PCO'` and the chain `'PCO, LZ4'`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The untyped `PCO` decode path (`CompressedReadBuffer` / HTTP `decompress=1`) peeks the number type embedded in the standalone `.pco` stream and dispatches on it, but the `match` in `pco_decompress` never handled `NUMBER_TYPE_BYTE = 9` (`half::f16`). The FFI header advertises `PCO_F16 = 9` and the vendored `pco` crate implements `half::f16`, so a valid standalone `.pco` stream carrying `f16` values (width 2) fell through to `PCO_ERROR`. That broke the standalone-pcodec compatibility contract this PR documents for the `0x9f` frame: `NativeFormat.md` states the embedded number type is sufficient to decode. Add the `f16` decode arm (and, for symmetry with the `PcoNumberType` enum, the encode arm), depending on `half` in the same major as `pco`'s own so they resolve to a single crate. Tests: `roundtrip_all_types` now covers `f16` through the FFI, and a new `decompress_external_f16_stream` feeds a valid `f16` stream built with the reference `simple_compress` API through `pco_decompress`, asserting byte-exact recovery and fail-closed behavior on a width mismatch.
Remove everything that is not the codec: the `spill_codec_authorized` plumbing for temporary-file codecs and its query-plan serialization, the changes in `AggregatingStep`, `SortingStep`, `DistinctStep` and the join code, the `ATTACH`/TTL/projection metadata sanitization, the untyped-codec classification helpers in `CompressionCodecFactory`, and all tests of those. The files are restored to their `master` versions. The codec is now declared as Beta (`enable_pco_codec` is `BETA`). It is registered only when the build has the pcodec library, like `SZ3`, so the throwing stub and the `SUPPORT_IS_DISABLED` special cases are gone. The only remaining factory change rejects `PCO` where the codec is resolved without a column type (the marks, primary key, default and TTL recompress codecs). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Simplified as requested in |
A server built without the library (without Rust, or with `ENABLE_PCO=OFF`) does not register the codec, so `CompressionCodecFactory::get` rejects the method byte with `UNKNOWN_CODEC`. The spec no longer claims unconditionally that the method byte is always accepted on decompression. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged current The remaining reds on the previous head: two |
|
🕵 Merged current |
|
🕵 Merged current |
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110613&sha=6722f4ca7b91a9b79714398d0f24d247f528adbb&name_0=PR — all five Also: the |
|
Not caused by this PR, and I don't think a code fix is warranted:
The run on the new head ( |
| @@ -0,0 +1 @@ | |||
| Subproject commit 35424f0fc3aa61328940774c1b915e1356092a5a | |||
There was a problem hiding this comment.
❌ The pinned dependency introduces undefined behavior into ordinary PCO compression.
In this revision, pco/src/chunk_latent_compressor.rs:23–31 implements uninit_vec by allocating capacity and immediately calling set_len, without initializing any elements. uninit_page_dissected_var uses it for four scratch vectors, and nontrivial pages reach this through simple_compress_into → write_page → dissect_page; dissect_batch then forms typed mutable slices over those uninitialized elements.
Vec::set_len requires the added elements to be initialized. Integer types having no destructor does not remove that requirement, despite the dependency's safety comment. This invalidates the memory-safety and lossless-compression guarantees on valid input; the FFI's catch_unwind cannot contain undefined behavior.
Please fix the fork and update this pin: initialize these scratch vectors, or keep their storage as MaybeUninit<T> and write through an appropriate interface until every exposed element is initialized. The wrapper's output-buffer initialization fix does not cover these internal vectors.
|
🕵 Merged current @groeneai, thanks for the CIDB outage analysis; agreed that no fix is needed for those perf shards. |
|
Let's follow standard lifecycle of codecs and start with experimental, wdyt? @groeneai could you open a PR that takes this from beta to experimental and backport to 26.10? |
|
Acknowledged. I will open a PR that moves |
|
I opened #126749. Once it merges on master I will ask for |
Adds a
PCOcompression codec (Beta) that links the pcodec (pco) Rust crate — the reference implementation — rather than reimplementing it.pcois a lossless codec specialized for sequences of fixed-width numbers; on numeric columns with smooth, multimodal, or high-entropy distributions (measurements, timings, counters, identifiers) it often beatsGorilla/FPC/ZSTD/ALPon ratio.This is the Rust-library counterpart to the native C++ port explored in #106222. Instead of maintaining a C++ reimplementation, it links the upstream crate.
Runtime CPU dispatch
pcohas no explicit SIMD: it relies on the compiler autovectorizing its per-batch loops, which only happens when the crate is compiled with the relevant instruction sets enabled (itsbuild.rswarns to build with-C target-feature=+avx2,+bmi1,+bmi2). That does not work for ClickHouse, which compiles all Rust once at a fixed baseline micro-architecture level for a binary that must run on a range of CPUs.So
pcois taken from a ClickHouse fork patched to add runtime CPU-feature dispatch of its hot loops — the same mechanism ClickHouse's C++ uses viaTargetSpecific.h. The vectorizable loop bodies (decoderead_offsets; encodewrite_short_uints/write_uints/set_offsets) are compiled at the crate baseline and again forx86-64-v3(AVX2 + BMI1/2 + FMA) andx86-64-v4(AVX-512), and the widest variant the running CPU supports is selected once and cached. On aarch64 the baseline already includes NEON, so the baseline body is used directly. Verified at baseline-C target-cpu=x86-64: theread_offsetsv3 trampoline emits AVX2 (ymm) and v4 emits AVX-512 (zmm).The patch is merged into
ClickHouse/pcodec(a fork of pcodec/pcodec in the ClickHouse organization) via its own PR: ClickHouse/pcodec#1. The crate is added as thecontrib/pcodecsubmodule and linked through a thin FFI wrapper crate (rust/workspace/pco). Its one not-yet-vendored dependency,rand_xoshiro, was added tocontrib/rust_vendorin ClickHouse/rust_vendor#72.Codec
Supported types are all fixed-width numerics of 1/2/4/8 bytes via their underlying integer/float representation:
Int8..Int64,UInt8..UInt64,Float32/Float64, and the types backed by them (Date,DateTime,Decimal32/Decimal64,IPv4,Enum, ...). The on-disk block stores a 2-byte header (element width + partial-tail byte count) followed by a raw partial-value tail (as inGorilla/FPC) and the payload. The payload is a standalone.pcostream, wire-compatible with the reference pcodec implementation; when compression would not shrink a block the raw bytes are stored instead (a per-block "stored" flag), so the output never expands by more than the 2-byte header andgetMaxCompressedDataSizeis tight.PCO(level)takes an optional compression level from 0 to 12, defaulting to 8.Gating
The codec is in Beta and is enabled by the
enable_pco_codecsetting. It is registered only in builds that include the pcodec library (likeSZ3). BecausePCOneeds the column type to compress, it can only be specified per column: it is rejected where the codec is resolved without a type (TTL ... RECOMPRESS,default_compression_codec,marks_compression_codec,primary_key_compression_codec).Documentation
The codec is documented in the source of truth for the codec reference page,
src/Parsers/ParserCreateQuery.cpp, and the compression-frame method byte0xa0is documented in theNativeformat specification,docs/resources/develop-contribute/native-protocol/format.mdx.Tests
04512_pco_codecround-trips every supported numeric and backed type (per-element verification, edge cases, codec chaining, compression-ratio check) and04513_pco_codec_gatingcovers the gate, the rejection in untyped contexts, and the codec-onlyALTER. The FFI wrapper has its own Rust unit tests (round-trip of all types, the no-expansion fallback, and fail-closed handling of malformed/mismatched streams).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new compression codec
PCO(Beta), which links the pcodec library (patched for runtime CPU dispatch), specialized for fixed-width numeric columns. It is wire-format compatible with pcodec.pcostreams and is enabled withenable_pco_codec.Documentation entry for user-facing changes:
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/110613]
Version info
26.10.1.2427-master(included in26.10and later)