Skip to content

Chimp compression for floating point data - #66467

Closed
panagiotisl wants to merge 77 commits into
ClickHouse:masterfrom
panagiotisl:chimp-compression
Closed

panagiotisl wants to merge 77 commits into
ClickHouse:masterfrom
panagiotisl:chimp-compression

Conversation

@panagiotisl

@panagiotisl panagiotisl commented Jul 13, 2024 •

Copy link
Copy Markdown

Changelog category (leave one):

  • New Feature

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

Added the experimental Chimp floating-point compression codec for Float32 and Float64 columns (especially effective on time series). It is gated behind the allow_experimental_codecs setting. Based on Panagiotis Liakos, Katia Papakonstantinopoulou, Yannis Kotidis: Chimp: Efficient Lossless Floating Point Compression for Time Series Databases. Proc. VLDB Endow. 15(11): 3058-3070 (2022), https://dl.acm.org/doi/abs/10.14778/3551793.3551852

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

  • Motivation: Chimp is a lossless XOR-based floating-point codec that refines Gorilla: it keeps a small ring buffer of recent values to pick a better XOR reference and encodes the trailing zeros of the XOR result, which makes it much more effective than Gorilla on values with local correlation, such as time series. The reference is Panagiotis Liakos, Katia Papakonstantinopoulou, Yannis Kotidis: Chimp: Efficient Lossless Floating Point Compression for Time Series Databases, PVLDB 15(11).

  • Measured numbers (single machine, clickhouse local, 10M Float64 values of a smooth sine plus 2-decimal noise, so ratios are dataset-specific and not a general claim):

    Codec Compressed Ratio INSERT (1 thread) SELECT sum(x) (1 thread, best of 3)
    NONE 76.32 MiB 1.00
    Gorilla 63.35 MiB 1.20 0.77 s 0.31 s
    FPC 61.57 MiB 1.24 0.55 s 0.26 s
    Chimp 22.97 MiB 3.32 0.52 s 0.25 s
    ALP 12.80 MiB 5.96 0.57 s 0.15 s

    So on this data Chimp compresses about 2.8x better than Gorilla at no cost in compression or decompression speed, which is the claim of the paper. It does not beat ALP, which was added to ClickHouse later and is both smaller and faster here — that is the open product question on this pull request (whether an experimental Chimp is worth carrying next to ALP), and it is a maintainer decision, not something this description asserts. Chimp is registered in the existing tests/performance/codecs_float_insert.xml and codecs_float_select.xml performance tests, so the CI performance job covers it as well.

  • Validation side effect: a floating-point time series codec is resolved and applied per substream, so the float-only sanity check now requires every element of a composite type to be floating-point, instead of accepting the column as soon as one of them was. This tightens Gorilla, FPC, ALP and SZ3 along with Chimp: Tuple(Float64, UInt64) CODEC(Gorilla) used to be created with default settings and applied Gorilla to the UInt64 substream, bypassing allow_suspicious_codecs for that part of the column. Such a definition now needs allow_suspicious_codecs, like any other non-floating-point type. Homogeneous composites are unaffected, and ATTACH runs with the sanity check disabled, so tables created earlier keep loading.

  • Parameters: The implementation has been based on the implementation of Gorilla so it requires the same parameters.

  • Example use: The implementation has been based on the implementation of Gorilla so it can be used exactly like Gorilla.

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

@CLAassistant

CLAassistant commented Jul 13, 2024 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 13, 2024
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-feature Pull request with new product feature label Jul 13, 2024
@alexey-milovidov

Copy link
Copy Markdown
Member

Need to add functional tests (with CREATE TABLE), not only unit tests.

@panagiotisl

Copy link
Copy Markdown
Author

I've copied an existing functional test of Gorilla to create a new functional test for Chimp. We can discuss in Slack if more tests are required.

@alexey-milovidov

Copy link
Copy Markdown
Member

Ok, it will be enough for tests.
But this test has failed.

@panagiotisl

panagiotisl commented Jul 16, 2024 •

Copy link
Copy Markdown
Author

I have fixed the bug that was causing the previous test to fail, and I've also added Chimp in more tests where Gorilla and FPC are used. One of them is failing, so I will try to figure out why.

2024-07-16 12:51:35 libc++abi: terminating due to uncaught exception of type DB::Exception: Can not write past end of buffer. Space available is 1 bytes, required to write 8 bytes.
2024-07-16 12:51:35 /ClickHouse/tests/queries/0_stateless/02584_compressor_codecs.sh: line 24: 328151 Aborted                 (core dumped) $CLICKHOUSE_COMPRESSOR --codec 'Chimp' --codec 'LZ4' --input '02584_test_data' --output '02584_test_out'
2024-07-16 12:51:35 

@panagiotisl

Copy link
Copy Markdown
Author

After the updates I can execute all new tests successfully locally and I also see a successful execution in CI logs. However, there is a failed new test in the Stateless tests flaky check (asan) which I am not sure how to explain or reproduce. The same tests passes in Stateless tests (release, old analyzer, s3, DatabaseReplicated) and Fast test so I doubt it has to do something with the code of this PR. Logs below:

2024-07-16 18:29:20 Reason: server died 32
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.397484 [ 4677 ] <Fatal> BaseDaemon: ########################################
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.399827 [ 4677 ] <Fatal> BaseDaemon: (version 24.7.1.2132, build id: 73D8D6F99A2453614A96C48EB043B669EBAF3B1B, git hash: 65f9fb76fa9dfe868a9270aad74b43bac50b8556) (from thread 4136) (query_id: 8e2af8d5-955d-4d32-9042-f3888d3c19cd) (query: -- best case - same value
2024-07-16 18:29:20 INSERT INTO codecTest (key, name, ref_valueF64, valueF64, ref_valueF32, valueF32)
2024-07-16 18:29:20 	SELECT number AS n, 'e()', e() AS v, v, v, v FROM system.numbers LIMIT 1, 100;) Received signal sanitizer trap (-3)
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.401165 [ 4677 ] <Fatal> BaseDaemon: Sanitizer trap.
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.403692 [ 4677 ] <Fatal> BaseDaemon: Stack trace: 0x000055ed743509b7 0x000055ed748fc4af 0x000055ed63f6d536 0x000055ed63f54eef 0x000055ed63f57d85 0x000055ed63f588f8 0x000055ed80bd4b2f 0x000055ed80bd2a4a 0x000055ed80bece57 0x000055ed80b554fe 0x000055ed851fb014 0x000055ed743ca71f 0x000055ed63fd5f6a 0x000055ed855a4d55 0x000055ed855b7b32 0x000055ed855b8c96 0x000055ed858a2df6 0x000055ed8591f8cc 0x000055ed8591a07f 0x000055ed85bc83b7 0x000055ed86a6cf0e 0x000055ed868632e7 0x000055ed86862e31 0x000055ed86861e68 0x000055ed86241fee 0x000055ed86228d71 0x000055ed8622771c 0x000055ed8622721b 0x000055ed862253c7 0x000055ed7448017c 0x000055ed7448a07f 0x000055ed63f4e059 0x00007fa7931c4ac3 0x00007fa793256850
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.525632 [ 4677 ] <Fatal> BaseDaemon: 0. ./build_docker/./src/Common/StackTrace.cpp:349: StackTrace::tryCapture() @ 0x000000001aabc9b7
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:50.798592 [ 4677 ] <Fatal> BaseDaemon: 1. ./build_docker/./src/Daemon/BaseDaemon.cpp:593: sanitizerDeathCallback() @ 0x000000001b0684af
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:28:56.017155 [ 4677 ] <Fatal> BaseDaemon: 2. __sanitizer::Die() @ 0x000000000a6d9536
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:29:01.706284 [ 4677 ] <Fatal> BaseDaemon: 3. ? @ 0x000000000a6c0eef
2024-07-16 18:29:20 [46de0438d3fd] 2024.07.16 09:29:08.443495 [ 4677 ] <Fatal> BaseDaemon: 4. __asan::ReportGenericError(unsigned long, unsigned long, unsigned long, unsigned long, bool, unsigned long, unsigned int, bool) @ 0x000000000a6c3d85
2024-07-16 18:29:20 Error on processing query: Code: 32. DB::Exception: Attempt to read after eof: while receiving packet from localhost:9000. (ATTEMPT_TO_READ_AFTER_EOF) (version 24.7.1.2132)
2024-07-16 18:29:20 (query: -- best case - same value
2024-07-16 18:29:20 INSERT INTO codecTest (key, name, ref_valueF64, valueF64, ref_valueF32, valueF32)
2024-07-16 18:29:20 	SELECT number AS n, 'e()', e() AS v, v, v, v FROM system.numbers LIMIT 1, 100;)
2024-07-16 18:29:20 , result:
2024-07-16 18:29:20 
2024-07-16 18:29:20 
2024-07-16 18:29:20 
2024-07-16 18:29:20 stdout:
2024-07-16 18:29:20 
2024-07-16 18:29:20 
2024-07-16 18:29:20 Settings used in the test: --max_insert_threads 1 --group_by_two_level_threshold 1 --group_by_two_level_threshold_bytes 1 --distributed_aggregation_memory_efficient 1 --fsync_metadata 1 --output_format_parallel_formatting 1 --input_format_parallel_parsing 1 --min_chunk_bytes_for_parallel_parsing 12796707 --max_read_buffer_size 805396 --prefer_localhost_replica 0 --max_block_size 11179 --max_joined_block_size_rows 43689 --max_threads 3 --optimize_append_index 1 --optimize_if_chain_to_multiif 0 --optimize_if_transform_strings_to_enum 0 --optimize_read_in_order 1 --optimize_or_like_chain 0 --optimize_substitute_columns 1 --enable_multiple_prewhere_read_steps 1 --read_in_order_two_level_merge_threshold 26 --optimize_aggregation_in_order 0 --aggregation_in_order_max_block_bytes 28083002 --use_uncompressed_cache 1 --min_bytes_to_use_direct_io 6169612870 --min_bytes_to_use_mmap_io 1 --local_filesystem_read_method io_uring --remote_filesystem_read_method read --local_filesystem_read_prefetch 0 --

@alexey-milovidov

Copy link
Copy Markdown
Member

@panagiotisl

Copy link
Copy Markdown
Author

There was indeed a memory-related bug in the new code. I have fixed it and I have also fixed an issue with an old test I have extended, that was creating and removing files with a fixed name and could not run successfully in parallel.

@alexey-milovidov

Copy link
Copy Markdown
Member

Update (pushed c35edfed26e..4e25760f2b1):

  • Merged master (the branch had fallen ~4500 commits behind and GitHub reported the PR as conflicting). The conflicts were all inside the codec footprint: master took method bytes 0x9d (SZ3), 0x9e (Quantized), and 0x9f (ZXC), so Chimp moves to method byte 0xa0. Updated CompressionMethodByte, the NativeFormat spec, the gtest malformed-input reproducers, and the 01222_system_codecs reference accordingly.
  • Fixed the decoder early-history issue (AI review Major): the 0b00/0b01 branches now reject match_index >= min(items_read, NO_PREVIOUS_VALUES) with CANNOT_DECOMPRESS, so malformed input can no longer reference an unwritten ring slot and silently decode a zero placeholder. Regression: ChimpTest.DecompressMalformedInputEarlyHistoryReference.
  • Fixed the stale ALTER validation snapshot (AI review Major): AlterCommands::validate now advances the column type in its working snapshot after a MODIFY COLUMN type change, so ALTER TABLE t MODIFY COLUMN x Float64, MODIFY COLUMN x CODEC(Chimp) validates against the same schema apply uses. Regression: 04612_chimp_codec_multi_command_alter_type_then_codec.

Verified locally on the merged branch: full codec gtest suite (11306 tests) passes, 00950/01222/04320/04510 match their references against the built binary, and a clickhouse compressor --codec 'Chimp(8)' round-trip writes the new 0xa0 method byte. The remaining open thread (the switch-vs-if structure at CompressionCodecChimp.cpp) stays a reviewer design call, as discussed earlier.

# Conflicts:
#	tests/queries/0_stateless/01222_system_codecs.reference
The `Chimp` method-byte paragraph left two consecutive blank lines before
the `Checksum` section, which the docs `markdownlint` check rejects with
`MD012/no-multiple-blanks`.
`isReadyToCompress` was only checked in `validateCodecAndGetPreprocessedAST`,
so codecs built through `CompressionCodecFactory::get(ast, nullptr)` bypassed
it. Every no-column codec built there is a write codec — the marks, primary
key and default compression codec settings, `temporary_files_codec`, the text
index marks codec and `TTL ... RECOMPRESS CODEC(...)` at merge time — and a
`Chimp` built without a column type has an undetermined data width, so it can
describe and decompress itself but cannot compress. Rejecting it in the factory
makes the failure happen where the codec is configured, instead of serializing
`CODEC(Chimp(0))` and failing on the first write, merge or spill.

The check sits next to the existing lossy-codec check: after the `only_generic`
filter, so it does not fire for the structural substreams that skip
non-generic codecs, and inside the per-element loop, so a chained
`Chimp, LZ4` is rejected too. The decompression path
(`CompressionCodecFactory::get(uint8_t)`) and `fillCodecDescriptions` build
codecs directly through the creator and never reach this point, so reading
existing data and `system.codecs` are unaffected.

Added `ChimpTest.NoColumnWriteCodecIsRejected`: bare `Chimp` and both chain
positions are rejected without a column type, while an explicit width
(`Chimp(4)`, `Chimp(8)`) or a `Float32`/`Float64` column type is accepted, and
width-independent codecs are untouched.
@alexey-milovidov

Copy link
Copy Markdown
Member

Update (pushed 4e25760f2b1..dfba5af96be), addressing the AI Review ⚠️ Request changes verdict and the remaining red.

  • Merged master (the branch had fallen ~3100 commits behind and GitHub reported the pull request as conflicting). The single conflict was in 01222_system_codecs.reference: master flipped ZXC to is_experimental = 1; the resolution takes master's row and keeps the codec count at 18 with Chimp. The method byte 0xa0 is still free on current master.
  • Required action 1 — reject bare Chimp consistently in the no-column write settings (dfba5af96be). The isReadyToCompress check moved into CompressionCodecFactory::get(ast, column_type), next to the existing lossy-codec check: after the only_generic filter and inside the per-element loop, so a chained Chimp, LZ4 is rejected in either position. That covers default_compression_codec, marks_compression_codec, primary_key_compression_codec, temporary_files_codec, the text-index marks codec and TTL ... RECOMPRESS at merge time, instead of only validateCodecAndGetPreprocessedAST. The read paths (get(uint8_t), fillCodecDescriptions) build codecs directly through the creator and are unaffected. Regression: ChimpTest.NoColumnWriteCodecIsRejected. One correction to the reported reproducer is in the review thread: default_compression_codec = 'Chimp' already failed as Unknown codec family: CHIMP, because the string-configured settings upper-case the whole codec string (the same pre-existing quirk hides Delta, Gorilla and DoubleDelta there), so the new check is defence in depth rather than a user-visible behaviour change.
  • Required action 2 — perf evidence for the ratio/speed claim: the description now carries measured numbers instead of an unsupported claim. On 10M Float64 values (smooth sine plus 2-decimal noise, clickhouse local, single thread): NONE 76.32 MiB, Gorilla 63.35 MiB (1.20x), FPC 61.57 MiB (1.24x), Chimp 22.97 MiB (3.32x), ALP 12.80 MiB (5.96x); INSERT 0.77 s / 0.55 s / 0.52 s / 0.57 s and single-threaded SELECT sum(x) 0.31 s / 0.26 s / 0.25 s / 0.15 s respectively. So Chimp compresses ~2.8x better than Gorilla here at no cost in either direction, and it does not beat ALP — stated explicitly in the description, since whether an experimental Chimp is worth carrying next to ALP is the open product question on this pull request and a maintainer call.
  • Docs check (Run markdown linter, MD012/no-multiple-blanks): the Chimp method-byte paragraph in docs/en/interfaces/specs/NativeFormat.md left two consecutive blank lines before the Checksum section. Fixed in eafe6ab0f69.
  • The remaining reds on the previous head were the arm_release performance shards: clickbench #20 on shard 2/6 is classified unstable by the harness itself, and neither clickbench nor the shard 5/6 entries exercise a float codec, so they are noise rather than a codec regression.

Verified locally on the merged branch: ninja clickhouse unit_tests_dbms is clean, the codec unit tests pass (11327 assertions, 0 failures, including the new one), and 00950, 01222, 04320, 04402, 04489, 04510 and 04612 all match their references against the built binary.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 86.30% +0.80%
Functions 91.30% 92.00% +0.70%
Branches 77.30% 78.40% +1.10%

Changed lines: Changed C/C++ lines covered: 380/407 (93.37%) · Uncovered code

Full report · Diff report

A floating-point time series codec (`Chimp`, `Gorilla`, `FPC`, `ALP`, `SZ3`) is
resolved and applied per substream, so for `Tuple(Float64, UInt64)` the codec is
applied to the `UInt64` element as well. `innerDataTypeIsFloat` accepted a tuple
as soon as *any* element was floating-point, so such a column was created with
default settings and the `allow_suspicious_codecs` check was bypassed for the
remaining elements — contradicting the documented contract.

Require every tuple element to be floating-point instead. Homogeneous composites
(`Nullable`, `Array`, `Tuple` of `Float32`/`Float64`) are unaffected; a mixed
composite now needs `allow_suspicious_codecs`, like any other non-floating-point
type. `ATTACH` is unaffected because the sanity check is disabled there, so
existing tables keep loading.

Address AI review on ClickHouse#66467
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 3, 2026 10:09
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Update (pushed dfba5af96be..b48cf3b340c), addressing the AI Review ⚠️ Request changes verdict.

  • Merged master (the branch had fallen about a week behind). No conflicts this time; the method byte 0xa0 is still free on current master, and 01222_system_codecs.reference still lines up at 18 codecs.
  • Required action — tighten the float-only guard for composite types (b48cf3b340c). The reported case was real: innerDataTypeIsFloat returned true for a Tuple as soon as any element was floating-point, while the codec is resolved and applied per isSpecialCompressionAllowed substream, so Tuple(Float64, UInt64) CODEC(Chimp) was created with default settings and Chimp was applied to the UInt64 substream as well, bypassing allow_suspicious_codecs for that part of the column. The Tuple branch now requires every element to be floating-point. That is equivalent to the substream-wise condition, since Nullable unwraps to its nested type, Array to its element, and every other type (Map, LowCardinality, Variant, Dynamic, JSON) was and remains rejected — so the change is strictly a tightening and cannot make a currently rejected type acceptable.
  • The guard is shared by all floating-point time series codecs, so Gorilla, FPC, ALP and SZ3 are tightened together with Chimp. That is deliberate — the same documented contract applies to all of them — and it is now stated in the description. It affects CREATE/ALTER validation only; ATTACH runs with sanity_check disabled, so a table created earlier with a mixed composite still loads.
  • Docs: the Chimp paragraph in create/table.md now spells out which composite types are allowed instead of implying Float32/Float64 only.
  • Regression 04695_float_codec_mixed_composite_type: mixed Tuple(Float64, UInt64) rejected for Chimp, Gorilla and FPC, plus Array(Tuple(Float64, String)) and Tuple(Float64, Nullable(UInt32)); the all-floating-point Tuple(Float64, Nullable(Float32)) still accepted and round-tripping; and the mixed type accepted once allow_suspicious_codecs is set.
  • The remaining reds on the previous head were the arm_release performance shards. vectorize_aggregation_combinators is classified unstable by the harness itself and neither it nor the shard 5/6 entries exercise a float codec, so they are noise rather than a codec regression.

Verified locally on the merged branch: ninja clickhouse unit_tests_dbms is clean, the codec unit tests pass (11427 assertions, 0 failures), and 00950, 01222, 02538, 04320, 04402, 04489, 04510, 04612 and the new 04695 all match their references against the built binary.

The only thread still open is @scanhex12's switch/case suggestion on the encode side, which is a style question for the reviewer to close.

/// constructible for method-byte decoding and `system.codecs`, but cannot compress.
/// Reject them now, instead of persisting a codec that would only fail later during
/// a background recompression merge.
if (!result_codec->isReadyToCompress())

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.

TTL ... RECOMPRESS CODEC(Chimp(8)) still slips through this no-column path even with the default allow_suspicious_codecs = 0. An explicit width makes isReadyToCompress() true, so the new guard does not fire, and the floating-point sanity check below only runs when column_type is known.

That means a definition like

SET allow_experimental_codecs = 1;
CREATE TABLE t
(
    dt DateTime,
    s String
)
ENGINE = MergeTree ORDER BY tuple()
TTL dt + INTERVAL 1 DAY RECOMPRESS CODEC(Chimp(8));

is accepted today even though the docs and the new mixed-composite tightening both say applying a floating-point time-series codec to non-floating-point data requires allow_suspicious_codecs. TTLDescription validates RECOMPRESS with column_type = {}, MergeTreeData::getCompressionCodecForPart later uses that AST as the part default codec, and the writer only filters out structural substreams, so regular non-float streams still get Chimp(8).

Can we add an analogous no-column suspicious-codec check here for isFloatingPointTimeSeriesCodec() (or otherwise make RECOMPRESS/default write codecs require allow_suspicious_codecs for explicit-width Chimp(4|8) too), plus a negative regression for a non-float RECOMPRESS CODEC(Chimp(8)) case?

`master` moved the documentation from the Docusaurus tree under
`docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every
file this branch edits. The edits are replayed at the new paths:

- `docs/en/interfaces/specs/NativeFormat.md` -> `docs/reference/interfaces/specs/NativeFormat.mdx`
- `docs/en/sql-reference/statements/create/table.md` -> `docs/reference/statements/create/table.mdx`
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

We are in a strange situation here: Chimp is better than Gorilla, but ALP is even better. We can't remove Gorilla. We will recommend ALP instead of Gorilla. The only potential reasons to have Chimp are:

  • if its implementation is much simpler and much more elegant compared to ALP - if it represents a fundamental idea notable on its own;
  • if it is considered as a natural succession of Gorilla, and for some reason, ALP isn't, or ALP has less production quality or worse in some other regard;
  • if Chimp is popular in some systems and just its name will make someone want to use it.

If none of these is true, we will go with ALP, consider this PR as an experiment, and close it.

@alexey-milovidov

Copy link
Copy Markdown
Member

Now, I was just at the ACM SIGMOD conference where a new paper called "Kangaroo" was presented and claimed to achieve 2.2x compression ratio improvements over the second best approach (which was not ALP btw even though ALP was included in the evaluation).

Maybe we should try Kangaroo?

@alexey-milovidov

Copy link
Copy Markdown
Member

To clarify the three points with data:

1. Simplicity and elegance. In this repository, CompressionCodecChimp.cpp is 613 lines vs. 1547 lines of CompressionCodecALP.cpp — essentially Gorilla-sized (495 lines). But conceptually Chimp is a refinement of Gorilla's XOR scheme rather than a fundamental idea of its own: it keeps a ring buffer of the last sizeof(T) * 16 values (128 for Float64) to pick a better XOR reference, and spends a 2-bit flag per value to encode the leading/trailing zeros more compactly. The fundamental idea — XOR against a previous value — is Gorilla's. ALP's extra lines buy a genuinely different algorithm: two variants (standard ALP for decimal-like data, ALP RD for "real doubles") with automatic per-block selection.

2. Natural succession of Gorilla / production quality of ALP. Chimp is the natural successor within the XOR family: same interface, same parameters, a drop-in replacement for Gorilla (this PR implements the stronger "Chimp128" variant from the paper). ALP belongs to a different lineage (scaled-integer frame-of-reference encoding). However, there is no production-quality argument against ALP: our implementation covers both ALP variants with automatic selection, both codecs are equally experimental at the moment (behind allow_experimental_codecs), and the measurements in this PR's description show ALP dominating Chimp in both compression ratio and speed.

3. Popularity. The main adoption story is a precedent for exactly this decision: DuckDB added Chimp (Chimp128, duckdb#4878) in v0.6.0 (2022) and the Chimp-derived Patas (duckdb#5044) in v0.7.0, then replaced both with ALP (duckdb#9635) in v0.10.0 (Feb 2024) — the announcement states "The new compression scheme replaces Chimp and Patas", with about 2x better compression ratios and 2-4x faster decompression. Apache IoTDB still ships CHIMP as a first-class encoding. The InfluxDB integration described in the paper is the authors' experimental extension, not upstream InfluxDB.

So of the three conditions, only "natural successor of Gorilla" holds cleanly — and the one system that carried both codecs (DuckDB) faced this exact question and resolved it in ALP's favor.

@alexey-milovidov

Copy link
Copy Markdown
Member

Follow-up: newer codecs in this family — Elf, Camel, Kangaroo.

Since Chimp (VLDB 2022), the XOR family has kept evolving:

  • Elf (VLDB 2023) adds an erasing preprocessing step (zeroing mantissa bits that are recoverable from the decimal precision) so the XOR residues have more trailing zeros; it reports about 12.4% better ratio than Chimp128 on Float64.
  • Camel (SIGMOD 2025) compresses the integer and decimal parts separately and also searches for better XOR references than the immediate predecessor.
  • Kangaroo (SIGMOD 2026, Northeastern University + Alibaba Group, published 2026-05-18) generalizes the Chimp idea further: dynamic reference selection over an extended history window (skipping unpromising candidates) plus a bit-flip erasure strategy to maximize trailing zeros. Across 26 datasets it claims a 23.2% average compression-ratio improvement and roughly 2x compression/decompression speed over the state-of-the-art streaming algorithms. I could not find a public implementation yet.

Two observations relevant to this PR:

  1. All of these compete in the streaming setting (value-at-a-time, each value XOR-chained to history), which is where the family's design makes sense. ClickHouse compresses whole blocks, which is exactly the block-based setting ALP targets. An independent re-implementation study of all these methods in one framework — "Beyond Compression: A Comprehensive Evaluation of Lossless Floating-Point Compression" (PVLDB 18(11), 2025) — found the best compression ratios to be Gzip, Zstd, ALP, Elf in that order, with ALP also achieving the highest compression and decompression throughput; it concludes that "from the perspective of compression performance, ALP is the best choice when SIMD instructions are enabled", while the XOR family "exhibit[s] very low throughput" because every value depends on the previous one.

  2. Within its own family, Chimp is no longer the state of the art — it has been superseded three times in four years (Elf 2023 → Camel 2025 → Kangaroo 2026). So if the motivation to merge were "carry the best XOR-family codec next to ALP", Chimp is not that codec, and the target keeps moving. That argues for treating the family as a research lineage to watch rather than merging its members one by one, and recommending ALP meanwhile. If one of the successors stabilizes with real adoption and a production-quality reference implementation (Kangaroo comes partly from Alibaba, so it may surface in their systems), it can be reconsidered on its own merits.

@alexey-milovidov

Copy link
Copy Markdown
Member

found the best compression ratios to be Gzip, Zstd, ALP, Elf in that order

What a strange paper! Sounds very wrong.

@alexey-milovidov alexey-milovidov self-assigned this Aug 5, 2026
@alexey-milovidov

alexey-milovidov commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

@panagiotisl, this is a good reference implementation, and it can serve as an example for adding new codecs. Thank you!

This PR will be closed because we have two other things in the pipeline:

  • make ALP production-ready;
  • merge PCodec.

alexey-milovidov pushed a commit that referenced this pull request Aug 5, 2026
Three changes to the XOR encoding after benchmarking against `ALP`,
`Gorilla`, `FPC` and the `Chimp` proposal from #66467:

- A per-vector flag omits the trailing-zero field when sampled XOR
  residues have almost no trailing zeros (typical for full-precision
  doubles), where the field was pure overhead.
- The encoder replaces the full ring scan with two O(1) probes (the
  predecessor and a high-bits hash table) and bails out to the RAW
  mode early on incompressible data; compression of incompressible
  data got 10x faster and now matches `NONE`.
- The reference ring grows from 32 to 64 values with a 6-bit index,
  which covers longer periodicity in the data.

Co-Authored-By: Claude Fable 5 <[email protected]>
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Aug 11, 2026
`RowPolicyFilter::expression` is the parsed policy condition owned by
`RowPolicyCache`. It is parsed once, in
`RowPolicyCache::PolicyInfo::setPolicy`, and then handed out as is: every query
of every user reading the table gets the same AST nodes, and a policy defined on
a whole database is shared by all of its tables. `FiltersMixer` combines the
parsed conditions without copying them, so the pointer a query receives points
straight into the cache.

`ReadFromMerge::RowPolicyData` passed that AST to `TreeRewriter` and
`ExpressionAnalyzer`, both of which rewrite the AST they are given in place:
they normalize identifiers, substitute the results of scalar subqueries for the
subqueries themselves, and record `ASTLiteral::unique_column_name`. So reading a
`Merge` table mutated the cache. Two consequences:

- A scalar subquery in a policy was evaluated once and then frozen. With
  `CREATE ROW POLICY p ON src USING x <= (SELECT max(v) FROM limits)`, one
  `SELECT` through a `Merge` table over `src` replaced the subquery with its
  value in the cached AST, and every later query - including direct reads of
  `src` by other users - kept using that value for the rest of the server's
  lifetime.

- Concurrent queries raced on the shared AST. ThreadSanitizer reported the
  write to `ASTLiteral::unique_column_name` from `ActionsMatcher::visit`
  against a concurrent `ASTLiteral::clone` performed by `buildQueryTree` for
  another table protected by the same policy:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=66467&sha=b48cf3b340cdcc0e2275b3c1a5a4ba34034deb4d&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
  ClickHouse#66467

Analyze a clone instead. `generateFilterActions` in `InterpreterSelectQuery`
already clones the policy expression for the same reason, as does
`MergeTreeDataSelectExecutor::getSampling` for the sampling key, and
`ASTLiteral::clone` resets `unique_column_name` precisely because it is
per-analysis scratch state. This was the last consumer of a row policy filter
that rewrote the cached AST: the other ones either clone (the analyzer, through
`buildQueryTree`), only visit it with a const visitor
(`StorageMergeTreeTextIndex`), or only test `isAlwaysTrue`.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants