Skip to content

Optimize postings list compression with simdcomp - #92871

Merged
Ergus merged 61 commits into
ClickHouse:masterfrom
fastio:compressed-postings-list
Jan 22, 2026
Merged

Ergus merged 61 commits into
ClickHouse:masterfrom
fastio:compressed-postings-list

Conversation

@fastio

@fastio fastio commented Dec 23, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Optimize postings list compression with simdcomp.

Documentation entry for user-facing changes

This PR introduces SIMD-accelerated compression for postings lists using
[simdcomp] on x86_64 and StreamVByte as a generic fallback.

Depending on the available SIMD ISA, postings are compressed in fixed-size
blocks with simdcomp, and the remaining tail is encoded with StreamVByte.

By using SIMD-friendly integer compression, we can reduce the storage
footprint and improve scan performance for inverted indexes, especially
for large postings lists.

https://github.com/fast-pack/simdcomp

This is a re-implementation of this PR #89612. With the release of Inverted Index V3, it needs to be reworked accordingly.

How to use ?

Added a parameter enable_postings_compression when creating the index.

REATE TABLE default.logs
(
    `_ts` DateTime,
    `_content` String CODEC(ZSTD(5)),
    INDEX inv_idx _content TYPE text(tokenizer = 'splitByNonAlpha', enable_posting_list_compression = true) GRANULARITY 128
)
ENGINE = MergeTree
PARTITION BY toDate(_ts)
ORDER BY _ts
SETTINGS index_granularity = 8192

A Simple Test

