Skip to content

Add StringHashMap to optimize string aggregation - #5417

Closed
amosbird wants to merge 1 commit into
ClickHouse:masterfrom
amosbird:ssomap
Closed

amosbird wants to merge 1 commit into
ClickHouse:masterfrom
amosbird:ssomap

Conversation

@amosbird

@amosbird amosbird commented May 25, 2019 •

Copy link
Copy Markdown
Collaborator

I hereby agree to the terms of the CLA available at: https://yandex.ru/legal/cla/?lang=en

For changelog.

Add short_string_optimization settings to optimize short string aggregations.

Category (leave one):

  • Performance Improvement

Motivations

There are a lot of string data that acts as an aggregation key all over the place, such as url domains, nick names, key words, rdf attributes, IDs, to name a few. Most of them share a common property: the length is small. A few of them have low cardinalities and are well handled by ClickHouse now, while others generally don't. Since a major portion of time consuming operations related to short strings are based on hash tables, a better hash table is needed for speeding them up for short string keys. No only will it give better aggregation performance, but also help improve Join, Dict and other analytical functions.

Observations and Current Limitations

Currently strings are represented as StringRefs and a linear probing hash table with saved hash values is used to support all string key related operations. The obvious drawback of this approach is its huge memory overhead. Each short string might results in a StringRef structure that is larger than itself. An naive appproach would be adopting the SSO techniques in major standard libraries that encodes short strings in place of their StringRef structures. However it might lead to even worse memory overhead, and suffer from tons of branch misses due to several branch conditions it introduces.

There are other aspects that can be optimized:

  1. It doesn't make sense to save short keys' hash values

  2. The loaded piece of memory in the hash computation process can be reused.

  3. CRC32 hash works well for both numeric and string values.

  4. We can assume strings don't contain zero bytes in middle. (this might not be true, but can be served as an optimization hint)

Side node: ClickHouse's HashMapWithSavedHash is already very efficient in aggregation workloads. I've tested 10+ hashmaps that are all self-claimed to be the fastest one, none of them runs even closed to HashMapWithSavedHash (+20% - 100%). Oh, there are also maps built via Trie, which are generally slower than hashmaps in aggregation workloads.

Main Ideas and Promising Results

The main idea of this patch is to use string length dispatching so that small string keys will end up in hash tables that are built for integers. It's both CPU and memory efficient than using StringRef for short keys. The outcome is a hashtable that is up to 100% faster than the original one.

Unit Testing

In order to get reliable test results, I did the following steps as a prelude:

  1. add "isolcpus=5,11 rcu_nocbs=5,11" to boot cmdline to isolate a real cpu (hyperthreaded) for testing

  2. sudo python3 -m perf system tune to set stable cpu frequency

  3. numactl and taskset to make sure local memory access and using the isolated cores

The following tests are all single-threaded.

Map

StringHashMap is up to 100% faster than both HashMap and HashMapWithSavedHash in small string workloads when tested directly (See string_hash_map.cpp). Here are some results: (termN means the key length is subject to binomial distribution with expectation N)

image

I've also tested StringHashMap with long string dataset (expectation = 48 bytes). It's about 1% slower. I decided to use up to 24 bytes for small strings, same as gcc and clang for their SSO strings. It makes code smaller and properly does faster dispatching.

Aggregation

StringHashMap is consistently more effcient in the aggregation tests (See string_hash_map_aggregation.cpp bench_agg). The improvement is a bit lower (up to 70%) since the actual time spending on hashmap operations are around 70%. (perf shows the two other major operations are: 1. getKey; and 2. agg function). To complete the comparision, I've also tested the merging process (See string_hash_map_aggregation.cpp bench_merge). As we now have more sequencial memory access during map iterations, the merge process runs faster too. Here are some results:

image

End to End Testing (Parallel 40 Threads)

To validate the efficiency of StringHashMap, I've carried on some e2e tests via the SQL interface. The query I used looks like this: insert into blackhole select term8, count() from terms group by term8. Here are some results:

image

Memory Consumption Testing

StringHashMap is very memory efficient compared to HashMap. It doesn't use Arena when keys are shorter than 24 bytes. To achieve this, I changed the emplace API to accept an additional Arena argument that is only used when Key is of type StringRef, wihch replaces the onNewKey method. Here are some results:

image

To further validate the efficiency, I tried grouping 1 billion small string records with high cardinality. StringHashMap consumes 60GB memory while HashMap 100GB. In addition, https://greg7mdp.github.io/parallel-hashmap/ suggests that two level hash tables use memory in a smooth manner. As we already adopted TwoLevelHashMap, StringHashMap makes it even smoother. Note: the table grower used in StringHashMap (or its two level variant) has its glowing rate set to 1, or else we could end up having too many submaps with a very low fill factor. It also helps make testing stable to different dataset, since some dataset might trigger the grow too early, resulting in unfair comparisions.

Additional Testing

I've also tested with some real dataset (100M weibo posting dataset with nickname and number of comments). The name cardinality is around 20M and the length distribution is

SELECT quantilesExact(0.2, 0.4, 0.6, 0.9, 1)(length(name)) FROM weibo

┌─quantilesExact(0.2, 0.4, 0.6, 0.9, 1)(length(name))─┐
│ [10,12,16,24,45]                                    │
└─────────────────────────────────────────────────────┘

Testing SQL: insert into blackhole select name, count(comments_num) from weibo group by name;. StringHashMap is 25% faster.

In addition to the StringHashMap work, I've also built a RobinHoodMap because of its recent fame (https://news.ycombinator.com/item?id=12399989 and rust's default hashmap). It turns out that the performance of a hashmap is heavily related to the workloads it's dealing with. For aggregations, ClickHouse's linear probing hashmap outperforms robinhood map by 20%. In fact, it outperforms all hashmaps I could find, which gives me a really hard time when building the map, since there is really nothing to optimize: the code is dead simple. However, there is indeed an opportunity for string keys to use RobinHoodMap due to its variant length property. This might make StringHashMap more efficient. I'll try to enhance it in near future. Also, for long string keys, there are some chances we can do better too.

Some Implementation Details

Key Dispatching

The key dispatching process is critical for efficiency. It has to do proper inlining, fast memcpying and hash computation, etc. (See comments in StringHashMap.h for detail)

Serialization and Merge

After aggregation, there is a workload for extracting key-values from hashmap into actual blocks. This might be a heavy workload when the grouping key has a high cardinality. Since StringHashMap requires converting different cells into a StringRef representation, it consumes addtional cpu resources. In order to avoid unnecessary data conversion, I've turned the iterator inside out (http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/), and make key disassembling as late as possible, hoping compilers eliminate additional data movements for me. This works well and is even faster due to that strings are stored continuously in the cells, compared to a bunch of randomly allocated StringRef pointers.

LastElemCache

Building the LastElemCache requires the original StringRef key stored, which drags StringHashMap down as we have to convert the numeric representation to a StringRef. To tackle this, I tried reusing the input key and making sure that onExistingKey wouldn't rollback the cache. (There is also a bug discovered in the Serialized method https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ColumnsHashingImpl.h#L243) However, enabling LastElemCache still slows down the aggregation by 20% due to code bloating. Luckily, emplacing keys in the numeric hash table has comparable performance to StringRef comparisons, so we can disable the use_cache without possibly introducing regression. To validate this observation, I've generated three datasets, each of them has 100 million same strings with length <= 8, <= 16, and <=24. Hence, all except one operation will end up hitting the LastElemCache if it's enabled. The test result shows that using StringHashMap without cache is as efficient as using HashMap with cache. That's why I have cached disabled for StringHashMap.

TODO

  1. StringHashMap in Join, Dict and others

  2. Apply to serialized method. Need to resolve zeroes in middle

  3. In distributed env the two level hash computation is redundant

  4. Make compatible to non SSE4.2 build and Big Endianness?

  5. Better hash maps for short keys and long keys

@alexey-milovidov alexey-milovidov added can be tested pr-performance Pull request with some performance improvements labels May 25, 2019
@alexey-milovidov

Copy link
Copy Markdown
Member

That's awesome!

@akuzm

akuzm commented Jun 3, 2019

Copy link
Copy Markdown
Contributor

@akuzm akuzm requested a review from alexey-milovidov an hour ago

Oops, disregard this, must've pressed something by accident.

@akuzm

akuzm commented Jun 3, 2019

Copy link
Copy Markdown
Contributor

@amosbird I'm seeing a ubsan failure on functional tests, could you look into it?

../dbms/src/Common/Arena.h:245:21: runtime error: null pointer passed as argument 2, which is declared to never be null
/usr/include/string.h:43:28: note: nonnull attribute specified here
    #0 0x16ad4f82 in DB::Arena::insert(char const*, unsigned long) /build/obj-x86_64-linux-gnu/../dbms/src/Common/Arena.h:245:9
    #1 0x16ad4f82 in HashTable<StringRef, HashMapCellWithSavedHash<StringRef, char*, DefaultHash<StringRef>, HashTableNoState>, DefaultHash<StringRef>, 
...

Full log is here: https://clickhouse-test-reports.s3.yandex.net/5417/8aa7045d846cafb5ac5776be83078c8ea7da362a/functional_stateless_tests_(ubsan)/stderr.txt

If you fix it, it's better to rebase to current master, because test reports were broken at that time so we only see '[' in error report.

@akuzm
akuzm removed the request for review from alexey-milovidov June 3, 2019 17:19
@akuzm

akuzm commented Jun 3, 2019

Copy link
Copy Markdown
Contributor

I see some formatting changes in the lines that are not otherwise touched by this pull request. This leads to some problems:

  • it complicates the review, because the reviewer has to filter out these changes,
  • it makes git blame less useful,
  • it might introduce unnecessary conflicts with other pull requests or older branches.

I'd prefer not to change the formatting of the old code at all, or, if it blatantly violates our style guide, to do it as a separate pull request.

Comment thread dbms/src/Common/HashTable/HashMap.h Resolved
@amosbird

amosbird commented Jun 4, 2019 •

Copy link
Copy Markdown
Collaborator Author

Thanks for reviewing this! The formating and style adjustments are to settle down the changes introduced from my previous FixedHashMap PR. I agree those should be separate commits, however this feature is a long over due and has been refactored multiple times. The original commits aren't reviewable at all thus I've squashed them.

@akuzm akuzm left a comment

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.

Thanks for the fixes, I will continue with the review. Among other things, I'd like to try adding a performance test for aggregation to our CI.

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.

It's worth to have a comment about why we use internal iteration, like you described in the pull request, and also mention what arguments the Func should take.

The names of the functions are somewhat unclear. Maybe something like mergeToEmplace -> merge and mergeToFind -> findInBoth?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Indeed, comments are needed among other places as well. Naming things is hard (https://martinfowler.com/bliki/TwoHardThings.html) . I'm open to suggestions.

Comment thread dbms/src/Common/ColumnsHashingImpl.h Outdated

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.

We can probably remove this one as well, I tried and there's no warning.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removing that leads to

/home/amos/git/chorigin/dbms/src/Common/ColumnsHashingImpl.h:40:54: error: 'state' may be used uninitialized in this function [-Werror=maybe-uninitialized]
     bool check(const Value & value_) { return !empty && value == value_; }
                                               ~~~~~~~^~~~~~~~~~~~~~~~~~

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.

StringHashTableHash doesn't provide a StringRef hash, so the Ts type looks wrong. I don't understand why it compiles. First I thought that it works because the actual hashing is done by dispatch(). To check that, I tried removing the hash function for UInt16, but then it doesn't compile because getHash() is required somewhere. I'm confused now.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yeah, that code somehow gets lost when doing refactoring. It compiles because Ts uses SavedHash scheme and dispatch always provides a hash value upon insertion, so getHash() never gets called. I'll add the hash function back.

@akuzm

akuzm commented Jun 7, 2019

Copy link
Copy Markdown
Contributor

As an aside, I found an interesting benchmark of some hashing algorithms: https://github.com/vnmakarov/mum-hash#intel-i7-9700k

MUM looks promising for small strings, and Meow -- for long ones. Both are relatively new, maybe we should test them in the future.

@amosbird

amosbird commented Jun 7, 2019

Copy link
Copy Markdown
Collaborator Author

I doubt any of those would beat CRC32 due to hardware acceleration. But it might be useful for serialized method when better hash functions are required.

Comment thread dbms/src/Common/HashTable/HashTable.h Outdated

@akuzm akuzm Jun 7, 2019 •

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.

So in the end the HashTable decides whether to put the key to arena or not, looking at its type? This looks convoluted. Can we decide this in the caller and just call the proper method? Or even better, just work with Arena in the caller, and not make HashTable know about it at all.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It's not trivial since StringHashMap has different submaps and only the string submap does allocation. Adding a new method will require multiple if constexpr hanging around

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.

You mean, because of multiplexing in dispatch(), the callers like HashMethodBase::emplaceKeyImpl() can't know whether they should put the key to Arena or not? This is a problem indeed. Still, I think HashTable is supposed to be a generic container, and so it shouldn't contain any logic specific to the particular use case with StringHashTable and Arena. Maybe we could make this decision in StringHashTable itself?

Or maybe we could move the Arena-related stuff even higher in the call graph. I'll try to find a solution next week, but this will take some time. The hashing-related code in CH seems rather convoluted and I'm having a hard time understanding it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@akuzm Gentle ping.

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.

Replied on Telegram.

Comment thread dbms/src/Common/ColumnsHashing.h Resolved
@akuzm

akuzm commented Jul 26, 2019

Copy link
Copy Markdown
Contributor

Now that sso is enabled by default, it's strange that we don't see improvement in performance test.

There are also some regressions on queries like SELECT URL, count() AS c FROM hits_100m_single GROUP BY URL ORDER BY c DESC LIMIT 10: https://clickhouse-test-reports.s3.yandex.net/5417/11f4f571f9c6e04bbbb3b005ac2f51d344e8b69e/performance_test/comparison_min_time_gcc_8.html

akuzm added a commit that referenced this pull request Aug 30, 2019
For compound hash tables such as the future StringHashMap, implementing
an iterator-based API might be inefficient, because:
1) the information about the component to which the value belongs is
lost, and has to be recalculated if the value is reinserted;
2) the key has to be converted to a general format from a from a
component-specific format, which may differ between the components.
These inefficiencies are especially apparent when merging two hash
tables. In contrast, an efficient algorithm would merge a compound table
component-wise, avoiding unnecessary conversions and recalculations.

Therefore, switch Aggregator to use internal iteration (map-like
functions) when traversing and merging the hash tables.

This commit prepares for the StringHashMap PR #5417 and contains some of
its code.
@akuzm

akuzm commented Aug 30, 2019

Copy link
Copy Markdown
Contributor

Some benchmark results.
I took this PR, and also my refactored version from #6243. Rebased them both to v19.13.1.1060-testing. Then ran string_hash_map test, term48, 50M elements. The results are as follows:

Branch Hash map type Emplaced keys/second
Refactored StringHashMap 4486378
Refactored HashMapWithSavedHash 4735624
Original StringHashMap 4345652
Original HashMapWithSavedHash 4466526

This is median of 38 runs, the spread of results is 5 to 20%. The CPU is Intel(R) Xeon(R) CPU E5-2660 v4 @ 2.00GHz.

I'm not sure what the results mean. There is a regression of StringHashMap compared to the HashMapWithSavedHash on long keys. I didn't see this regression on the original version before, but that was on a different machine. It's good to see that the refactoring didn't worsen performance, but I'm also not sure why would it improve performance, especially when we are benchmarking emplace() of the old hash map. Maybe it's the effect of not having to construct a resulting iterator and returning a pointer to mapped value instead (that is change 2.2 from my above big comment).

@amosbird

Copy link
Copy Markdown
Collaborator Author

I'm not sure what the results mean

It might related to the load factor being too small which triggers edge resize. https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/HashTable/HashTable.h#L159

tweaking it to 80%-95% probably gives more reliable results.

akuzm added a commit that referenced this pull request Sep 6, 2019
Some aggregation methods initially emplace a temporary StringRef key
into a hash table. Then, if the key was not seen before, they make a
persistent copy of the key and update the hash table with it. This
approach is not suitable for compound hash tables, because the logic of
when the persistent key is needed is more complex, and is contained
within the hash table itself.

In this commit, we switch to managing key memory with callbacks passed
to the hash table, that allow it to request a persistent copy of the key
if it is needed. This should be more appropriate for compound hash
tables.

This commit prepares for StringHashMap PR #5417.
akuzm added a commit that referenced this pull request Sep 6, 2019
For compound hash tables such as the future StringHashMap, implementing
an iterator-based API might be inefficient, because:
1) the information about the component to which the value belongs is
lost, and has to be recalculated if the value is reinserted;
2) the key has to be converted to a general format from a from a
component-specific format, which may differ between the components.
These inefficiencies are especially apparent when merging two hash
tables. In contrast, an efficient algorithm would merge a compound table
component-wise, avoiding unnecessary conversions and recalculations.

Therefore, switch Aggregator to use internal iteration (map-like
functions) when traversing and merging the hash tables.

This commit prepares for the StringHashMap PR #5417 and contains some of
its code.
akuzm added a commit that referenced this pull request Sep 6, 2019
Some aggregation methods initially emplace a temporary StringRef key
into a hash table. Then, if the key was not seen before, they make a
persistent copy of the key and update the hash table with it. This
approach is not suitable for compound hash tables, because the logic of
when the persistent key is needed is more complex, and is contained
within the hash table itself.

In this commit, we switch to managing key memory with callbacks passed
to the hash table, that allow it to request a persistent copy of the key
if it is needed. This should be more appropriate for compound hash
tables.

This commit prepares for StringHashMap PR #5417.
akuzm pushed a commit that referenced this pull request Sep 9, 2019
For compound hash tables such as the future StringHashMap, an
iterator-based API might be inefficient for iterating over a table or
for merging two tables, because:

1) the key has to be converted to a general format from a from a
   component-specific format, which may differ between the components;

2) the information about the component of the compound hash table to
   which the value belongs is lost, and has to be recalculated if the
   value is reinserted.

A more efficient approach is to use internal iteration, that is,
map-like functions, which avoids unnecessary conversions when iterating,
and allows to use an efficient component-wise approach when merging.

This commit is a part of the StringHashMap PR #5417.
@akuzm

akuzm commented Sep 12, 2019

Copy link
Copy Markdown
Contributor

Remember the mysterious ubsan failure?
Good news: I can reproduce it every time under MemorySanitizer.
Bad news: It's in master now.

The old ubsan stack was like that, the new msan one is the same.

../dbms/src/Columns/ColumnArray.cpp:163:16: runtime error: pointer index expression with base 0xffffffffffffffff overflowed to 0x000000000007
    #0 0x166a229a in DB::ColumnArray::insertData(char const*, unsigned long) /build/obj-x86_64-linux-gnu/../dbms/src/Columns/ColumnArray.cpp:163:16
    #1 0x156a3c7e in void DB::deserializeAndInsertImpl<true>(StringRef, DB::IColumn&) /build/obj-x86_64-linux-gnu/../dbms/src/AggregateFunctions/AggregateFunctionGroupUniqArray.h:284:13
    #2 0x156a3c7e in DB::AggregateFunctionGroupUniqArrayGeneric<true, std::__1::integral_constant<bool, true> >::deserializeAndInsert(StringRef, DB::IColumn&) /build/obj-x86_64-linux-gnu/../dbms/src/AggregateFunctions/AggregateFunctionGroupUniqArray.h:163
    #3 0x156a3c7e in DB::AggregateFunctionGroupUniqArrayGeneric<true, std::__1::integral_constant<bool, true> >::insertResultInto(char const*, DB::IColumn&) const /build/obj-x86_64-linux-gnu/../dbms/src/AggregateFunctions/AggregateFunctionGroupUniqArray.h:254
    #4 0x1622a88c in auto DB::Aggregator::convertToBlockImplFinal<DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >(DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >&, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&) const::{lambda(auto:1 const&)#1}::operator()<FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >::ValueHolder>(FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >::ValueHolder const&) const /build/obj-x86_64-linux-gnu/../dbms/src/Interpreters/Aggregator.cpp:1131:37
    #5 0x1622a599 in void FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >::forEachValue<DB::Aggregator::convertToBlockImplFinal<DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >(DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >&, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&) const::{lambda(auto:1 const&)#1}>(DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >&&) /build/obj-x86_64-linux-gnu/../dbms/src/Common/HashTable/FixedHashMap.h:121:13
    #6 0x1622a412 in void DB::Aggregator::convertToBlockImplFinal<DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >(DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >&, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&) const /build/obj-x86_64-linux-gnu/../dbms/src/Interpreters/Aggregator.cpp:1127:10
    #7 0x16226d32 in void DB::Aggregator::convertToBlockImpl<DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >(DB::AggregationMethodOneNumberNoCache<unsigned char, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> > >&, FixedHashMap<unsigned char, char*, AllocatorWithHint<true, AllocatorHints::DefaultHint, 67108864ul> >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, std::__1::vector<DB::PODArray<char*, 4096ul, AllocatorWithHint<false, AllocatorHints::DefaultHint, 67108864ul>, 15ul, 16ul>*, std::__1::allocator<DB::PODArray<char*, 4096ul, AllocatorWithHint<false, AllocatorHints::DefaultHint, 67108864ul>, 15ul, 16ul>*> >&, std::__1::vector<COW<DB::IColumn>::mutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::mutable_ptr<DB::IColumn> > >&, bool) const /build/obj-x86_64-linux-gnu/../dbms/src/Interpreters/Aggregator.cpp:1100:9

@amosbird

Copy link
Copy Markdown
Collaborator Author

In master now? You mean it's introduced by the iterator inside out pr ?

@akuzm

akuzm commented Sep 12, 2019

Copy link
Copy Markdown
Contributor

In master now? You mean it's introduced by the iterator inside out pr ?

I thought so, but after reverting this PR, it still reproduces. Will investigate further.

@akuzm

akuzm commented Sep 12, 2019

Copy link
Copy Markdown
Contributor

In master now? You mean it's introduced by the iterator inside out pr ?

I thought so, but after reverting this PR, it still reproduces. Will investigate further.

It doesn't reproduce if I revert the key holder patch. The test that fails under MemorySanitizer is 00376_shard_group_uniq_array_of_int_array. I've been looking at this for several hours now, and don't have a slightest idea what is happening. Interestingly, the test doesn't fail if I create the table and wait for the background merges to complete.

@amosbird

Copy link
Copy Markdown
Collaborator Author

Interestingly, the test doesn't fail if I create the table and wait for the background merges to complete.

Intriguing. I'll investigate too. What's the cmake command line you use to generate memory sanitizer build?

@amosbird

Copy link
Copy Markdown
Collaborator Author

Hmm, I cannot reproduce with memory sanitizer

@akuzm

akuzm commented Sep 13, 2019

Copy link
Copy Markdown
Contributor

Interestingly, the test doesn't fail if I create the table and wait for the background merges to complete.

Intriguing. I'll investigate too. What's the cmake command line you use to generate memory sanitizer build?

I'm using these flags:

cmake -DSANITIZE=memory -DCMAKE_C_COMPILER="clang-8" -DCMAKE_CXX_COMPILER="clang++-8" -DCMAKE_CXX_FLAGS="-stdlib=libc++" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_CXX_FLAGS="-O1 -fno-omit-frame-pointer -fno-optimize-sibling-calls" -DCMAKE_C_FLAGS="-O1 -fno-omit-frame-pointer -fno-optimize-sibling-calls" -D ENABLE_HDFS=0 -D ENABLE_CAPNP=0 -D ENABLE_RDKAFKA=0 -D ENABLE_ICU=0 -D ENABLE_POCO_MONGODB=0 -D ENABLE_POCO_NETSSL=0 -D ENABLE_POCO_ODBC=0 -D ENABLE_ODBC=0 -D ENABLE_MYSQL=0 -D ENABLE_EMBEDDED_COMPILER=0 -D USE_INTERNAL_CAPNP_LIBRARY=0 -D USE_SIMDJSON=0 -DENABLE_READLINE=0 -DENABLE_ORC=0 -DENABLE_PARQUET=0 -DUSE_CAPNP=0 -DUSE_INTERNAL_ORC_LIBRARY=0 -DUSE_ORC=0 -DENABLE_SSL=0

Some easy frequent failures are fixed here: #6925

@amosbird

Copy link
Copy Markdown
Collaborator Author

@akuzm found the cause. It's actually a bug lurking before and gets unveiled by hashtable refactoring.

When getting data from ColumnArray https://github.com/yandex/ClickHouse/blob/master/dbms/src/Columns/ColumnArray.cpp#L144
we can get an invalid pointer when current array is empty. (due to left padding of podarray, it should be some global readonly address)

Theoretically we'd like to get the same pointer value in https://github.com/yandex/ClickHouse/blob/master/dbms/src/Columns/ColumnArray.cpp#L151 . However, since we have a dedicated ZeroValueStorage in hash table. The pointer of zero lengthed arrays becomes nil after placing into the agg states hash table, which leads to UBSan and MemSan failure.

#6937

@akuzm

akuzm commented Sep 19, 2019

Copy link
Copy Markdown
Contributor

Some news about what I'm working on now: before, I changed emplace() to return a pointer to Mapped type, not an iterator. I realized that this makes it impossible to support a consecutive keys cache, because the cache must store the persistent key, and there is no way to get it from the table. The code that is now in #6243 is incorrect, it has a use-after-free in HashMethodBase::emplaceImpl, where it stores the key into cache.

I'm trying to fix this by returning a different type from emplace() based on the kind of the table. For normal tables, it will return a reference to Cell, and for FixedHashTable or StringHashTable -- pointer to Mapped type. The caller will then get the key and "mapped" value using overloaded functions. There will be no overloads for string or fixed table, but they are not needed, because these tables don't use cache. So hopefully it will work this way.

@amosbird

Copy link
Copy Markdown
Collaborator Author

Yeah, that was a difficulty when I built this hash map, which leads me to disable consecutive caches for certain maps.

@stale

stale Bot commented Oct 20, 2019

Copy link
Copy Markdown

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale Bot added the not planned Known issue, no plans to fix it currenlty label Oct 20, 2019
@blinkov blinkov removed the not planned Known issue, no plans to fix it currenlty label Oct 20, 2019
@akuzm

akuzm commented Oct 23, 2019

Copy link
Copy Markdown
Contributor

This PR was fully merged as a series of patches ending with #6243.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants