Repository navigation
Let TwoLevelHashTable choose its bucket count, and add PartitionedFixedHashTable - #120024
Conversation
|
Workflow [PR], commit [b52c051] Summary: ✅
AI ReviewSummaryThis PR makes Findings
Final Verdict
LLVM Coverage Report |
…rallel aggregation example `hash` is static now, and clang-tidy rejects calling it through an instance (`readability-static-accessed-through-instance`), which failed the `Build (arm_tidy)` job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120024&sha=a585437dc47e09116473f1ff7791a6c4244b8916&name_0=PR&name_1=Build%20(arm_tidy) #120024 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes79 object files changed (-811.82 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units522 translation units recompiled, 4946 s compile time in total, 522 of them have a recent master baseline. |
| for (auto & map : data->maps) | ||
| joinDispatch(kind, strictness, map, maps_kind, [this](auto, auto, auto & map_) { map_.computeBucketPrefix(data->type); }); | ||
| } | ||
|
|
There was a problem hiding this comment.
offsetInternal is no longer self-initializing, but StorageJoin never reaches this hook. StorageJoin::finishInsert() is empty, StorageJoin::getJoinLocked() only clones the prebuilt join through reuseJoinedData(), and reuseJoinedData() does not call computeBucketPrefix(). Once a reused Join(ANY, INNER, ...) / Join(ANY, RIGHT, ...) grows into a two-level map, the probe and non-joined paths still read map.offsetInternal(...) with bucket_cells_prefix left empty. In debug that trips the new chassert; in release it becomes an out-of-bounds read on the prefix vector. Please finalize the prefixes on the StorageJoin reuse path as well, or move this setup into a shared path that every probeable two-level join goes through.
|
For some reason it includes changes from |
| Impl flat; | ||
| }; | ||
|
|
||
| using Storage = std::conditional_t<isFixedRangeStorage(), FixedRangeStorage, PerBucketStorage>; |
There was a problem hiding this comment.
With more than one bucket, PartitionedFixedHashMap is instantiated by
exactly two map types: two_level_key8 and two_level_key16. Every
range* variant is declared JoinFixedHashMap<...>, i.e.
PartitionedFixedHashMap<..., BITS_FOR_BUCKET_SERIAL> - one bucket, no
routing, no locks - and none of them is ever built concurrently anyway:
chooseMethod returns no range* type, they come out of
tryConvertToFixedHashMap after the build, single-threaded. Those two
tables are 256 and 65536 cells: 3 KiB and 768 KiB at the 12-byte MapsOne
cell.
I'd want us to consider having no such abstraction at all: give each
inserter its own FixedHashMap and merge after the build. Basically,
repeating what CHJ already does with two-level maps. Key subsets are
already disjoint, so the merge copies into guaranteed-empty cells. At 64
inserters that is 192 KiB for key8 and 48 MiB for key16.
There was a problem hiding this comment.
Yeah.. I kept the one shared table because of the later layers in this stack.
Later layers of this PR stack build one hash table and share it across threads, for every key type. A slot is only a lock, bucket & (num_slots - 1). two_level_key64 is built the same way.
Scatter and insertIntoSlots both write that one map. The byte accounting and freezeMapsForProbing read it. StorageJoin reuses it when a later join has a different thread count.
A FixedHashMap has no sub-table per bucket. The cell index is the key, so a copy per inserter is a full array and most cells are empty.
FixedRangeStorage puts this map under the same slot locks. A private map per inserter, merged at the end, would build key8 and key16 on a different path from the rest of the stack.
There was a problem hiding this comment.
I understand the motivation, and it makes sense, that is not the question. I'd still want to avoid such changes in the precious HT. What about the following:
A standalone type that satisfies BucketPartitionedTable over one flat FixedHashMap. The concept already exists precisely so the join can hold either shape.
That lets all of this leave TwoLevelHashTable.h:
┌───────────────────────────────────────────────────────────────────────────────────┬───────────┐
│ │ lines │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ IsFixedRangeTable + its 2 specializations │ ~10 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ FixedRangeStorage │ 39 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ PerBucketStorage as a swappable class (collapses to plain members + prefix logic) │ ~50 of 78 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ BucketHash parameter + bucketRoutingHash indirection │ ~15 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ routedBucketFromIteration + both getRoutedBucket │ 15 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ serializedPartitionCount + its 4 loops → back to NUM_BUCKETS │ ~10 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ restoreMinMaxOptimization / canUseMinMaxOptimization on both storages │ ~6 │
├───────────────────────────────────────────────────────────────────────────────────┼───────────┤
│ the isFixedRangeStorage() halves of the guards at :299/308/316/509/515 │ — │
└───────────────────────────────────────────────────────────────────────────────────┴───────────┘
TwoLevelHashTable is left with exactly one new thing: bits_for_bucket, and the NUM_BUCKETS == 1 guards it needs anyway. That's the version of this PR I'd want — one parameter on a template the whole aggregator uses, not a second storage mode.
The standalone class is mostly delegation:
template <typename Key, typename Mapped, size_t size_bits = sizeof(Key)*8, UInt32 num_buckets = 256>
class PartitionedFixedHashMap // NOT a TwoLevelHashTable
{
Impl flat; // FixedHashMap<...FixedHashTableStoredSize...>
public:
static constexpr UInt32 NUM_BUCKETS = num_buckets;
static size_t bucketRoutingHash(Key k, size_t) { return FixedRangeBucketHash<sizeof(cell_type)>{}(k); }
static size_t getBucketFromHash(size_t h) { ... }
void emplace(...) { flat.emplace(...); } // find/has/size/empty/buffer sizes
void computeBucketPrefix() const { } // offsets are already global
size_t offsetInternal(ConstLookupResult p) const { return flat.offsetInternal(p); }
size_t offsetInternalAtBucket(ConstLookupResult p, size_t) const { return flat.offsetInternal(p); }
// + a thin iterator adding getBucket()/getRoutedBucket() over flat's
};
Call it ~100 lines each for the map and set flavours, against ~150 leaving TwoLevelHashTable. Net is roughly a wash on line count — the win is structural, not size: the aggregator's hash table stops carrying a mode that only the join's two fixed maps use, and the two shapes stay interchangeable because the concept enforces it.
And it should also allow to get rid of the atomic in the HT methods.
I haven't prototyped it myself, ofc, so this plan might be too optimistic.
There was a problem hiding this comment.
Thanks for writing this out in so much detail. I'll prototype the standalone class and come back with how it holds up.
On the atomic, I don't think the split lets us drop it. FixedHashTableStoredSize::m_size became atomic in #87366, for the parallel merge of key8 and key16 aggregation states. In that merge, several threads write into one FixedHashMap (Aggregator::mergeSingleLevelDataImplFixedMap), so they all update the same size counter. With the standalone class the join would no longer need the atomic, but the aggregator still would. Did you have a different atomic in mind?
There was a problem hiding this comment.
standalone class for FixedHashTable turned out to produce smaller diff :)
There was a problem hiding this comment.
With the standalone class the join would no longer need the atomic, but the aggregator still would.
It should be possible to fix joins and leave aggregation untouched. It is regulated by the template parameters, so it'd be different types. The effect should be very obvious on a targeted perf test.
The proposed patch
diff --git a/src/Common/HashTable/FixedHashMap.h b/src/Common/HashTable/FixedHashMap.h
index 1f56355a968e57..6dff9dd0f8a8f8 100644
--- a/src/Common/HashTable/FixedHashMap.h
+++ b/src/Common/HashTable/FixedHashMap.h
@@ -271,3 +271,15 @@ using FixedHashMapWithSizeBits = FixedHashMap<
FixedHashTableStoredSize<FixedHashMapCell<Key, Mapped>>,
HashTableAllocator,
size_bits>;
+
+/// Keeps no element counter, so `size` walks the buffer. For a caller that fills the table from
+/// several threads and does not ask for the size until the fill is over, which is cheaper than
+/// making the counter atomic - see `AggregatedDataWithUInt8Key`, which merges in parallel this way.
+template <typename Key, typename Mapped, size_t size_bits>
+using FixedHashMapWithSizeBitsAndCalculatedSize = FixedHashMap<
+ Key,
+ Mapped,
+ FixedHashMapCell<Key, Mapped>,
+ FixedHashTableCalculatedSize<FixedHashMapCell<Key, Mapped>>,
+ HashTableAllocator,
+ size_bits>;
diff --git a/src/Common/HashTable/FixedHashSet.h b/src/Common/HashTable/FixedHashSet.h
index 31ee7a88b6924c..f73c74a86306f9 100644
--- a/src/Common/HashTable/FixedHashSet.h
+++ b/src/Common/HashTable/FixedHashSet.h
@@ -2,12 +2,16 @@
#include <Common/HashTable/FixedHashTable.h>
-template <typename Key, typename Allocator = HashTableAllocator, size_t size_bits = sizeof(Key) * 8>
-class FixedHashSet : public FixedHashTable<Key, FixedHashTableCell<Key>, FixedHashTableStoredSize<FixedHashTableCell<Key>>, Allocator, size_bits>
+template <
+ typename Key,
+ typename Allocator = HashTableAllocator,
+ size_t size_bits = sizeof(Key) * 8,
+ typename Size = FixedHashTableStoredSize<FixedHashTableCell<Key>>>
+class FixedHashSet : public FixedHashTable<Key, FixedHashTableCell<Key>, Size, Allocator, size_bits>
{
public:
using Cell = FixedHashTableCell<Key>;
- using Base = FixedHashTable<Key, Cell, FixedHashTableStoredSize<Cell>, Allocator, size_bits>;
+ using Base = FixedHashTable<Key, Cell, Size, Allocator, size_bits>;
using Self = FixedHashSet;
void merge(const Self & rhs)
@@ -22,3 +26,8 @@ public:
/// caller, and the cell only records presence.
template <typename Key, size_t size_bits>
using FixedHashSetWithSizeBits = FixedHashSet<Key, HashTableAllocator, size_bits>;
+
+/// Set counterpart of `FixedHashMapWithSizeBitsAndCalculatedSize`: no element counter.
+template <typename Key, size_t size_bits>
+using FixedHashSetWithSizeBitsAndCalculatedSize
+ = FixedHashSet<Key, HashTableAllocator, size_bits, FixedHashTableCalculatedSize<FixedHashTableCell<Key>>>;
diff --git a/src/Common/HashTable/PartitionedFixedHashMap.h b/src/Common/HashTable/PartitionedFixedHashMap.h
index 92518f6a0bef69..096489de964de0 100644
--- a/src/Common/HashTable/PartitionedFixedHashMap.h
+++ b/src/Common/HashTable/PartitionedFixedHashMap.h
@@ -7,4 +7,5 @@
/// A `FixedHashMap` whose keys are split into buckets for a fill from several threads. See `PartitionedFixedHashTable`.
template <typename Key, typename Mapped, size_t size_bits = sizeof(Key) * 8, size_t BITS_FOR_BUCKET = DEFAULT_BITS_FOR_BUCKET>
-using PartitionedFixedHashMap = PartitionedFixedHashTable<FixedHashMapWithSizeBits<Key, Mapped, size_bits>, BITS_FOR_BUCKET>;
+using PartitionedFixedHashMap
+ = PartitionedFixedHashTable<FixedHashMapWithSizeBitsAndCalculatedSize<Key, Mapped, size_bits>, BITS_FOR_BUCKET>;
diff --git a/src/Common/HashTable/PartitionedFixedHashSet.h b/src/Common/HashTable/PartitionedFixedHashSet.h
index 06df24a16542b5..a71615b3828b3c 100644
--- a/src/Common/HashTable/PartitionedFixedHashSet.h
+++ b/src/Common/HashTable/PartitionedFixedHashSet.h
@@ -8,4 +8,5 @@
/// Set counterpart of `PartitionedFixedHashMap`, for a caller that only records which keys exist.
/// The cell holds nothing but the presence flag, so routing uses the cache line of that narrower cell.
template <typename Key, size_t size_bits = sizeof(Key) * 8, size_t BITS_FOR_BUCKET = DEFAULT_BITS_FOR_BUCKET>
-using PartitionedFixedHashSet = PartitionedFixedHashTable<FixedHashSetWithSizeBits<Key, size_bits>, BITS_FOR_BUCKET>;
+using PartitionedFixedHashSet
+ = PartitionedFixedHashTable<FixedHashSetWithSizeBitsAndCalculatedSize<Key, size_bits>, BITS_FOR_BUCKET>;
diff --git a/src/Common/HashTable/PartitionedFixedHashTable.h b/src/Common/HashTable/PartitionedFixedHashTable.h
index 6440a8ac8f8912..6888296541619c 100644
--- a/src/Common/HashTable/PartitionedFixedHashTable.h
+++ b/src/Common/HashTable/PartitionedFixedHashTable.h
@@ -16,7 +16,9 @@
* range would put every key into one bucket, so a key is routed by the cache line its cell starts on.
* `FixedHashMapCell` is padded so that its size divides the line, so two keys on one line share a bucket.
*
- * Distinct keys are distinct cells, and `FixedHashTableStoredSize` counts the size with an atomic.
+ * Distinct keys are distinct cells, so concurrent writers never touch the same cell. They keep no
+ * element counter: `size` walks the buffer instead, so that an insert does not have to update a
+ * counter shared by every bucket. Do not ask for the size while the table is being filled.
* The min/max bounds of the flat table are the one thing concurrent writers would race on.
* They stay off while there is more than one bucket. `restoreMinMaxOptimization` derives them after the fill.
*/
@@ -24,9 +26,6 @@ template <typename Impl, size_t BITS_FOR_BUCKET>
class PartitionedFixedHashTable
{
static_assert(BITS_FOR_BUCKET < 32, "the bucket is taken from the low 32 bits of the hash");
- static_assert(
- std::is_base_of_v<FixedHashTableStoredSize<typename Impl::cell_type>, Impl>,
- "several threads insert at once, so the size counter has to be atomic");
public:
using key_type = typename Impl::key_type;
diff --git a/src/Common/tests/gtest_partitioned_fixed_hash_map.cpp b/src/Common/tests/gtest_partitioned_fixed_hash_map.cpp
index c214a92ba50c72..fee0b66c9014b4 100644
--- a/src/Common/tests/gtest_partitioned_fixed_hash_map.cpp
+++ b/src/Common/tests/gtest_partitioned_fixed_hash_map.cpp
@@ -25,8 +25,15 @@ using Partitioned = PartitionedFixedHashMap<Key, UInt64, size_bits, BITS_FOR_BUC
template <typename Key, size_t size_bits>
using Plain = FixedHashMapWithSizeBits<Key, UInt64, size_bits>;
+/// The flat table the partitioned one wraps, which keeps no element counter.
+template <typename Key, size_t size_bits>
+using PlainUncounted = FixedHashMapWithSizeBitsAndCalculatedSize<Key, UInt64, size_bits>;
+
/// The buckets add no state to the flat table.
-static_assert(sizeof(Partitioned<UInt16, 16, 8>) == sizeof(Plain<UInt16, 16>));
+static_assert(sizeof(Partitioned<UInt16, 16, 8>) == sizeof(PlainUncounted<UInt16, 16>));
+
+/// And dropping the counter is what makes it smaller than a table that keeps one.
+static_assert(sizeof(Partitioned<UInt16, 16, 8>) < sizeof(Plain<UInt16, 16>));
template <typename Map>
void insertKeyValue(Map & map, typename Map::key_type key, UInt64 value)There was a problem hiding this comment.
Yeah, you're right, the counter slows the fill down a lot more than I thought. Applied your patch now, thanks!
…rallel aggregation example `hash` is static now, and clang-tidy rejects calling it through an instance (`readability-static-accessed-through-instance`), which failed the `Build (arm_tidy)` job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120024&sha=a585437dc47e09116473f1ff7791a6c4244b8916&name_0=PR&name_1=Build%20(arm_tidy) #120024 Co-Authored-By: Claude Fable 5.1 <[email protected]>
47abb80 to
d382e68
Compare
3adc7e0 to
65e42fc
Compare
The table was fixed at 256 buckets and always routed on the high bits of the hash a cell is placed by. Both become template parameters, defaulted so every existing instantiation keeps its type. `bits_for_bucket = 0` gives a single bucket: routing folds to a constant and every operation compiles down to what the single-level table does, so one map type can serve a serial and a partitioned build. `BucketHash` decouples bucket selection from cell placement. A `FixedHashMap` places by the key itself, so routing on the high bits of that would put a dense key range into one bucket. `PartitionedFixedHashMap` and `PartitionedFixedHashSet` route on the cache line of the cell instead, and share one flat table between the buckets: the buckets only partition the keys, which is what a build with one lock per bucket needs, while cells, offsets, iteration and serialization stay those of the plain table. The min/max bounds of the flat table are the one thing such writers would race on, so they are off while several buckets are filled and `restoreMinMaxOptimization` derives them again afterwards. `offsetInternal` still numbers cells across buckets and still computes the prefix sums on first use; `computeBucketPrefix` recomputes them for a caller that grows the table after reading offsets. `has`, `reserve`, `bucketFor`, `bucketRoutingHash`, `offsetInternalAtBucket` and `iterator::getRoutedBucket` are new. The `BucketPartitionedTable` concept spells out this interface and the tests assert it for every shape. `FixedHashTable::write` gets the `wb` argument it always lacked, and the fixed-range cells learn to read and write themselves, so the partitioned map and set round-trip. `HashTableTraits.h` loses the `HasConstructorOfNumberOfElements` specialization for a bare `TwoLevelHashTable`. It could never match, because a type pack cannot bind the bucket-count parameter, so the nullable two-level aggregation variants never took a size hint; a specialization that matched would start reserving 256 buckets from the hint for them. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…oLevel` `TwoLevelHashTable(const Source &)` is now constrained with `requires(!std::is_arithmetic_v<Source>)` so that an integer size hint picks the size-hint constructor. C++20 prefers the more constrained candidate, so with `using Base::Base` the inherited constructor won over the unconstrained one in `AggregationDataWithNullKeyTwoLevel`, and `convertToTwoLevel` copied the cells but dropped the NULL key group. The derived constructor gets the same constraint, so it hides the inherited one again and copies the NULL group onto `impls[0]`. The new gtest pins that, and pins which aggregation data types take a size hint. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… first lookup `offsetInternal` no longer checks whether the prefix sums exist. The caller computes them with `computeBucketPrefix` once the buckets stop growing, and `HashJoin::onBuildPhaseFinish` does that for its two-level maps, after `ConcurrentHashJoin` has merged the per-slot buckets into one map. That removes an acquire load from every offset read on the probe path, and the table drops the `std::once_flag` and the inline prefix array in favour of a vector that exists only once it is computed. `bits_for_bucket` is an `Int32`, and `bucketFor` stays public: it names the sub-table of a key, which for fixed-range storage is not the bucket the key routes to. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`HasConstructorOfNumberOfElements` had a specialization for a bare `TwoLevelHashTable` that could never match: a type pack cannot bind the bucket-count parameter. `AggregatedDataWithNullableUInt32KeyVoidTwoLevel` and its 64-bit twin build on a bare `TwoLevelHashTable`, so they were the only two-level variants `AggregatedDataVariants::init` created without a size hint. The specialization now spells the parameters out and matches, and the test pins the trait for those types. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…rallel aggregation example `hash` is static now, and clang-tidy rejects calling it through an instance (`readability-static-accessed-through-instance`), which failed the `Build (arm_tidy)` job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120024&sha=a585437dc47e09116473f1ff7791a6c4244b8916&name_0=PR&name_1=Build%20(arm_tidy) #120024 Co-Authored-By: Claude Fable 5.1 <[email protected]>
`offsetsByIteration`, `countByIteration` and `assertOffsetsAreUnique` only read the map, so they take it by const reference. That removes the `const_cast` in `SerializesTheFlatTableOnce`. The comment above the `TwoLevelHashTable` specialization in `HashTableTraits.h` states the present fact instead of the history. Comment sentences longer than 25 words in `BucketPartitionedTable.h`, `AggregatedData.h`, `HashJoin.h` and the three tests are split, with every fact kept. Behaviour is unchanged. The 35 gtests of the change pass, and clang-tidy reports nothing on the touched lines. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comments only. The code of `TwoLevelHashTable.h` and `PartitionedFixedHashMap.h` is byte-identical after comment stripping with `gcc -fpreprocessed`. The `computeBucketPrefix` rule is stated once, on `computeBucketPrefix`. The class header points there, and `offsetInternal` names only its precondition. The `bucketFor` comment drops the routing formula that `BucketPartitionedTable.h` already gives. Sentences longer than 25 words in the class header, `FixedRangeStorage`, `prefetchByHash`, `forEachMapped` and the `PartitionedFixedHashMap` alias are split, with every fact kept. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Pad `FixedHashMapCell` so a 12-byte payload becomes 16 bytes and divides the cache line. `computeBucketPrefix` publishes the prefix, so it is no longer const. The bucket-count parameter is `size_t BITS_FOR_BUCKET`. Co-authored-by: Cursor <[email protected]>
65e42fc to
5952587
Compare
`PartitionedFixedHashMap` and `PartitionedFixedHashSet` are now aliases of a standalone `PartitionedFixedHashTable`: one flat `FixedHashTable` whose keys are split into buckets by the cache line of their cell. It satisfies `BucketPartitionedTable`, but it is not a `TwoLevelHashTable`. `TwoLevelHashTable` loses its second storage mode: `IsFixedRangeTable`, `FixedRangeStorage`, `FixedRangeBucketHash`, the `BucketHash` parameter, `getRoutedBucket`, `serializedPartitionCount` and the min/max methods. Its buckets are a plain `Impl impls[NUM_BUCKETS]` again, as on master. It keeps an identity `bucketRoutingHash`: `FixedHashTable::find(key, hash)` indexes by the hash, so the hash of a fixed map must stay the key, and routing needs a hook of its own. The iterator of the new class reports the routed bucket from `getBucket`, so one name serves both shapes. `BucketPartitionedTable` now also requires `computeBucketPrefix` and the iterator's `getBucket`. The tests of the removed `BucketHash` parameter are deleted. Related: #120024 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ptyCell` test The merge of #120024 kept the concept requirements on `computeBucketPrefix` and the iterator's `getBucket`, but lost the two sentences of `BucketPartitionedTable` that explain them. They are back, without the mentions of `PartitionedFixedHashTable`, which this layer deletes. `IsEmptyCellFindsTheBucketFromTheCellHash` tests the plain `TwoLevelHashTable` only, so it applies here unchanged and is restored as #120024 has it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s comment `write`, `writeText`, `read` and `readText` forwarded to the flat table, but `FixedHashMapCell` has no such methods, so the map flavour could not compile them. Nothing calls them, so they go, together with the round trip of the set flavour in the test. The class comment claimed that the join can hold the table wherever it holds a `TwoLevelHashTable`. It cannot: the table has no `iteratorAt`, and its iteration does not follow the buckets, so a caller that scans by bucket has to handle it separately. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FixedHashTableCell` gets back the text it has on `master`: its `write`, `writeText`, `read` and `readText` methods go, together with its constructor from a cell and a state. `FixedHashMapCell` loses the same constructor. `FixedHashTable::write` goes back to calling `writeVarUInt` without the `wb` argument, as on `master`. Only `FixedHashTable::read`, `readText` and `write` used any of them, and nothing instantiates those. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Copilot review overview
Review effort: Lite
Findings: 1
Open (5)
Makinghash()static and computing viaHash{}changes behavior (or breaks compilation) for any… · New The added logic does not always make the cell size a divisor of the cache line: when `fields_size >… · New The added logic does not always make the cell size a divisor of the cache line: when `fields_size >… · New The added logic does not always make the cell size a divisor of the cache line: when `fields_size >… · NewBucketPartitionedTabledocuments routing as `getBucketFromHash(bucketRoutingHash(key,… · New
What changed in this PR
This PR refactors ClickHouse hash-table bucketing to make TwoLevelHashTable configurable (bucket count/routing) and introduces bucket-partitioning for fixed-range tables to support concurrent fills with per-bucket locking, while removing the previous lazy/once-flag prefix computation from offset reads.
Changes:
- Make
TwoLevelHashTablesupport configurableBITS_FOR_BUCKET, removeonce_flagprefix initialization, and require explicitcomputeBucketPrefix()before offset reads. - Add
PartitionedFixedHashTable(+ map/set aliases) to provide bucket-based locking over a single flatFixedHashTable, routing by cache-line. - Update traits + aggregation/join integration and add gtests covering new invariants and concurrency behavior.
| File | Description |
|---|---|
| src/Interpreters/tests/gtest_aggregated_data_null_key_two_level.cpp | Adds regression/static-assert coverage for size-hint trait and null-key converting constructor behavior. |
| src/Interpreters/HashJoin/HashJoin.h | Adds a dispatcher to run computeBucketPrefix() only for two-level join variants. |
| src/Interpreters/HashJoin/HashJoin.cpp | Calls computeBucketPrefix() at build-finish so used-flag offset numbering is stable. |
| src/Interpreters/AggregatedData.h | Constrains converting ctor to avoid size-hint overload stealing and dropping NULL group. |
| src/Common/tests/gtest_two_level_hash_table_buckets.cpp | New tests for configurable bucket counts, offset uniqueness/prefix recompute, routing, and concurrency. |
| src/Common/tests/gtest_partitioned_fixed_hash_map.cpp | New tests validating fixed-table partitioning preserves flat-table semantics and routing invariants. |
| src/Common/examples/parallel_aggregation.cpp | Adjusts hashing callsite to use static MapTwoLevel::hash. |
| src/Common/HashTable/TwoLevelHashTable.h | Core change: configurable buckets, explicit prefix computation, static hash, new routing hooks, new has(). |
| src/Common/HashTable/TwoLevelHashMap.h | Plumbs BITS_FOR_BUCKET through wrappers; relies on base forEachMapped. |
| src/Common/HashTable/PartitionedFixedHashTable.h | New bucket-partitioning wrapper over a flat fixed table with cache-line routing. |
| src/Common/HashTable/PartitionedFixedHashSet.h | Adds PartitionedFixedHashSet alias. |
| src/Common/HashTable/PartitionedFixedHashMap.h | Adds PartitionedFixedHashMap alias. |
| src/Common/HashTable/HashTableTraits.h | Fixes size-hint trait matching for TwoLevelHashTable/wrappers with non-type template params. |
| src/Common/HashTable/HashSet.h | Plumbs BITS_FOR_BUCKET through TwoLevelHashSet wrappers. |
| src/Common/HashTable/FixedHashTable.h | Renames min/max trust flag and adds restoreMinMaxOptimization() for post-fill recovery. |
| src/Common/HashTable/FixedHashMap.h | Pads fixed-map cells to cache-line-friendly sizes and adds helper utilities for padding. |
| src/Common/HashTable/BucketPartitionedTable.h | Adds a concept specifying the bucket-partitioned table interface used by concurrent fillers. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| /// Static so that a caller can route keys to buckets without a table at hand. `Hash` must be stateless. | ||
| static size_t hash(const Key & x) { return Hash{}(x); } |
| /// Smallest size >= `size` that divides `line`. A larger `size` rounds up to a multiple of `line`. | ||
| constexpr size_t roundUpToCacheLineDivisor(size_t size, size_t line) | ||
| { | ||
| if (size == 0 || line == 0) | ||
| return size; | ||
|
|
||
| if (size > line) | ||
| { | ||
| const size_t remainder = size % line; | ||
| return remainder == 0 ? size : size + (line - remainder); | ||
| } | ||
|
|
||
| for (size_t candidate = size; candidate <= line; ++candidate) | ||
| if (line % candidate == 0) | ||
| return candidate; | ||
|
|
||
| return line; | ||
| } |
| static constexpr size_t fields_size = sizeof(FixedHashMapCellFields<Mapped>); | ||
| static constexpr size_t padded_size = roundUpToCacheLineDivisor(fields_size, DB::CH_CACHE_LINE_SIZE); |
|
|
||
| bool full; | ||
| Mapped mapped; | ||
| /// Tail bytes so the cell divides the cache line. Two keys that start on one line then share a bucket lock. |
| } | ||
|
|
||
| /// The bucket the key routes to. There are no sub-tables, so a scan split by bucket filters on it. | ||
| size_t getBucket() const { return getBucketFromHash(bucketRoutingHash(this->getHash(), 0)); } |
| template <typename K> | ||
| static size_t ALWAYS_INLINE bucketRoutingHash(const K & key, size_t /* hash_value */) | ||
| { | ||
| const UInt64 line = (static_cast<UInt64>(key) * sizeof(cell_type)) / DB::CH_CACHE_LINE_SIZE; |
There was a problem hiding this comment.
bucketRoutingHash is still routing by a synthetic cache-line number here: key * sizeof(cell_type) / 64 only matches the real cache line if cell 0 starts on a CH_CACHE_LINE_SIZE boundary. FixedHashTable::alloc() still calls Allocator::alloc(NUM_CELLS * sizeof(Cell)) with no explicit alignment, so the backing array is only max_align_t-aligned. With 16-byte cells and buf % 64 == 16, keys 3 and 4 both touch the same real cache line, but this formula routes them as different lines and therefore under different bucket locks. That breaks the core safety contract of PartitionedFixedHashTable even after padding the cell size. Please either make the fixed-table buffer cache-line aligned or fold the real base-address offset into routing, and strengthen the test to compare buckets against reinterpret_cast<uintptr_t>(cell_ptr) / CH_CACHE_LINE_SIZE instead of the same synthetic formula used by the implementation.
…nedFixedHashSet` Several threads fill these tables at once, one lock per bucket. The atomic counter of `FixedHashTableStoredSize` is then the one cache line that every thread writes, and it shares that line with `buf`. A `key16` fill of 64M rows from 64 threads took 11.2 ms with the counter and 6.1 ms without it. `size` now walks the cells, so it must not be called during the fill. The aggregator's tables keep the atomic. The patch is from the review: #120024 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…elHashTable` Of the new bucket API, `TwoLevelHashTable` keeps only `BITS_FOR_BUCKET` and `computeBucketPrefix`. Its `HasConstructorOfNumberOfElements` specialization and `FixedHashMapCell` are as on `master`. Only a partitioned map pads its cells. Partitioned tables assume that their buffer starts on a cache line. `HashJoin::onBuildPhaseFinish` drops the `twoLevelMapIsUsed` check, because `MapsTemplate::computeBucketPrefix` already skips single-level maps. The bucket gtests merge into one file, and a stateless test replaces the `NULL` group gtest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
TwoLevelHashTable choose its bucket count and bucket hash, and share one fixed-range table between bucketsTwoLevelHashTable choose its bucket count, and add PartitionedFixedHashTable
nickitat
left a comment
There was a problem hiding this comment.
For the second round I mostly just skimmed through the changes. If you want me to check something with more rigor - pls tell. Otherwise I'm leaving it to the auto review )
`test_iceberg_narrow_manifest_bounds` failed in `Integration tests (amd_llvm_coverage, 1/8)` on 2eb21c1. The test failed on every `master` run from #122679 until #122895 fixed it. The CI run of 2eb21c1 started before that fix was merged, so it tested a merge without it. A re-run tests that same merge again, so only a new run can pick up the fix. This merge is clean and does not change the diff of the pull request. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120024&sha=2eb21c1bc9f02e703ede180dc854745e7b1bf68d&name_0=PR Related: #122895 Co-Authored-By: Claude Opus 5.5 <[email protected]>



Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on
master, and #120011 sits on this.Related: #115605
Related: #115605 (comment)
TwoLevelHashTablesplits its cells over 256 buckets, and each bucket is its own hash table.offsetInternalnumbers the cells across all buckets. It reads a 2 KB array of prefix sums. The first reader fills that array behind aonce_flag.FixedHashMapis one flat array indexed by the key, with no buckets.Every offset read of a non-zero cell pays for an acquire load on that
once_flag. Onmasterthe only reader isHashJoin, and its buckets have stopped changing by the time it reads.TwoLevelHashMap,TwoLevelHashSetand their table and saved-hash variants do not pass the bucket count through, so a caller cannot ask for one bucket. A caller that fills aFixedHashMapfrom several threads has no bucket to lock, and routing on the high bits of the key would put a dense key range into one bucket.These six wrappers now take a trailing
BITS_FOR_BUCKET, defaulted to 8, so every existing instantiation keeps its 256 buckets. With 0 bits there is one bucket, routing is a constant, and offsets need no prefix sums. Theonce_flaggoes, and the prefix array becomes a vector.offsetInternalno longer fills it. The caller runscomputeBucketPrefixafter the last insert and before any thread reads offsets.HashJoin::onBuildPhaseFinishdoes that through a small helper inHashJoin.h, before it sizes the used flags. That is the only join change, and nothing else onmasteruses the new types.PartitionedFixedHashTableis a new class over one flatFixedHashTable, andPartitionedFixedHashMapandPartitionedFixedHashSetare its map and set. Its buckets only choose which lock a key is inserted under, and the caller has one lock per bucket.FixedHashTable::find(key, hash)indexes by the hash, so for a fixed table the hash has to stay the key. The high bits of the hash are then the high bits of the key, sobucketOfKeydoes not route on them. It routes a key by the cache line that its cell starts on. This assumes that the cell buffer starts on a cache line.FixedHashTable::allocdoes not ask for that alignment. If the buffer is not aligned, the results stay correct, but two buckets can write to one line. With more than one bucket, the map usesPartitionedFixedHashMapCell: aFixedHashMapCellpadded so that its size divides the cache line or is a multiple of it. In that case the min and max bounds stay off untilrestoreMinMaxOptimizationderives them after the fill. The map and the set are built onFixedHashMapWithSizeBitsAndCalculatedSizeandFixedHashSetWithSizeBitsAndCalculatedSize. These keep no element counter, sosizeandemptywalk the cells.PartitionedFixedHashTableis not aTwoLevelHashTable: it has noiteratorAt, and it iterates in cell order, not bucket by bucket.The concept
BucketPartitionedTablestates what a caller relies on when it fills a table bucket by bucket.TwoLevelHashMap,PartitionedFixedHashMapandPartitionedFixedHashSetsatisfy it. It requires the member types,hash,NUM_BUCKETS,findandemplacewith and without a hash,computeBucketPrefix,offsetInternal,size,emptyand the buffer-size getters,beginandend, and an iteratorgetBucketthat returns the bucket of the key it points to. It also requires the free functiongetBucketOfKey(key, hash). That function takes the bucket from the hash for aTwoLevelHashTable, and from the key for aPartitionedFixedHashTable.A type pack cannot bind the new
size_tparameter, so theHasConstructorOfNumberOfElementsspecializations forTwoLevelHashMapTableandTwoLevelHashSetTablenow name every parameter. The converting constructor ofTwoLevelHashTableaccepts only a non-arithmetic source, so an integer argument always means a size hint.AggregationDataWithNullKeyTwoLevelputs the same constraint on its own converting constructor. Otherwise the more constrained constructor that it inherits fromTwoLevelHashTablewould win, andconvertToTwoLevelwould drop the NULL key group. Aggregation is otherwise unchanged:NUM_BUCKETSandimpls[i]mean what they meant, and it never reads offsets.FixedHashSettakes aSizeparameter.FixedHashTablerenamesonly_emplace_was_used_to_insert_datatocan_trust_min_max_values.Changelog category (leave one):
Workflow [PR]
Sync PR [sync-upstream/pr/120024]
Version info
26.10.1.1194-master(included in26.10and later)