Skip to content

Optimize postings list compression with simdcomp - #89612

Closed
fastio wants to merge 42 commits into
ClickHouse:masterfrom
fastio:postings-list
Closed

fastio wants to merge 42 commits into
ClickHouse:masterfrom
fastio:postings-list

Conversation

@fastio

@fastio fastio commented Nov 6, 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

  • Documentation is written (mandatory for new features)

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

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_postings_compression = true) GRANULARITY 128
)
ENGINE = MergeTree
PARTITION BY toDate(_ts)
ORDER BY _ts
SETTINGS index_granularity = 8192

A Simple Test

In the same ClickHouse process, I inserted 12,400,000 rows into two tables (logs_compressed and logs_uncompressed). Then I used the system.parts table to measure the size of the inverted index for each table, as well as its proportion relative to the total data size.

  • Insert data into the table where the text index has postings compression enabled
INSERT INTO logs_compressed SELECT
    now(),
    multiIf((number % 3) = 0, 'aa', (number % 13) = 0, 'aa', (number % 11) = 0, 'bb', (number % 23) = 0, 'cc', 'dd')
FROM numbers(102400000)

Query id: 75da5abd-8109-4eab-8d07-43fc69eaa52d

Ok.

102400000 rows in set. Elapsed: 11.231 sec. Processed 102.40 million rows, 819.20 MB (9.12 million rows/s., 72.94 MB/s.)
Peak memory usage: 43.69 MiB.
  • Insert data into the table where the text index has postings compression disabled.
INSERT INTO logs_uncompressed SELECT
    now(),
    multiIf((number % 3) = 0, 'aa', (number % 13) = 0, 'aa', (number % 11) = 0, 'bb', (number % 23) = 0, 'cc', 'dd')
FROM numbers(102400000)

Query id: 2e5f7f87-92fc-4c21-9b07-fe5a40008f42

Ok.

102400000 rows in set. Elapsed: 11.552 sec. Processed 102.40 million rows, 819.20 MB (8.86 million rows/s., 70.91 MB/s.)
Peak memory usage: 43.69 MiB.
  • Check the size of the index data.
SELECT
    database,
    `table`,
    sum(bytes_on_disk) AS total,
    sum(secondary_indices_compressed_bytes) AS index_total,
    sum(rows) AS count,
    formatReadableSize(total) AS bytes,
    formatReadableSize(index_total) AS index_bytes,
    formatReadableSize(total - index_total) AS data_bytes,
    index_total / total AS ratio
FROM system.parts
WHERE active AND (database = 'default')
GROUP BY
    database,
    `table`

Query id: 91259d2b-61db-489e-953f-1950581f6ed9

   ┌─database─┬─table─────────────┬────total─┬─index_total─┬─────count─┬─bytes─────┬─index_bytes─┬─data_bytes─┬────────────────ratio─┐
1. │ default  │ logs_uncompressed │ 40933122 │    17556363 │ 102400000 │ 39.04 MiB │ 16.74 MiB   │ 22.29 MiB  │  0.42890359059345634 │
2. │ default  │ logs_compressed   │ 23529012 │      152304 │ 102400000 │ 22.44 MiB │ 148.73 KiB  │ 22.29 MiB  │ 0.006473029976779306 │
   └──────────┴───────────────────┴──────────┴─────────────┴───────────┴───────────┴─────────────┴────────────┴──────────────────────┘

2 rows in set. Elapsed: 0.005 sec.

In this simple test scenario, enabling postings compression for the inverted index significantly reduced the index disk footprint — by more than two orders of magnitude (over a 100× reduction).

A More Complex Test

Now I’ve done a more complex one. I inserted 10B rows of random, log-like data into each of the two tables, and then measured how much disk space the inverted index occupies in each table.

ELECT
    database,
    `table`,
    sum(bytes_on_disk) AS total,
    sum(secondary_indices_compressed_bytes) AS index_total,
    sum(rows) AS count,
    formatReadableSize(total) AS bytes,
    formatReadableSize(index_total) AS index_bytes,
    formatReadableSize(total - index_total) AS data_bytes,
    index_total / total AS ratio
FROM system.parts
WHERE active AND (database = 'default') AND (`table` IN ('logs_uncompressed_1b', 'logs_compressed_1b'))
GROUP BY
    database,
    `table`

Query id: 46e2ed37-5a52-40b8-874d-5f634a2adc50

   ┌─database─┬─table────────────────┬───────total─┬─index_total─┬──────count─┬─bytes─────┬─index_bytes─┬─data_bytes─┬───────────────ratio─┐
1. │ default  │ logs_uncompressed_1b │ 53329343091 │ 23630662611 │ 1000000000 │ 49.67 GiB │ 22.01 GiB   │ 27.66 GiB  │  0.4431080759925575 │
2. │ default  │ logs_compressed_1b   │ 31578203205 │  1879500753 │ 1000000000 │ 29.41 GiB │ 1.75 GiB    │ 27.66 GiB  │ 0.05951892641891687 │
   └──────────┴──────────────────────┴─────────────┴─────────────┴────────────┴───────────┴─────────────┴────────────┴─────────────────────┘

2 rows in set. Elapsed: 0.006 sec.

With postings compression enabled for the inverted index, the index storage footprint is reduced by more than an order of magnitude (over 10× smaller).

@Algunenano

Copy link
Copy Markdown
Member

The library uses GPL 2, which is not compatible with ClickHouse's Apache

@Ergus Ergus self-assigned this Nov 6, 2025
@Ergus

Ergus commented Nov 6, 2025

Copy link
Copy Markdown
Member

Hi @fastio

Apart from the License, which is a serious issue.

We already tried PFor based compression in posting lists a few months ago and it had a very important impact in performance ~2-3x slowdown. And the compression rate was <20%. It would be nice to share if you have some numbers about the compression rate with TurboPFor

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

Hi @fastio

Very thanks for this contribution and the code is actually very nice.

Sadly I cannot approve this due to a License issue, however I reviewed it with some comments in case you want to consider. Feel free to share your thought and any comment related with them

Also I don't see any test for this code. In a change like this I would request very extensive tests including some performance checks and rate compression information.

Best,
Ergus

temp_buffer.resize(bytes);
in.readStrict(temp_buffer.data(), bytes);
/// Decode postings
unsigned char *p = reinterpret_cast<unsigned char *>(temp_buffer.data());

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.

Minor: unsigned char * p

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, got it.

in.readStrict(raw.data(), bytes);
auto p = reinterpret_cast<unsigned char*>(raw.data());
Codec::decodeBlock<T>(p, n, decoded, bytes);
++ current_block;

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.

No space here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, got it.


String getName() const override { return PostingListData::name(); }

void add(AggregateDataPtr __restrict place, const IColumn ** columns, size_t row_num, Arena * arena) const override

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.

Is it possible to use another input argument than a **.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The add method is part of the aggregate function interface named IAggregateFunction defined by the framework.
AggregateFunctionPostingsList inherits from this interface and must implement the same function signature.

My understanding is that this design comes from the requirement that the aggregation hot path must have zero abstraction overhead.
Using const IColumn ** allows the compiler to optimize aggressively, which wouldn’t be possible with a std::vector<const IColumn *> wrapper.


}

void registerAggregateFunctionsTextSearch(AggregateFunctionFactory & factory)

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.

Where is this function used?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function will be used together with projection indexes to support text indexing in future work.

}
}

void serialize(WriteBuffer & buf, std::optional<size_t> /* version */) const

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.

The code should at least chassert that the version argument is correct right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, got it.

if (postings.isSmall())
{
const auto &small = postings.getSmall();
assert(postings.size() <= small.size());

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.

chassert

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👌,got it.

{
PostingsContainer32 container;
PostingList postings;
container.decodeTo(istr, postings);

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.

In my experience this could be the key for any performance impact. You could consider to use the profiler events api to measure this and compare with uncompressed alternatives

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you very much for pointing this out.

Apologies — I took a shortcut here.
I reused the existing PostingListBuilder logic, which still relies on a bitmap-based representation for the token → row-id mapping.

In this PR I only implemented the write-side using PostingsContainer, while the read/query side is still using the original bitmap path. This means there is an unnecessary data-structure conversion happening here.

As a next step, I will switch the query-side to use PostingsContainer directly, and then compare the performance between the original bitmap-based path, and the pure PostingsContainer path.

{
PostingsContainer64 out_container;
mergePostingsContainers(out_container, container, rhs.container);
container.swap(out_container);

@Ergus Ergus Nov 6, 2025 •

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.

Very minor:

IIUC the "old container" is not needed anymore, so maybe it is better to use a move (to release it) instead of a swap. I know it will go out of scope immediately, but in case of issues it will be easier to debug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I completely agree — thanks for pointing it out. I’ll update it.

}

/// Returns an iterator over decompressed postings (lazy block decoding).
auto begin() const

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 strongly discourage to use the croaring iterator api. In their own comment they explain that it is much slower than the array conversion alternative. And in our tests it affected performance by ~40%.

https://github.com/RoaringBitmap/CRoaring/blob/8711167f6c06f663ef2163875f2704bd44355cb5/cpp/roaring/roaring.hh#L899

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the warning — I fully agree that the croaring iterator API is not something we want to use in hot paths. Just to clarify: in this particular code we are not using the croaring iterator API. The Iterator here is the iterator of our own PostingsContainer abstraction.

result_array_data.resize(result_array_data_insert_begin + container.size());

size_t idx = 0;
for (auto it = container.begin(); it != container.end(); ++it, idx++)

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.

The croaring iterator API is very slow. That's why we recommend to use api variants based in the toArray call

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Iterator here is the iterator of our own PostingsContainer abstraction.

@fastio

fastio commented Nov 7, 2025

Copy link
Copy Markdown
Contributor Author

Very thanks for this contribution and the code is actually very nice.

Sadly I cannot approve this due to a License issue, however I reviewed it with some comments in case you want to consider. Feel free to share your thought and any comment related with them

Also I don't see any test for this code. In a change like this I would request very extensive tests including some performance checks and rate compression information.

Best,

@Ergus , Thanks a lot for your detailed review and kind words!
I understand the license concern. I’ll also prepare additional tests — both functional and performance — to provide better coverage and metrics for compression efficiency.

Thanks again for the thoughtful review and valuable suggestions!

Best,
Jian.

@rschu1ze

Copy link
Copy Markdown
Member

It was said above but TurboPFOR is a no-no for ClickHouse due to GPL.

Perhaps we can splitt of the aggregation function into a separate PR?

@fastio
fastio requested a review from Ergus December 5, 2025 08:36
@fastio
fastio marked this pull request as draft December 5, 2025 08:37
@fastio
fastio marked this pull request as ready for review December 10, 2025 09:20
@fastio

fastio commented Dec 12, 2025

Copy link
Copy Markdown
Contributor Author

It was said above but TurboPFOR is a no-no for ClickHouse due to GPL.

Perhaps we can splitt of the aggregation function into a separate PR?

@rschu1ze Ok, I’ve removed the aggregation-related code. This PR is now focused solely on posting list storage compression.

@fastio

fastio commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @fastio

Very thanks for this contribution and the code is actually very nice.

Sadly I cannot approve this due to a License issue, however I reviewed it with some comments in case you want to consider. Feel free to share your thought and any comment related with them

Also I don't see any test for this code. In a change like this I would request very extensive tests including some performance checks and rate compression information.

Best, Ergus

@Ergus Thank you very much for all your helpful review comments.

I’ve removed the posting list aggregate function–related code, so this PR now focuses solely on posting list compression. Based on current tests, when postings are relatively long (i.e. tokens are highly repetitive in the log data), the compression ratio is quite substantial. At the same time, CPU and memory usage during writes have not increased noticeably.

@fastio

fastio commented Dec 12, 2025

Copy link
Copy Markdown
Contributor Author

Hi @Ergus, Thanks for reviewing this! No rush, but could you continue the review on this PR when you have bandwidth?

@Ergus

Ergus commented Dec 12, 2025

Copy link
Copy Markdown
Member

Hi @fastio

Very very sorry for the delay. This is a bad week because we have critical tasks with 100% priority (even over my own tasks, plans and development) and your new version deserves a full new review ;)

I promise that your PR will be my first task after this ;)

@fastio

fastio commented Dec 12, 2025

Copy link
Copy Markdown
Contributor Author

Hi @fastio

Very very sorry for the delay. This is a bad week because we have critical tasks with 100% priority (even over my own tasks, plans and development) and your new version deserves a full new review ;)

I promise that your PR will be my first task after this ;)

No worries — I completely understand. Thanks a lot for taking this on, and good luck with the urgent tasks!

@Ergus

Ergus commented Dec 15, 2025

Copy link
Copy Markdown
Member

Hi @fastio

I was checking the code and in general it looks good to me (I have some comments, but nothing critical to worry).

However, at the moment we are working in an update for the index format: Inverted Text Index v3 (that is expected to be merged soon) and these changes has conflicts.

Let's stop this PR for now and after merging the new version we restore this PR. Is it fine?

@fastio

fastio commented Dec 15, 2025

Copy link
Copy Markdown
Contributor Author

Hi @fastio

I was checking the code and in general it looks good to me (I have some comments, but nothing critical to worry).

However, at the moment we are working in an update for the index format: Inverted Text Index v3 (that is expected to be merged soon) and these changes has conflicts.

Let's stop this PR for now and after merging the new version we restore this PR. Is it fine?

@Ergus Thanks for your review.
Sure, looking forward to the new inverted text index v3!

@Ergus

Ergus commented Dec 18, 2025

Copy link
Copy Markdown
Member

Hi @fastio

I just want to let you know that the V3 was merged today :)

I am looking again at this changes and it looks that they will need full re-implementation for the new format. I let to your consideration if it worth trying that for the new index.

However I highlight two + 1 details to consider:

  1. The current v3 format will be the standard soon when we make the beta version. So a simdcomp compressed format will require to be specified with a flag or any method that don't break compatibility with v3. Fell free to ask for help, advise or share any concert and we will be very happy to help.

  2. If yo decide to finally re-implement this, please, don't forget to repeat the benchmark showed in the PR description to to ensure that the change is improving as expected.

2 + 1. It will be very relevant to measure not only space, but also performance impact of the compression with some numbers (the good and the bad ones). Either in hot or cold runs.

Best,
Ergus

@fastio

fastio commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor Author

I just want to let you know that the V3 was merged today :)

I am looking again at this changes and it looks that they will need full re-implementation for the new format. I let to your consideration if it worth trying that for the new index.

However I highlight two + 1 details to consider:

  1. The current v3 format will be the standard soon when we make the beta version. So a simdcomp compressed format will require to be specified with a flag or any method that don't break compatibility with v3. Fell free to ask for help, advise or share any concert and we will be very happy to help.
  2. If yo decide to finally re-implement this, please, don't forget to repeat the benchmark showed in the PR description to to ensure that the change is improving as expected.

2 + 1. It will be very relevant to measure not only space, but also performance impact of the compression with some numbers (the good and the bad ones). Either in hot or cold runs.

@Ergus Congratulations on the V3. Thanks a lot for the update and the detailed notes — much appreciated.

I’ll work on re-implementing the index compression for the v3 format in the next few days and rerun the benchmarks, covering storage size and the performance impact on reads and writes.

@Ergus

Ergus commented Dec 22, 2025

Copy link
Copy Markdown
Member

@Ergus Congratulations on the V3.

That's for @CurtizJ ;)

I’ll work on re-implementing the index compression for the v3 format in the next few days and rerun the benchmarks, covering storage size and the performance impact on reads and writes.

Thank you very much, I will be on hold for whatever you need

@fastio

fastio commented Dec 29, 2025

Copy link
Copy Markdown
Contributor Author

I’ve submitted a new PR and closed the old one.

@fastio fastio closed this Dec 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants