Skip to content

Add pcodec (PCO) compression codec - #106222

Closed
alexey-milovidov wants to merge 43 commits into
masterfrom
add-pcodec-codec
Closed

alexey-milovidov wants to merge 43 commits into
masterfrom
add-pcodec-codec

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Adds pcodec (pco) as a new ClickHouse compression codec PCO. 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 beats Gorilla/FPC/ZSTD/ALP on ratio — at a speed cost: encoding is several times slower than ZSTD, and decoding is workload-dependent (from on par with ZSTD to 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 .pco interop 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/Dict modes; None/Consecutive/Lookback/Conv1 delta; interleaved 4-way tANS). The encode path auto-selects Classic/IntMult/FloatQuant modes and a consecutive delta order via cheap sampling, only switching away from Classic when 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, so getMaxCompressedDataSize (the per-block buffer CompressedWriteBuffer reserves) is tight.

The codec is gated behind allow_experimental_codecs for 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 as CODEC(Delta, PCO)). A gtest (gtest_pcodec_fixtures.cpp) additionally decodes reference-generated .pco fixtures for the decoder-only modes (FloatMult, Dict, Lookback, Conv1), which the encoder round-trip cannot reach.

Changelog category (leave one):

  • Experimental Feature

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 .pco streams and is enabled with allow_experimental_codecs.

Documentation entry for user-facing changes:

  • Documentation is written (the PCO codec is documented in docs/en/sql-reference/statements/create/table.md).

alexey-milovidov and others added 2 commits June 1, 2026 07:59
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
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ce326c5]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
02477_single_value_data_string_regression FAIL cidb
03305_mergine_aggregated_filter_push_down FAIL cidb
03248_create-same-table-concurrently-with-replicated-engine FAIL cidb
02210_processors_profile_log_2 FAIL cidb
04033_tpc_ds_q13 FAIL cidb
03761_primes_long FAIL cidb
01274_alter_rename_column_distributed FAIL cidb
00443_optimize_final_vertical_merge FAIL cidb
02771_system_user_processes FAIL cidb
03297_input_compression_autodetect FAIL cidb
121 more test cases not shown
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED
Build (riscv64) DROPPED

AI Review

Summary

This PR adds the experimental PCO compression codec, wires it through the relevant MergeTree and query-time validation paths, updates the Native format specification, and adds focused interoperability and malformed-input coverage. I reviewed the current head together with the full prior discussion and inline thread history, and I did not find a remaining correctness, compatibility, or validation issue that still warrants action.

Final Verdict

✅ No blocking or major findings on the current head.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jun 1, 2026
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
Comment thread src/Compression/Pcodec/BitReader.h Resolved
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]>
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
`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]>
Comment thread src/Compression/CompressionCodecPco.cpp Resolved
alexey-milovidov and others added 3 commits June 3, 2026 02:11
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]>
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
Comment thread src/Compression/Pcodec/Metadata.h Resolved
Comment thread src/Compression/Pcodec/LatentDecoder.h Resolved
Comment thread src/Compression/CompressionCodecPco.cpp Resolved
Comment thread src/Compression/Pcodec/Metadata.h Resolved
Comment thread src/Compression/CompressionCodecPco.cpp Resolved
Comment thread src/Compression/CompressionCodecPco.cpp Resolved
alexey-milovidov and others added 3 commits June 5, 2026 08:32
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 5114dc28353 addressing the second AI Review Request changes finding (temporary_files_codec, TemporaryDataOnDisk.cpp).

getCodec for temporary_files_codec only rejected codecs that requiresColumnTypeToCompress (e.g. the experimental PCO). An experimental codec that does not require a column type — ALP — still passed through and could be used for external sort/aggregation spill files even with allow_experimental_codecs = 0. Now the experimental-codec gate is enforced here too, matching the <compression> config selector and the untyped MergeTree compression settings (marks_compression_codec, ...); experimental codecs can only be specified per column. 04337_pco_codec_untyped_settings gets an ALP case (single codec and inside a chain).

The other finding — FloatQuant / IntMult decomposed-latent range validation in StandaloneDecoder.h — is being discussed in its inline thread.

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

Copy link
Copy Markdown
Member Author

Pushed a86a41f89c2 addressing the remaining AI Review Request changes finding — the FloatQuant / IntMult decomposed-latent range validation in StandaloneDecoder.h.

The bot's follow-up was correct that this is a current fail-closed boundary, not only a future raw-.pco concern: CompressedReadBufferBase::readHeaderAndGetCodecAndSize dispatches an external frame by its method byte alone (CompressionCodecFactory::instance().get(method)), so a checksummed 0x9d frame reaches this decoder without allow_experimental_codecs. A malformed IntMult / FloatQuant chunk would then decode to fabricated values by wrapping modularly instead of raising a decompression exception.

The join now validates the decomposition against the encoder's split (Modes.h::splitForMode) and throws on violation:

  • IntMult: base != 0, secondary < base, and primary * base + secondary fits the latent width.
  • FloatQuant: primary fits in latentBits - k bits and the remainder m <= (1 << k) - 1.

These are the exact inverse of the encoder's split, so they never reject a valid stream. New regressions: gtest_pcodec_malformed_block runs a malformed IntMult block through codec->decompress (the shared compressed-frame reader), and gtest_pcodec_encode_bounds covers malformed IntMult/FloatQuant across all latent widths, each with a well-formed baseline that still round-trips. Verified locally: all three touched TUs compile clean under -Weverything -Werror, and a standalone run of the decoder guards passes all 13 valid-decodes-vs-malformed-throws checks.

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

Copy link
Copy Markdown
Member Author

Pushed 399aef3e027 to fix the only real, PR-caused CI failure: Build (arm_tidy).

The two gtest files added in a86a41f89c2 failed clang-tidy's bugprone-argument-comment (run with -warnings-as-errors) — 18 inline argument comments whose names did not match the callee's parameter names:

  • buildIntMultStandaloneU32(/*base=*/…, /*primary=*/…) — params are base_latent / primary_latent
  • buildFloatQuantStream(/*k=*/…, /*primary=*/…, /*m=*/…) — params are primary_latent / secondary_latent

This is why the local -Weverything -Werror compile passed but CI failed: bugprone-argument-comment is a clang-tidy-only check, not a compiler warning, so it only runs in the tidy build. The fix renames the argument comments to match the parameter names exactly — comment-only, no behavioral change.

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

Comment thread src/Compression/CompressionCodecPco.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Build (arm_tidy) fix from 399aef3e is green — all 18 builds pass and there are no test failures on the current head; CI is re-running the remaining stages normally.

On the new AI Review blocker (CompressionCodecPco.cpp:358 — registering PCO makes method byte 0x9d decodable on the external-data path with allow_experimental_codecs = 0): leaving this design call to you, since it looks like something you've already decided rather than a fresh regression:

  • Same pattern as the existing experimental codec. ALP (0x9c, also isExperimental() == true) is registered globally in CompressionFactory.cpp next to PCO and is reachable through the identical external_data = true path (HTTPHandler decompress=1 and direct-client TCPHandler), also without an allow_experimental_codecs check. So PCO follows the established convention here rather than opening a new class of exposure; the bot's suggested external_data-side isExperimental() rejection would be a cross-cutting change to CompressedReadBufferBase that also alters ALP's behavior.
  • This is the documented contract. The NativeFormat spec update already states that the transport emits only NONE/LZ4/ZSTD but the shared CompressedReadBuffer accepts any registered method byte on input.
  • Mitigation already chosen. The 399aef3e-era hardening (fail-closed IntMult/FloatQuant decomposition validation via the inverse of Modes.h::splitForMode, plus the malformed-block gtests) is exactly the "decoder is robust on untrusted transport input" approach for this path.

Scope note: external_data = true is set only for transport input; stored MergeTree part reads use external_data = false, so a block there would be transport-only and would not affect reading PCO-compressed parts either way. No code change made — deferring the accept-vs-reject-on-transport decision (and @rienath's higher-level "should we add this codec / C++ vs Rust" question) to you.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Answering questions:

  1. About comparison with ALP. Yes, if there are no useful cases when it is better, we are not going to merge PCodec.

  2. About maintainability. I ported it to C++ specifically for maintainability - because it makes it more accessible, and the build system is simpler. I was also worried a little about memory management (but likely for nothing, as the input and output buffers shouldn't be managed by the library). And also I used it as an opportunity to optimize performance a little (but with only moderate results). If it is in Rust, we can have it if the library does not need a lot of modifications, but as soon as I faced the need to modify something, I ported it to C++.

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.

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Jul 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Empirical comparison: PCO vs ALP vs existing codecs on mgbench / uk_price_paid / hits

Since 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 CompressionCodecALP.cpp and CompressionCodecPco.cpp, so I used this PR's build_arm_release CI binary (v26.7.1.1). Loaded mgbench (logs1 = 22M rows × 18 Float32 sensor columns; logs2 = 76M; logs3 = 109M), uk_price_paid (31.3M), and full hits (99,997,497 rows). For each numeric column I encode it under every applicable codec in one wide-part MergeTree and read column_data_compressed_bytes from system.parts_columns; ratio = uncompressed/compressed. Floats measured on non-null values, data kept in each table's real primary-key order. 41 columns total.

Aggregate — total bytes if a single codec is used for all numeric columns

dataset ALP ZSTD PCO PCO's marginal gain added on top of the full existing toolbox (ZSTD/T64/GCD/Delta/DoubleDelta/Gorilla + ALP)
mgbench floats (logs1, 18 cols) 0.88 GB (worst) 0.49 GB 0.42 GB (−14%) +8.7%
uk_price_paid (price, date) n/a (int) 0.13 GB 0.10 GB (−27%) +26.9%
mgbench logs2/3 (4 cols) — 0.269 GB 0.260 GB (−3.2%) small
hits (17 int cols) n/a 2.25 GB 2.44 GB (+8.8% larger) +4.4%
  • PCO is the single best codec on 28 of 41 columns (68%).
  • ALP does not win a single column in any of the requested datasets, and is worse than PCO on every float column.

Float columns — the direct ALP head-to-head (ratio, higher is better)

winner is the best of all codecs tried.

column PCO ALP ZSTD best other CH codec winner
cpu_idle 2.73 1.32 2.49 2.18 Delta_ZSTD PCO
cpu_nice 15.88 10.15 16.18 14.79 Delta_ZSTD ZSTD
cpu_system 2.64 1.54 2.63 2.22 Delta_ZSTD PCO
cpu_user 2.55 1.49 2.52 2.17 Delta_ZSTD PCO
cpu_wio 2.74 1.54 2.74 2.22 Delta_ZSTD PCO
disk_free 36.98 3.36 23.08 29.32 DoubleDelta_ZSTD PCO
disk_total 984.29 44.96 1285.68 867.91 Delta_ZSTD ZSTD
part_max_used 242.82 23.60 382.64 314.91 Delta_ZSTD ZSTD
load_fifteen 3.10 1.68 3.01 2.78 Delta_ZSTD PCO
load_five 1.97 1.21 1.92 1.70 Delta_ZSTD PCO
load_one 1.90 1.21 1.81 1.65 LZ4 PCO
mem_buffers 5.49 1.38 3.10 4.60 Delta_ZSTD PCO
mem_cached 6.79 1.36 3.76 5.40 Delta_ZSTD PCO
mem_free 2.74 1.14 1.77 2.09 Delta_ZSTD PCO
mem_shared 1.00 1.00 25.49 130.73 LZ4 LZ4
swap_free 46.50 4.62 29.89 42.07 Delta_ZSTD PCO
bytes_in 1.80 1.00 1.47 1.55 Gorilla_ZSTD PCO
bytes_out 1.73 1.00 1.51 1.51 Gorilla_ZSTD PCO
event_value 2.81 2.21 3.24 2.69 Delta_ZSTD ZSTD

ALP,ZSTD (giving ALP an entropy backend) was also measured on a few columns: it helps a lot (cpu_idle 1.32→1.58, disk_total 43→344) but still never beats plain ZSTD or PCO here.

Integer columns — PCO vs the existing integer codecs

column PCO ZSTD best other CH codec winner
price 2.87 1.72 1.72 GCD_ZSTD PCO
date 1.21 1.08 1.08 GCD_ZSTD PCO
status_code 14.22 9.61 9.57 GCD_ZSTD PCO
object_size 6.32 5.00 5.48 T64_ZSTD PCO
device_floor 10.84 14.67 14.55 GCD_ZSTD ZSTD
WatchID 1.03 1.00 1.03 T64_ZSTD PCO
UserID 5.52 4.75 4.78 Gorilla_ZSTD PCO
RefererHash 1.65 2.54 2.54 GCD_ZSTD GCD_ZSTD
URLHash 1.39 2.04 2.04 GCD_ZSTD GCD_ZSTD
EventTime 6.24 4.08 4.39 Delta_ZSTD PCO
EventDate 730.89 934.73 688.13 GCD_ZSTD ZSTD
CounterID 1040.98 1230.11 854.03 Delta_ZSTD ZSTD
RegionID 9.88 8.42 8.39 GCD_ZSTD PCO
ClientIP 3.96 3.95 3.95 GCD_ZSTD PCO
IPNetworkID 5.58 5.01 5.41 Gorilla_ZSTD PCO
ResolutionWidth 6.68 6.88 6.86 GCD_ZSTD ZSTD
Age 11.39 9.43 9.38 GCD_ZSTD PCO
OS 12.62 10.48 12.46 T64_ZSTD PCO
IsRefresh 21.92 19.79 29.03 T64_ZSTD T64_ZSTD
IsMobile 53.27 32.69 54.42 T64_ZSTD T64_ZSTD
SendTiming 14.22 11.65 12.63 T64_ZSTD PCO
ResponseEndTiming 11.33 8.14 10.35 T64_ZSTD PCO

Compression & decompression throughput

Single-thread, uncompressed source in page cache, SELECT sum(v) for decode (best of 3). Format: ratio× / compress MB/s / decompress MB/s (MB = uncompressed).

Floats

column ZSTD ALP PCO
cpu_idle 2.51× / 270 / 879 1.33× / 111 / 1818 2.75× / 90 / 1000
disk_total 1289.32× / 777 / 2000 49.96× / 435 / 1951 989.18× / 423 / 2286
event_value 3.55× / 196 / 808 2.30× / 259 / 1860 3.07× / 114 / 1013

Integers

column best other CH codec ZSTD PCO
price T64_ZSTD (1.62×/218/544) 1.72× / 202 / 734 2.87× / 44 / 541
UserID Delta_ZSTD (6.34×/364/1231) 6.58× / 426 / 1778 7.55× / 238 / 1758
OS T64_ZSTD (13.06×/234/1000) 11.00× / 282 / 909 13.16× / 114 / 519
SendTiming T64_ZSTD (13.80×/244/676) 12.70× / 250 / 1248 15.92× / 152 / 1248

Speed takeaways: PCO's encoder is consistently the slowest of all codecs (44–238 MB/s single-thread — ~2–5× slower than ZSTD; uk.price is the worst at 44 MB/s). PCO decode is variable: comparable to ZSTD on some columns (UserID 1758≈1778, SendTiming 1248=1248), faster on very repetitive data (disk_total 2286), but notably slower on others (OS 519 vs ZSTD 909, uk.price 541 vs 734) — and generally behind LZ4. ALP is a genuinely fast decoder (~1.8–1.9 GB/s, its design point), but on this data it doesn't convert that into a competitive ratio.

Two micro-benchmarks worth flagging

  • Constant / low-cardinality columns (very common in practice): PCO has no RLE/LZ path. On a constant Float32 column PCO gets 1.00× (no compression at all) vs ZSTD 17.9×; on a 5-distinct-value UInt32, PCO 42× vs ZSTD 1080×. This is why PCO loses on hits sorted keys, hashes and flags.
  • ALP's actual sweet spot — clean Float64 2-decimal data (uniform range): ALP 3.18× > ZSTD 2.02× > PCO 1.18× (PCO worst), and ALP decodes at ~1.9 GB/s. None of the three requested datasets contain such Float64-decimal columns, which is the whole reason ALP looks weak above.

Conclusion

The 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 hits, it degenerates to 1.0× on constant/low-cardinality columns, and it is the slowest encoder measured (down to 44 MB/s). Its incremental gain on top of the existing toolbox (ZSTD/T64/GCD/Delta + ALP) is ~4% on hits, ~9% on mgbench floats, ~27% on uk_price_paid.

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 build_arm_release binary (both codecs), clickhouse local, per-column column_data_compressed_bytes from system.parts_columns; mgbench 22M/76M/109M rows, uk_price_paid 31.3M, hits 99,997,497 (full). Ratios measured on data in each table's real primary-key order; floats on non-null values.

@alexey-milovidov alexey-milovidov removed the hold Skip for auto-updating. label Jul 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rienath, now we have the answer.

@alexey-milovidov
alexey-milovidov requested a review from rienath July 14, 2026 00:14
@alexey-milovidov

Copy link
Copy Markdown
Member Author

About the above, likely the comparison has two flaws:

  • it uses ZSTD level 1, not higher;
  • it does not compare codecs combined with ZSTD.

Nevertheless, I conclude that PCO is defended and can be merged.

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

I’ll take a look

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

Copy link
Copy Markdown
Member Author

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.

@mintlify

mintlify Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 14, 2026, 5:02 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 1995/2170 (91.94%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Member Author

Pushed ce326c51dc8 addressing the AI Review Request changes verdict (and the corresponding clickhouse-gh inline thread on the docs): the PCO docs no longer claim "comparable speed". The paragraph now makes a ratio-focused claim scoped to the data where the codec actually wins (smooth / multimodal / high-entropy numeric distributions), states the speed tradeoff explicitly (encoding is several times slower than ZSTD; decoding ranges from on par with ZSTD to a few times slower depending on the data), and mentions that constant/low-cardinality columns compress much worse (no run-length or match-based path). This matches the measurements posted above. I also updated the first paragraph of the PR description accordingly.

CI triage for the two failures on 4306f98fab3, both unrelated to this PR:

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

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

I don't mind, we can try...

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Rust version here: #110613

CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Sep 16, 2026
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]>

This branch was successfully deployed

1 active deployment
staging - docs — ce326c51 Deployed Jul 15, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants