Skip to content

add T64('byte_mask') codec variant - PEXT/PDEP bitpack - #94499

Open
4ertus2 wants to merge 4 commits into
ClickHouse:masterfrom
4ertus2:t64_mask
Open

4ertus2 wants to merge 4 commits into
ClickHouse:masterfrom
4ertus2:t64_mask

Conversation

@4ertus2

@4ertus2 4ertus2 commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a [user-readable short description]

add T64('byte_mask') and T64('bit_mask') codec variants

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

T64 crops most significant bits of value by min and max values in array. But it's possible to calculate always-ones and always-zeroes bitmasks to crop equal bits in any part of values. It could be done fast using PEXT/PDEP x86 instructions.

bit_compress()/bit_expand() operations that use such instructions are in proposal for C++ standard. Related part of PR was copy-pasted from this proposal and could be replaced when the bit_compress()/bit_expand() appear in stdlib.

T64 itself is interested in context of "fast row-access and GPU-friendly compression" in context of Parquet replacement hype and Parquet answer It's possible to get a "row position" inside compressed data and decompress values in parallel using only a small "header".


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

@4ertus2 4ertus2 changed the title T64 mask add T64('byte_mask') codec variant - PEXT/PDEP bitpack Jan 17, 2026
@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label Jan 17, 2026
@4ertus2

4ertus2 commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor Author

My expectation was it should make beter compression ratio for Decimals. They are multiplyed by powers of 10 and should have trailing zeroes in least-significant bits.

I didn't test it much. But it seems there's a win using it without LZ4/ZSTD. And there's no win after LZ4/ZSTD. It's just a bit more stable than default T64 in combination with future LZ4. Also I found it useful for values multiplied by exp2(N). In this case T64('byte_mask') beats T64('byte') variant regardless of future compression.

@clickhouse-gh

clickhouse-gh Bot commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [76c0520]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: Can't determine table for parallel replicas (STID: 3634-41e5) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/pr_body_check.py FAIL

AI Review

Summary

This PR adds T64('byte_mask') and T64('bit_mask') by storing a new mask-based T64 subformat inside the existing 0x93 codec family. I do not think it is ready to merge yet: the new encoding has no safe mixed-version rollout story, and the PR still lacks focused coverage proving the new persistent layout and its claimed benefit.

Findings

❌ Blockers

  • [src/Compression/CompressionCodecT64.cpp:1111-1153] byte_mask / bit_mask reuse the stable T64 family byte but change the inner cookie from type_id[0..6] + variant[7] to type_id[0..5] + mask[6] + bit[7]. Older servers still decode 0x93 blocks as variant = cookie >> 7 and type = cookie & 0x7f, so a block written as T64('byte_mask') for UInt64 becomes type id 0x44 and is rejected as bad T64 data. Because these spellings are accepted unconditionally, a mixed-version cluster or downgrade can produce unreadable parts as soon as a table starts using the new variant.
    Suggested fix: keep the new encoding behind a disabled-by-default compatibility / experimental gate, or version it under a new codec family byte so old binaries never accept the frame as plain T64.
Tests
  • ⚠️ Add focused stateless coverage for T64('byte_mask') and T64('bit_mask') analogous to 00872_t64_bit_codec.sql and 04278_codec_t64_estimate_compression_ratio.sql: round-trip read/write, mixed signed values, and estimateCompressionRatio / tryGetCompressedSize agreement with on-disk bytes.
  • ⚠️ Add a small benchmark or measured example on the decimal / trailing-zero workloads from the PR description. pr-performance was skipped, so there is currently no evidence that either new variant improves size or speed over existing T64 / T64('bit').
Final Verdict

Not ready.

LLVM Coverage Report

Measured on commit 76c0520.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 137/240 (57.08%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jan 17, 2026
@nikitamikhaylov nikitamikhaylov added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Jan 20, 2026
@4ertus2

4ertus2 commented Jan 21, 2026

Copy link
Copy Markdown
Contributor Author

Should I do anything with flaky tests? Tests fails are not related to my changes.

@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@4ertus2

4ertus2 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@copilot resolve the merge conflicts in this pull request

Nothing changes.

nickitat and others added 3 commits September 3, 2026 12:17
Conflict in `src/Compression/CompressionCodecT64.cpp`: master reworked
compression around a precomputed `T64Layout` (used by the new
`tryGetCompressedSize` / `CompressedSizeCalculator`), added decompression
bounds checks and introduced the `COOKIE_SIZE` / `MATRIX_SIZE` /
`HEADER_SIZE` constants, while this branch added the `bit_mask` and
`byte_mask` variants.

Resolution:
- `computeT64Layout` gained a `with_mask` template parameter and a
  `header_size` field, so the layout describes both the min/max header
  (`HEADER_SIZE`) and the mask header (`4 * sizeof(T)`). The mask path
  computes `valuable_bits` via `findMasks` and `getMaskBitsNumber`.
- `compressData` and `decompressData` keep master's layout-driven shape
  and constants, with the `pext` / `pdep` steps and the mask header
  read/write under `if constexpr (with_mask)`.
- `calculateCompressedDataSize` now takes the variant, so
  `tryGetCompressedSize` is exact for the mask variants too.
- Master's "compressed size too small for the header" check now uses
  `header_size`, so it also covers the mask header.
- Restored the mask bit of the cookie in `doCompressData`, which the
  automatic merge had attached to master's new `tryGetCompressedSize`.
- `min` / `max` in `decompressData` are now initialized, since the
  `num_bits == 0` path reads `min` through a runtime ternary shared with
  the mask path.
- Updated the on-disk layout comment for the two extra cookie bits and
  the mask header, and dropped a duplicated include block.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pj9RDkQHKvbZ9UkWNgBwiN
Fast test failed to build after the merge with master:

    src/Compression/CompressionCodecT64.cpp:69:5: error: code will never be executed [-Werror,-Wunreachable-code]
    src/Compression/CompressionCodecT64.cpp:102:25: error: code will never be executed [-Werror,-Wunreachable-code]

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=94499&sha=0d5b3700919aaae774bcdc411f473b0a5c7ee8f4&name_0=PR&name_1=Fast+test

Master changed the default x86 build target from `x86-64-v2` to
`x86-64-v3`, which defines `__BMI2__`. `bitCompress64` and `bitExpand64`
returned early from an `#ifdef __BMI2__` block and then fell through to
the portable implementation, so that implementation became unreachable.

Turned the three implementations into one `#if` / `#elif` / `#else`
chain, and moved the declarations they need inside the `#else`. With
`__BMI2__` defined, `log2Floor` and `bitwiseInclusiveRightParity64` are
then used by nobody, so they are compiled only when the portable path is.

Checked that the file compiles with `-Weverything -Werror` at
`x86-64-v2`, `x86-64-v3` and `x86-64-v4`, and on `aarch64` both with and
without `sve2`. Also checked that `_pext_u64` / `_pdep_u64` and the
portable fallback agree on 3M random `(x, mask)` pairs, so the switch to
`x86-64-v3` does not change what the codec writes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pj9RDkQHKvbZ9UkWNgBwiN
`Build (arm_tidy)` fails with 11 `google-runtime-int` errors, all in
`src/Compression/CompressionCodecT64.cpp`:

    error: consider replacing 'unsigned long long' with 'uint64' [google-runtime-int,-warnings-as-errors]

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=94499&sha=f9ca9c7a6364d64cf08f2ec2d6120241142926b6&name_0=PR&name_1=Build+%28arm_tidy%29

`log2Floor`, `bitwiseInclusiveRightParity64`, `bitCompress64` and
`bitExpand64` were copied from the reference implementation, which spells
the type `unsigned long long`. Switched them to `UInt64`, which is what
the rest of the file uses, and dropped the local `using T` aliases that
only existed to shorten the name.

Checked with `clang-tidy` and the repository's `.clang-tidy`: 11 errors
before, none after. The file still compiles with `-Weverything -Werror`
at `x86-64-v2`, `x86-64-v3` and `x86-64-v4`, and on `aarch64` both with
and without `sve2`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pj9RDkQHKvbZ9UkWNgBwiN
@nickitat nickitat self-assigned this Sep 3, 2026
UInt8 cookie = static_cast<UInt8>(serializeTypeId(type_idx)) | static_cast<UInt8>(static_cast<UInt8>(variant) << 7);
UInt8 bit_flag = static_cast<UInt8>(static_cast<UInt8>(variant) << 7);
UInt8 mask_flag = static_cast<UInt8>((static_cast<UInt8>(variant) & 0x2) << 5);
UInt8 cookie = static_cast<UInt8>(serializeTypeId(type_idx)) | bit_flag | mask_flag;

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.

The new mask variants change the T64 on-disk cookie layout without changing the outer 0x93 family byte. Older servers still interpret T64 cookies as variant = cookie >> 7 and type = cookie & 0x7f, so a block written as T64('byte_mask') for UInt64 is seen as type id 0x44 and rejected as bad T64 data. Because these spellings are accepted unconditionally, a mixed-version cluster or downgrade can start producing unreadable parts as soon as a table uses the new variant.

Please give the new encoding a disabled-by-default rollout mechanism, or version it under a new codec family byte instead of silently extending stable T64.

variant = Variant::Byte;
else if (name == "bit")
variant = Variant::Bit;
else if (name == "byte_mask")

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.

This is the user-visible entrypoint for the new spellings, but the PR still ships no focused coverage or measurements for them. The existing T64 tests only cover plain T64 and T64('bit'), so we never exercise round-trip correctness, mixed-sign data, or estimateCompressionRatio / tryGetCompressedSize on the new mask header.

For a persistent codec change, please add at least a stateless round-trip test for both byte_mask and bit_mask plus an estimateCompressionRatio case proving the predicted bytes match what is written. pr-performance was also skipped, so a small before/after measurement on the decimal / trailing-zero workloads from the PR description is still missing.

@nickitat

nickitat commented Sep 3, 2026

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

Nothing changes.

Did manually, pls check the code.
Pls add some tests.
Also, how will we judge this PR - any perf tests, compression ratio comparisons?

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 76c0520b2 with master fb0b23675 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+71.93 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_compression.dir/Compression/CompressionCodecT64.cpp.o 196.84 KiB 268.68 KiB +71.84 KiB (+36.50%)

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

Compile time of recompiled translation units

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::CompressionCodecT64::doDecompressData(char const*, unsigned int, char*, unsigned int) const 47.50 KiB 116.37 KiB +68.87 KiB (+144.99%)
programs/clickhouse-keeper DB::CompressionCodecT64::doDecompressData(char const*, unsigned int, char*, unsigned int) const 47.50 KiB 116.37 KiB +68.87 KiB (+144.99%)

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
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... external Author is not a member of the ClickHouse organization pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants