Repository navigation
Add pcodec (PCO) compression codec - #106222
alexey-milovidov wants to merge 43 commits into
Conversation
pcodec (`pco`) is a lossless codec specialized for fixed-width numeric sequences. This adds a native C++ reimplementation as a new ClickHouse compression codec `PCO`, registered under method byte `0x9d`. The implementation is bit-for-bit wire-format compatible with the reference pcodec v1.0.2 (format major 4 / minor 1, standalone version 3): ClickHouse can decode `.pco` streams produced elsewhere, and streams produced by this codec are read back byte-identically by the reference Rust decoder. This compatibility was used as a cross-validation oracle in both directions during development. The codec supports all fixed-width numeric ClickHouse types via their underlying integer/float width (1/2/4/8 bytes): `Int8`..`Int64`, `UInt8`..`UInt64`, `Float32`/`Float64`, and the types backed by them (`Date`, `DateTime`, `Decimal32/64`, `IPv4`, `Enum`, etc.). It implements the full decode path (Classic / IntMult / FloatMult / FloatQuant / Dict modes; None / Consecutive / Lookback delta encodings; interleaved 4-way tANS) and an auto-selecting encode path (Classic / IntMult / FloatQuant modes and consecutive delta, chosen by cheap sampling so the ratio never regresses below the Classic guarantee). The codec is gated behind `allow_experimental_codecs` for now. The library lives in a self-contained `src/Compression/Pcodec/` sub-directory; the codec entry point is `CompressionCodecPco`. The on-disk block stores a 2-byte header (element width + partial-tail byte count) followed by a raw partial-value tail (as in `Gorilla`/`FPC`) and a complete standalone `.pco` payload, which the encoder writes directly into ClickHouse's destination buffer. A stateless test (`04303_pco_codec`) round-trips every supported numeric type (including per-element verification, edge cases, and codec chaining such as `CODEC(Delta, PCO)`), and the documentation section for `PCO` is added under `docs/en/sql-reference/statements/create/table.md`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts: # src/Compression/CompressionFactory.cpp
|
Workflow [PR], commit [ce326c5] Summary: ❌
AI ReviewSummaryThis PR adds the experimental Final Verdict✅ No blocking or major findings on the current head. |
The `src/Compression` style lint forbids raw `std::vector` in favor of a memory-tracked alternative. Route the codec's internal buffers through a `PcoArray<T>` facade over `DB::PODArray` (so allocations use ClickHouse's memory-tracking allocator). The facade restores the `std::vector` semantics the codec relies on that plain `PODArray` lacks (copyable; value-initializing `resize` and sized constructor), so it is a drop-in. The standalone cross-validation harnesses compile these headers without the ClickHouse runtime, so under `PCODEC_STANDALONE` the container falls back to `std::vector`; because the facade mirrors `std::vector` semantics exactly, the production (`PODArray`) and oracle (`std::vector`) builds behave identically, keeping the reference-`.pco` cross-check faithful to the production path. The two `std::unordered_map` usages in IntMult detection (cold path) keep `std::vector` semantics via the sanctioned `STYLE_CHECK_ALLOW_STD_CONTAINERS` marker. Also add the `database = currentDatabase()` condition to the `system.parts` queries in `04303_pco_codec.sql` (required by the test style check). Co-Authored-By: Claude Opus 4.8 <[email protected]>
`system.codecs` now lists the `PCO` codec, so the existing `01222_system_codecs` test reference needs the new row (method byte 157, experimental) and the updated codec count (14 -> 15). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses the review findings on the new PCO (pcodec) codec: - `LatentDecoder.h`: fix `Conv1` delta inversion to output the reconstructed batch `residuals[order..order+len)` instead of the carried-in delta state `residuals[0..len)`, which produced shifted/stale values for reference `.pco` streams using `Conv1`. - `StandaloneDecoder.h`: reject `Conv1` for 64-bit latent types (the signed accumulator widening is lossy and unsupported), bound the `Lookback` window against the chunk size before `initPage` allocates scratch, and reject `FloatQuant` `quant_k` larger than the float type precision so the join shifts can never reach undefined behavior on a malformed stream. - `BitReader.h`: bounds-check `readUint`, `readBool`, and `readAlignedBytes` against `unpadded_bit_size` so truncated/malformed metadata fails closed instead of being decoded from the padding area. The hot batch loops are bounded once per batch via `checkInBounds` plus `DECODE_BATCH_OVERSHOOT` of readable slack in the source buffer. - `Metadata.h`: bound the `Dict` length against the remaining stream size before resizing, avoiding a large allocation driven by a tiny malformed stream. - `CompressionCodecPco.cpp`: decode straight into `dest` only when the output pointer is aligned for the element type (otherwise use aligned scratch), since `ICompressionCodec::decompress` does not guarantee alignment; enlarge the padded decode buffer to `DECODE_BATCH_OVERSHOOT`. - `StandaloneEncoder.h`: split blocks larger than `MAX_ENTRIES` values into multiple chunks instead of truncating the 24-bit per-chunk count and writing an unreadable stream; update the size bounds accordingly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… test After merging master, two follow-ups: - `src/Common/TargetSpecific.h` dropped the combined `MULTITARGET_FUNCTION_X86_V4_V3` multi-target macro (it now provides only the V4 variant). Define the V4+V3+default expansion the pcodec hot decode loops rely on locally in `LatentDecoder.h`, in terms of the per-arch attribute macros the header still exposes, so the codec keeps its AVX2 (`x86-64-v3`) and AVX-512 (`x86-64-v4`) specializations. - Renumber the stateless test `04303_pco_codec` to `04306_pco_codec` (master added several `04303_*`/`04304_*` tests) and reduce its row counts so it no longer trips the `Test runs too long` limit on the MSan flaky check, while still spanning many decode batches across every supported numeric type. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The commit adapting the codec to master's `TargetSpecific.h` referenced `X86_64_V3_FUNCTION_SPECIFIC_ATTRIBUTE`, but that header only exposes a per-function attribute macro for the V4 target — there is no V3 one. On x86-64 (`ENABLE_MULTITARGET_CODE`), the `_x86_64_v3` specialization of the hot decode loops therefore failed to declare, while `dispatchReadOffsets` still called it, breaking the build with `use of undeclared identifier 'pcoReadOffsetsImpl_x86_64_v3'` (Fast test). Define `X86_64_V3_FUNCTION_SPECIFIC_ATTRIBUTE` locally in the codec header, matching the `arch=x86-64-v3` target that the header's `BEGIN_X86_64_V3_SPECIFIC_CODE` block uses, guarded by `#ifndef` so it composes if the shared header gains the macro later. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Several correctness and fail-close hardening fixes raised in review: - `updateHash` now folds in `data_bytes_size` and the pcodec number-type byte. `PCO` is type-dependent, but the hash previously covered only the `PCO(level)` AST. Compact parts group substreams by codec hash, so a `UInt32`, `Int64` and `Float64` column all using `CODEC(PCO)` could share one codec object and encode later streams with the wrong width/type. (`Int64` and `Float64` share a width but differ in type byte, so both are needed — mirrors `Gorilla`'s `data_bytes_size` hashing.) - `getMaxCompressedDataSize` is computed in 64-bit and fails closed when the bound exceeds `UInt32`. The old `UInt32` expression could wrap for wide 1-byte blocks and under-reserve the destination buffer. - `decodeStandalone` validates that each chunk's number-type width matches the codec element width. The decompress path picks the aligned/scratch output from the outer width, so a malformed block with a wider inner type (outer width 4 wrapping an `F64`/`U64` chunk) could write 8-byte stores through a 4-byte-aligned pointer. - Reject newer wrapped format minors (`4.x` with `x > 1`); we only decode through `4.1`, and a newer minor may change metadata semantics. - Reject corrupt `Lookback` distance `0` (would read the slot being written) and `Classic`/other bins whose `lower + max-offset` overflows the latent type (would wrap in the offset add instead of reporting corrupt data). - Docs: `PCO` supports `Decimal32`/`Decimal64` only (not `Decimal128`/ `Decimal256`), and it is the embedded standalone payload — not the whole compressed block — that is wire-compatible with reference `.pco`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed
The other finding — |
The standalone `.pco` decoder reconstructed `IntMult` and `FloatQuant` values
without validating the mode-specific decomposition invariants. Because
`CompressedReadBufferBase` dispatches external compressed frames by method byte
alone, a checksummed `0x9d` (`PCO`) frame reaches this decoder without
`allow_experimental_codecs`, so a malformed stream could silently decode to
fabricated values instead of raising a decompression exception.
Validate the decomposition in the join, matching the encoder in
`Modes.h::splitForMode`, and throw on violation:
- `IntMult`: `base != 0`, `secondary < base`, and `primary * base + secondary`
fits the latent width (checked with the overflow builtins so the check
itself stays defined for sub-word latents).
- `FloatQuant`: `primary` occupies at most `latentBits - k` bits and the
remainder `m` fits in `k` bits.
These checks never reject a valid stream: they are the exact inverse of the
encoder's split. Extend `gtest_pcodec_encode_bounds` and
`gtest_pcodec_malformed_block` (the latter reaching the guard through
`codec->decompress`, i.e. the shared compressed-frame reader) with malformed
`IntMult`/`FloatQuant` regressions, plus well-formed baselines that still
round-trip.
Addresses the AI Review finding on `StandaloneDecoder.h`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed The bot's follow-up was correct that this is a current fail-closed boundary, not only a future raw- The join now validates the decomposition against the encoder's split (
These are the exact inverse of the encoder's split, so they never reject a valid stream. New regressions: The higher-level review points from @rienath (whether to add the codec at all, and the maintainability of the hand-ported C++ rewrite vs. linking the Rust crate) remain open for your decision. |
The `Build (arm_tidy)` check failed compiling the two gtest files added in the previous commit (`gtest_pcodec_malformed_block.cpp` and `gtest_pcodec_encode_bounds.cpp`): `clang-tidy`'s `bugprone-argument-comment`, run with `-warnings-as-errors`, rejected inline argument comments whose names did not match the callee's parameter names — `/*base=*/`/`/*primary=*/` on `buildIntMultStandaloneU32` (params `base_latent`/`primary_latent`) and `/*primary=*/`/`/*m=*/` on `buildFloatQuantStream` (params `primary_latent`/`secondary_latent`). `bugprone-argument-comment` is a `clang-tidy`-only check, not a compiler warning, so it is not caught by a plain `-Weverything -Werror` compile; it only runs in the tidy build. Rename the argument comments to match the parameter names exactly. This is a comment-only change with no behavioral effect. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106222&sha=a86a41f89c22f922a954f6049531af2a4ee3473d&name_0=PR&name_1=Build%20%28arm_tidy%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed The two gtest files added in
This is why the local |
|
The On the new AI Review blocker (
Scope note: |
|
Answering questions:
As a philosophical observation, today the original language of a library does not matter (for codebases under 10k lines of code, assuming they have good test coverage), you can get what you want in your desired language. |
Empirical comparison: PCO vs ALP vs existing codecs on mgbench / uk_price_paid / hitsSince the open question here is "is there a reasonable use-case for this codec in the presence of ALP?", I measured actual per-column compression on three real datasets. Method. Built nothing — the PR branch already carries both Aggregate — total bytes if a single codec is used for all numeric columns
Float columns — the direct ALP head-to-head (ratio, higher is better)
Integer columns — PCO vs the existing integer codecs
Compression & decompression throughputSingle-thread, uncompressed source in page cache, Floats
Integers
Speed takeaways: PCO's encoder is consistently the slowest of all codecs (44–238 MB/s single-thread — ~2–5× slower than ZSTD; Two micro-benchmarks worth flagging
ConclusionThe two codecs barely overlap, so ALP does not make PCO redundant — PCO covers all integer types (ALP can't) plus high-entropy floats, and it wins 2 of 3 datasets outright on ratio; ALP wins none here. Conversely PCO does not subsume ALP (in ALP's Float64-decimal sweet spot, ALP compresses ~2.7× better than PCO — 3.18× vs 1.18× — and on floats generally ALP decodes ~1.8–1.9 GB/s vs PCO's ~1 GB/s). But PCO is not a free or universal win: "PCO everywhere" is larger than "ZSTD everywhere" on So the reasonable use-case is real but niche and opt-in: specific numeric columns with smooth / multimodal / high-entropy distributions (counters, timings, IDs, sensor measurements) where a per-column +10–40% ratio is worth ~2–5× slower writes — not a new default, and not justified as "the float codec" when ALP/ZSTD already cover that space. Method + full 41-column data: PR CI |
|
@rienath, now we have the answer. |
|
About the above, likely the comparison has two flaws:
Nevertheless, I conclude that PCO is defended and can be merged. |
Resolve conflicts from the new `SZ3` codec that master added on the same method byte `0x9d` that `PCO` used: - `CompressionInfo.h`: reassign `PCO` to the next free method byte `0x9e` (`SZ3` keeps `0x9d`). The method byte is ClickHouse's compressed-block framing, not part of the embedded standalone `.pco` stream, so this is wire-neutral for pcodec interop. - `CompressionFactory.cpp` / `registerCompressionCodecs.h`: register both `SZ3` (under `#if USE_SZ3`) and `PCO`. - `MergeTreeSettings.cpp`: keep `PCO`'s `checkCompressionCodecSettings`, which is a superset of master's inline validation — building each untyped codec with a null type via `get` rejects the lossy `SZ3`, while additionally rejecting experimental and column-type-requiring codecs; also covers user `ATTACH`. - Docs `create/table.md`, spec `NativeFormat.md`, and `01222_system_codecs` reference: list both codecs; `PCO` moves to `0x9e` (spec: added `PCO` to the per-column codec registry table and dropped it from the whole-stream table, since it is never emitted on the transport path); codec count is now 16. - Update `0x9d` -> `0x9e` in `PCO` code comments.
|
Merged the latest `master` and resolved the conflicts. The main one: `master` added the new `SZ3` codec on method byte `0x9d` — the byte `PCO` had been using — so I reassigned `PCO` to the next free byte `0x9e` (`SZ3` keeps `0x9d`). This is wire-neutral for pcodec interop, since the method byte is ClickHouse's compressed-block framing and is not part of the embedded standalone `.pco` stream. Updated accordingly: the `CompressionMethodByte` enum, `CompressionFactory`/`registerCompressionCodecs`, the `create/table.md` docs, the `NativeFormat` spec (added `PCO` to the per-column codec registry table and dropped it from the whole-stream table, since it is never emitted on the transport path), the `01222_system_codecs` reference (both codecs now listed; codec count is 16), and the `PCO` code comments. Also reconciled `MergeTreeSettingsImpl::checkCompressionCodecSettings` with `master`'s new lossy-codec validation: the existing gate is a superset — building each untyped codec with a null type via `get` already rejects the lossy `SZ3` (all its rejection paths throw `BAD_ARGUMENTS`), and it additionally rejects experimental / column-type-requiring codecs and also covers user `ATTACH`. The two validations do not double up. Verified the affected translation units compile locally (`clickhouse_compression`, `MergeTreeSettings`, `AlterCommands`, `MergeTreeData`); CI will re-run on the merge. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1995/2170 (91.94%) · Uncovered code |
…e speed The `PCO` section promised "substantially better compression ratios ... at comparable speed", but the benchmark measurements posted in the PR (#106222 (comment)) show that encoding is consistently several times slower than `ZSTD` and decoding speed is workload-dependent. Reword the claim to be ratio-focused, state the write/read speed tradeoff explicitly, and mention that constant and low-cardinality columns compress much worse because the codec has no run-length or match-based path. Addresses the `clickhouse-gh` review thread on docs/en/sql-reference/statements/create/table.md.
|
Pushed CI triage for the two failures on
|
rienath
left a comment
There was a problem hiding this comment.
Even with chains and up to ZSTD(3), the wins are real, especially for heavy-tailed columns. You mentioned that performance optimisations we introduced in the port are moderate. The original repo is over 10k lines and port is not complete (the current version encodes only 3 of 5 modes and 2 of 4 delta encodings, completing it is thousands more lines). Currently, the original repo would compress better. Given this and the maintenance burden, what do you think of linking the crate?
The only non-upstreamable change is fail-closed validation, but we could add it in our repo on top of the crate (the no-expansion bound already works through the public API).
|
I don't mind, we can try... |
|
Rust version here: #110613 |
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 ClickHouse#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]>
Adds pcodec (
pco) as a new ClickHouse compression codecPCO. pcodec is a lossless codec specialized for fixed-width numeric sequences. On numeric columns with smooth, multimodal, or high-entropy distributions (measurements, timings, counters, identifiers) it often beatsGorilla/FPC/ZSTD/ALPon ratio — at a speed cost: encoding is several times slower thanZSTD, and decoding is workload-dependent (from on par withZSTDto a few times slower); it has no run-length or match-based path, so constant/low-cardinality columns compress much worse. See the empirical comparison on mgbench / uk_price_paid / hits for per-column measurements.Rather than linking the Rust crate, this is a native C++ reimplementation, which fits ClickHouse's all-C++ codec tradition (
Gorilla/FPC/ALP/T64) and allows future ClickHouse-style runtime CPU dispatch of the hot loops.The codec is bit-for-bit wire-format compatible with the reference pcodec v1.0.2 (format major 4 / minor 1, standalone version 3). This gives
.pcointerop and a free cross-validation oracle: streams produced by this codec are decoded byte-identically by the reference Rust implementation, and vice versa. This was used in both directions during development.Supported types are all fixed-width numerics via their underlying integer/float width:
Int8..Int64,UInt8..UInt64,Float32/Float64, and the types backed by them (Date,DateTime,Decimal32/Decimal64,IPv4,Enum, ...). The full decode path is implemented (Classic/IntMult/FloatMult/FloatQuant/Dictmodes;None/Consecutive/Lookback/Conv1delta; interleaved 4-way tANS). The encode path auto-selectsClassic/IntMult/FloatQuantmodes and a consecutive delta order via cheap sampling, only switching away fromClassicwhen it reduces the estimated size. The encoder additionally guarantees no expansion: a chunk whose chosen configuration would exceed the raw data size (plus small framing) is re-encoded with a trivial single-bin configuration, sogetMaxCompressedDataSize(the per-block bufferCompressedWriteBufferreserves) is tight.The codec is gated behind
allow_experimental_codecsfor the first release. Because it needs the column type, it can only be specified per column: the untyped MergeTree compression settings (marks_compression_codec,primary_key_compression_codec,default_compression_codec) reject it (and experimental codecs in general) at validation time.A stateless test (
04306_pco_codec) round-trips every supported numeric type (per-element verification, edge cases, and codec chaining such asCODEC(Delta, PCO)). A gtest (gtest_pcodec_fixtures.cpp) additionally decodes reference-generated.pcofixtures for the decoder-only modes (FloatMult,Dict,Lookback,Conv1), which the encoder round-trip cannot reach.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new experimental compression codec
PCO(a native port of pcodec), specialized for fixed-width numeric columns. It is wire-format compatible with pcodec.pcostreams and is enabled withallow_experimental_codecs.Documentation entry for user-facing changes:
PCOcodec is documented indocs/en/sql-reference/statements/create/table.md).