Here is my testing procedure:

    1. I created two tables, one with postings compression enabled and one disabled: logs_compressed_1b and logs_uncompressed_1b.
    1. I inserted the exact same 200,000,000 log rows into both tables.
    1. After the inserts completed, I ran OPTIMIZE TABLE FINAL once for each table.
      1. I then executed several text search queries.
      1. Finally, I collected key metrics from system.parts, system.query_log, and system.part_log to compare disk footprint, insert performance, query performance, and merge behavior between the two setups.
    2. Inverted Index Data Size / Raw Data Size

      In both scenarios—with posting list compression enabled and disabled—we insert the same 200,000,000 log rows into the test table. We then compute the ratio between the inverted index data size and the raw log data size (excluding the inverted index data).

      WITH
          sum(bytes_on_disk) AS total,
          sum(secondary_indices_compressed_bytes) AS index_total
      SELECT
          database,
          `table`,
          count() AS parts,
          sum(rows) AS `rows-count`,
          formatReadableSize(total) AS `total-bytes`,
          formatReadableSize(index_total) AS `text-index-bytes`,
          formatReadableSize(total - index_total) AS `data-bytes-excludes-text-index`,
          index_total / (total - index_total) AS `text-index-bytes/data-bytes`
      FROM system.parts
      WHERE active AND (database = 'default')
      GROUP BY
          database,
          `table`
      
      Query id: 6ca8b504-3f9e-4e26-9655-fcb98504aa08
      
         ┌─database─┬─table────────────────┬─parts─┬─rows-count─┬─total-bytes─┬─text-index-bytes─┬─data-bytes-e⋯-text-index─┬─text-index-bytes/data-bytes─┐
      1. │ default  │ logs_uncompressed_1b │     4 │  200000000 │ 21.17 GiB   │ 14.66 GiB        │ 6.51 GiB                 │           2.251726149635651 │
      2. │ default  │ logs_compressed_1b   │     5 │  200000000 │ 11.20 GiB   │ 4.69 GiB         │ 6.51 GiB                 │          0.7208855409030969 │
         └──────────┴──────────────────────┴───────┴────────────┴─────────────┴──────────────────┴──────────────────────────┴─────────────────────────────┘
      

      Based on the measured data, enabling postings compression reduces the inverted text index size from 14.66 GiB to 4.69 GiB (about 68% reduction, ≈ 3.1× compression ratio), while keeping the raw data size unchanged.
      As a result, the ratio of text index size to raw data size drops from 2.25× to 0.72×, and the total on-disk footprint is reduced by approximately 47%.

      Merge

      SELECT
          `table`,
          sum(duration_ms),
          sum(RealTimeMicroseconds),
          sum(UserTimeMicroseconds),
          sum(SystemTimeMicroseconds),
          sum(MergeHorizontalStageExecuteMilliseconds),
          sum(MergeTextIndexStageExecuteMilliseconds),
          formatReadableSize(sum(read_bytes)),
          formatReadableSize(sum(peak_memory_usage))
      FROM
      (
          SELECT
              `table`,
              duration_ms,
              read_bytes,
              peak_memory_usage,
              ProfileEvents['RealTimeMicroseconds'] AS RealTimeMicroseconds,
              ProfileEvents['UserTimeMicroseconds'] AS UserTimeMicroseconds,
              ProfileEvents['SystemTimeMicroseconds'] AS SystemTimeMicroseconds,
              ProfileEvents['MergeHorizontalStageExecuteMilliseconds'] AS MergeHorizontalStageExecuteMilliseconds,
              ProfileEvents['MergeTextIndexStageExecuteMilliseconds'] AS MergeTextIndexStageExecuteMilliseconds
          FROM system.part_log
          WHERE (database = 'default') AND (event_type = 'MergeParts')
      )
      GROUP BY `table`
      
      Query id: 8b0b25da-3f2a-4a46-9fef-9ad35f9a4766
      
         ┌─table────────────────┬─sum(duration_ms)─┬─sum(RealTimeMicroseconds)─┬─sum(UserTimeMicroseconds)─┬─sum(SystemTimeMicroseconds)─┬─sum(MergeHor⋯lliseconds)─┬─sum(MergeTex⋯lliseconds)─┬─formatReadab⋯ead_bytes))─┬─formatReadab⋯ory_usage))─┐
      1. │ logs_compressed_1b   │          2290729 │                2288807597 │                2273810829 │                    15183744 │                   609275 │                  1678479 │ 47.14 GiB                │ 1.58 GiB                 │
      2. │ logs_uncompressed_1b │          2241323 │                2239398473 │                2212336458 │                    24687655 │                   634020 │                  1604294 │ 48.96 GiB                │ 1.61 GiB                 │
         └──────────────────────┴──────────────────┴───────────────────────────┴───────────────────────────┴─────────────────────────────┴──────────────────────────┴──────────────────────────┴──────────────────────────┴──────────────────────────┘
      
      2 rows in set. Elapsed: 0.013 sec. Processed 15.01 thousand rows, 2.25 MB (1.15 million rows/s., 172.51 MB/s.)
      

      Based on the test result, enabling postings compression reduces the amount of data read during merges by about 3.7% and slightly lowers peak memory usage.
      While the TextIndex merge stage becomes moderately more expensive (around 4–5%), the overall merge time increases by only about 2%, with CPU usage remaining stable and no noticeable memory regression.

      Insert

      SELECT
          `table`,
          sum(query_duration_ms),
          sum(RealTimeMicroseconds),
          sum(UserTimeMicroseconds),
          sum(SystemTimeMicroseconds),
          sum(WriterSkipIndicesCalculationMicroseconds) AS WriterSkipIndicesCalculationMicroseconds,
          formatReadableSize(sum(OSWriteBytes)) AS OSWriteBytes,
          formatReadableSize(sum(InsertedBytes)) AS InsertedBytes
      FROM
      (
          SELECT
              tables[1] AS `table`,
              query_duration_ms,
              ProfileEvents['RealTimeMicroseconds'] AS RealTimeMicroseconds,
              ProfileEvents['UserTimeMicroseconds'] AS UserTimeMicroseconds,
              ProfileEvents['SystemTimeMicroseconds'] AS SystemTimeMicroseconds,
              ProfileEvents['MergeTreeDataWriterSkipIndicesCalculationMicroseconds'] AS WriterSkipIndicesCalculationMicroseconds,
              ProfileEvents['OSWriteBytes'] AS OSWriteBytes,
              ProfileEvents['InsertedBytes'] AS InsertedBytes
          FROM system.query_log
          WHERE has(databases, 'default') AND (query_kind = 'Insert') AND (type = 'QueryFinish')
      )
      GROUP BY `table`
      
      Query id: 7bcf1f93-0796-4460-b1d6-923d36eee61f
      
         ┌─table────────────────────────┬─sum(query_duration_ms)─┬─sum(RealTimeMicroseconds)─┬─sum(UserTimeMicroseconds)─┬─sum(SystemTimeMicroseconds)─┬─WriterSkipIndicesCalculationMicroseconds─┬─OSWriteBytes─┬─InsertedBytes─┐
      1. │ default.logs_uncompressed_1b │                1574460 │               30957768151 │                1361109264 │                    59879637 │                                690661469 │ 16.89 GiB    │ 16.75 GiB     │
      2. │ default.logs_compressed_1b   │                1608469 │               32704244385 │                1393081284 │                    60757311 │                                691504901 │ 16.49 GiB    │ 16.75 GiB     │
         └──────────────────────────────┴────────────────────────┴───────────────────────────┴───────────────────────────┴─────────────────────────────┴──────────────────────────────────────────┴──────────────┴───────────────┘
      
      2 rows in set. Elapsed: 0.010 sec. Processed 1.19 thousand rows, 323.80 KB (118.39 thousand rows/s., 32.24 MB/s.)
      

      According to the test result, when inserting the same dataset, enabling postings compression introduces only a marginal overhead on INSERT performance (about 2–5% in wall time), while CPU usage and skip index construction costs remain almost unchanged.
      At the same time, the total amount of data written to disk is reduced by approximately 2.4%, indicating lower write amplification even during the INSERT phase.

      Query

      SELECT count()
      FROM logs_compressed_1b
      WHERE hasAnyTokens(_content, ['T205938', 'T123456', 'not_exists'])
      
      Query id: 096aef81-ef48-4727-8d5a-52c2b89192b6
      
         ┌─count()─┐
      1. │    3991 │
         └─────────┘
      
      1 row in set. Elapsed: 0.014 sec. Processed 199.68 million rows, 199.68 MB (14.14 billion rows/s., 14.14 GB/s.)
      Peak memory usage: 1.87 MiB.
      
      localhost.localdomain :) select count() from logs_uncompressed_1b where hasAnyTokens(_content, ['T205938','T123456','not_exists'])
      
      SELECT count()
      FROM logs_uncompressed_1b
      WHERE hasAnyTokens(_content, ['T205938', 'T123456', 'not_exists'])
      
      Query id: 246798b8-06a3-41c3-b847-175889a524c6
      
         ┌─count()─┐
      1. │    3991 │
         └─────────┘
      
      1 row in set. Elapsed: 0.012 sec. Processed 30.06 million rows, 30.06 MB (2.55 billion rows/s., 2.55 GB/s.)
      

      After enabling compression, the impact on query performance is not significant.

      Version info

      • Merged into: 26.1.1.770

@fastio
fastio marked this pull request as draft December 23, 2025 08:33
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Dec 23, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 23, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d4d694]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) failure
02844_max_backup_bandwidth_s3 FAIL cidb
BuzzHouse (amd_debug) failure
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-1bfa) FAIL cidb, issue

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR. labels Dec 23, 2025
@fastio
fastio marked this pull request as ready for review December 24, 2025 12:46
@fastio
fastio marked this pull request as draft December 26, 2025 01:58
@fastio fastio closed this Dec 29, 2025
@fastio
fastio force-pushed the compressed-postings-list branch from 6878913 to 7c029d1 Compare December 29, 2025 08:11
@fastio fastio reopened this Dec 29, 2025
@fastio
fastio marked this pull request as ready for review December 29, 2025 11:29
@fastio

This comment was marked as resolved.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Dec 29, 2025
Ergus

This comment was marked as resolved.

@rschu1ze

This comment was marked as resolved.

@rschu1ze

This comment was marked as resolved.

@@ -145,6 +146,8 @@ struct PostingsSerialization
EmbeddedPostings = 1ULL << 1,
/// If unset, the number of blocks is stored as an additional VarUInt.
SingleBlock = 1ULL << 2,
/// If set, the posting lists are encoded and stored in a compressed format on disk.
CompressedPostings = 1ULL << 3,

This comment was marked as resolved.

@fastio

This comment was marked as resolved.

@rschu1ze

This comment was marked as resolved.

@amosbird amosbird mentioned this pull request Dec 30, 2025
1 task done
@fastio

This comment was marked as resolved.

@fastio
fastio force-pushed the compressed-postings-list branch from f0c9adf to be6266d Compare December 31, 2025 06:55
@Ergus

Ergus commented Jan 16, 2026

Copy link
Copy Markdown
Member

Hi @fastio

I have seen your latest changes and I am wondering why did you moved the tests to integration. If the problems is the randomization we solve that by assigning a setting value in the beginning of the test. But moving the test to integration adds a level of complexity that we don't want in this case.

If we don't know where is the real problem yet, then moving the test to integration is not a solution, but a way to hide the problem.

@fastio

fastio commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @fastio

I have seen your latest changes and I am wondering why did you moved the tests to integration. If the problems is the randomization we solve that by assigning a setting value in the beginning of the test. But moving the test to integration adds a level of complexity that we don't want in this case.

If we don't know where is the real problem yet, then moving the test to integration is not a solution, but a way to hide the problem.

Hi @Ergus,

I’m very sorry about this. I understand your concern, and I fully agree with your point.

The query I moved to the integration tests (it queries system tables to compute the data size) is not the one that triggers the index file issue. However, if we keep it in place, the randomized settings frequently cause the data size validation SQL to fail. That said, you are absolutely right that moving it away could potentially mask the real problem.

To address this properly, I split the original test into two parts:

  1. A dedicated data size validation part, where we disable the randomized settings via test tags.
  2. The original query part, where we keep randomized settings enabled and additionally include the MergeTreeSettings that were involved in yesterday’s issue.

@Ergus

Ergus commented Jan 19, 2026

Copy link
Copy Markdown
Member

Hi @fastio

I’m very sorry about this. I understand your concern, and I fully agree with your point.

Not need to apologize at all!! ;)

However, if we keep it in place, the randomized settings frequently cause the data size validation SQL to fail. That said, you are absolutely right that moving it away could potentially mask the real problem.

If randomization is an issue, the least we can do is to investigate which settings cause the issue. Then, hardcode their values in the test header preferably with a comment about why the value was chosen.

The best approach for tests is always KISS. And integration tests are intended to be used for end-to-end tests that cannot be expressed with a single .sql. They use an infrastructure much harder to use for debugging and reproduce locally.

@fastio

fastio commented Jan 19, 2026

Copy link
Copy Markdown
Contributor Author

If randomization is an issue, the least we can do is to investigate which settings cause the issue. Then, hardcode their values in the test header preferably with a comment about why the value was chosen.

The best approach for tests is always KISS. And integration tests are intended to be used for end-to-end tests that cannot be expressed with a single .sql. They use an infrastructure much harder to use for debugging and reproduce locally.

Hi @Ergus ,

Thank you for the feedback, it's very helpful.

This PR currently has two issues:

    1. Index mark file error in query path - I've identified the root cause and submitted a separate PR to fix it. Fix text index mrk file incompatibility #94494
    1. Data size validation affected by random settings - As you suggested, I can hardcode the relevant settings in the test header with comments explaining the rationale.

I'm currently adjusting the test cases for this PR. I'll request your review again once the changes are ready.

@Ergus

This comment was marked as resolved.

@fastio

This comment was marked as resolved.

@Ergus

Ergus commented Jan 21, 2026

Copy link
Copy Markdown
Member

Hi @fastio

I still see the data size mismatch issue failing in fastest. I thought this was already fixed

@fastio

fastio commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @fastio

I still see the data size mismatch issue failing in fastest. I thought this was already fixed

Hi @Ergus,

Thanks for the feedback. I looked into the fast test failure this time, and it was caused by the latest change (2f558ce) switching the table name from table to 'table', which made the generated SQL output differ from the reference. The main issue is that the table name doesn’t match, not that the data size is mismatched.

We just need a small fix to align the table name — I can take care of it.

@fastio
fastio force-pushed the compressed-postings-list branch from 00ef573 to 2f558ce Compare January 22, 2026 02:47
@Ergus
Ergus added this pull request to the merge queue Jan 22, 2026
@Ergus

Ergus commented Jan 22, 2026

Copy link
Copy Markdown
Member

Thank you very much @fastio !! hoping to help with your next contribution very soon!!!

Merged via the queue into ClickHouse:master with commit e3fb348 Jan 22, 2026
126 of 128 checks passed
@fastio

fastio commented Jan 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you very much @fastio !! hoping to help with your next contribution very soon!!!

Hi @Ergus , Thanks a lot! Really appreciate your help.

I’m almost ready with the next PR, which should significantly improve query performance for compressed posting lists.

And thanks as well to @rschu1ze for the help.

@rschu1ze

Copy link
Copy Markdown
Member

I'm just a random peasant reviewing PRs as I hapen to see them :-)

@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jan 23, 2026
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 manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants