Skip to content

Commit 039d5de

Browse files
Merge pull request #128972 from harikrishnan94/packed-string-keys-parallel-hash-join
Faster hash joins on a single `String` key with a large right side
2 parents 48f9d3b + b21b312 commit 039d5de

30 files changed

Lines changed: 2204 additions & 2 deletions

‎src/Client/BuzzHouse/Generator/SessionSettings.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,7 @@ std::unordered_map<String, CHSetting> performanceSettings
465465
{"enable_lazy_columns_replication", trueOrFalseSetting},
466466
{"enable_optimize_predicate_expression_to_final_subquery", trueOrFalseSetting},
467467
{"enable_packed_string_keys_in_aggregation", trueOrFalseSetting},
468+
{"enable_packed_string_keys_in_hash_join", trueOrFalseSetting},
468469
{"enable_parallel_replicas", trueOrFalseSetting},
469470
{"enable_parallel_single_level_merge", trueOrFalseSetting},
470471
{"enable_producing_buckets_out_of_order_in_aggregation", trueOrFalseSetting},
@@ -2453,6 +2454,7 @@ void loadFuzzerServerSettings(const FuzzConfig & fc)
24532454
"min_insert_block_size_rows",
24542455
"min_joined_block_size_rows",
24552456
"min_outstreams_per_resize_after_split",
2457+
"min_rows_for_packed_string_keys_in_hash_join",
24562458
"min_table_rows_to_use_projection_index",
24572459
"query_cache_max_entries",
24582460
"query_cache_min_query_runs",

‎src/Common/ProfileEvents.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,8 @@
553553
M(JoinNonJoinedTransformRowCount, "Number of non-joined rows emitted by NonJoinedBlocksTransform.", ValueType::Number) \
554554
M(JoinNonJoinedHashTableScans, "Number of times a RIGHT or FULL hash join scanned its hash table for non-joined rows.", ValueType::Number) \
555555
M(JoinNonJoinedHashTableScansSkipped, "Number of times a RIGHT or FULL hash join skipped scanning its hash table for non-joined rows, because every right key in the scanned part had matched.", ValueType::Number) \
556+
M(JoinPackedStringKeysInline, "Number of single `String` join keys of up to 15 bytes that hash joins inserted inline into their hash tables (see `enable_packed_string_keys_in_hash_join`). A join with `OR` inserts a key for each condition. A row is counted again when it is inserted again: after a `grace_hash` join splits its buckets, or after a spilling join switches to `grace_hash`.", ValueType::Number) \
557+
M(JoinPackedStringKeysHashed, "Number of single `String` join keys of 16 bytes or more that hash joins inserted into their hash tables as their 128-bit `SipHash` (see `enable_packed_string_keys_in_hash_join`). A join with `OR` inserts a key for each condition. A row is counted again when it is inserted again: after a `grace_hash` join splits its buckets, or after a spilling join switches to `grace_hash`.", ValueType::Number) \
556558
M(JoinDelayedJoinedTransformBlockCount, "Number of blocks emitted by DelayedJoinedBlocksWorkerTransform.", ValueType::Number) \
557559
M(JoinDelayedJoinedTransformRowCount, "Number of rows emitted by DelayedJoinedBlocksWorkerTransform.", ValueType::Number) \
558560
M(JoinSpillingHashJoinSwitchedToGraceJoin, "Number of times a HashJoin was switched to GraceHashJoin due to memory limit in SpillingHashJoin.", ValueType::Number) \

‎src/Core/Settings.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10784,6 +10784,26 @@ Enable converting the hash table to a flat array for joins when the key is a sin
1078410784
Use hash tables that store the join keys alone, without a reference to a right row, for joins whose result can never contain a value taken from a right row: `LEFT ANTI`, and `LEFT SEMI` when no right column is selected. Such a table has a smaller cell and lets the right blocks be dropped instead of stored.
1078510785
)", 0, \
1078610786
{"26.9", false, true, "New setting to store the join keys alone, without a reference to a right row, in the hash tables of joins whose result can never contain a value taken from a right row (`LEFT ANTI`, and `LEFT SEMI` when no right column is selected)."}) \
10787+
DECLARE(Bool, enable_packed_string_keys_in_hash_join, true, R"(
10788+
In `hash`, `parallel_hash` and `grace_hash` joins on a single `String` key, store each key in the hash table as a 16-byte value. This includes a join with `OR` whose every condition has a single `String` key. It also includes a `hash` or `parallel_hash` join after it is converted to `grace_hash` to spill to disk.
10789+
10790+
A key of up to 15 bytes is stored inline and compared exactly. A key of 16 bytes or more is stored as its 128-bit `SipHash`. One bit of the hash marks the key as hashed, so two such keys are compared by their other 127 bits. In both cases the hash table keeps no separate copy of the string.
10791+
10792+
Two different keys of 16 bytes or more whose hashes have the same 127 bits are matched as equal. For N distinct keys the probability of that is about N^2/2^128. Disable the setting to compare the keys exactly.
10793+
10794+
The hash tables are smaller, so a join reaches `max_bytes_in_join` and `max_bytes_before_external_join` later.
10795+
10796+
The setting does not apply to `FixedString` keys or to `LowCardinality(Nullable(String))` keys. A join on a non-nullable `LowCardinality(String)` key can use a hash table of the key's dictionary instead. This needs a join that has one condition, is not `ASOF` and builds its hash table as one part: a `grace_hash` join, or a `hash` join with the serial layout (see `parallel_hash_join_threshold` and `hash_join_layout`). Tables with the `Join` engine, `joinGet` and joins that run from a serialized query plan keep exact keys. So does a join whose right side is estimated at fewer rows than `min_rows_for_packed_string_keys_in_hash_join`.
10797+
)", 0, \
10798+
{"26.11", false, true, "New setting to store the single `String` key of `hash`, `parallel_hash` and `grace_hash` joins in 16 bytes: inline up to 15 bytes, as a 127-bit `SipHash` for longer keys."}) \
10799+
DECLARE(UInt64, min_rows_for_packed_string_keys_in_hash_join, 100'000, R"(
10800+
The minimum number of rows in the right side of a join for `enable_packed_string_keys_in_hash_join` to apply. A join whose right side is estimated at fewer rows compares its `String` keys exactly. The hash table of a small right side stays in the CPU cache, so packed keys save little there. Hashing the keys of 16 bytes or more costs more than that.
10801+
10802+
The estimate is the number of right rows seen in an earlier run of the same join, when `collect_hash_table_stats_during_joins` keeps such statistics. Otherwise it is the row estimate of the query optimizer. `parallel_hash_join_threshold` uses the same estimate. A join without an estimate uses packed keys.
10803+
10804+
0 means no minimum.
10805+
)", 0, \
10806+
{"26.11", 0, 100'000, "New setting: `enable_packed_string_keys_in_hash_join` applies only when the right side of the join is estimated at 100000 rows or more, or has no estimate."}) \
1078710807
DECLARE(UInt64, query_plan_max_limit_for_join_lazy_indexing, 1000, R"(Control maximum limit value that allows to use query plan for lazy indexing optimization in JOIN. If zero, there is no limit.
1078810808
)", 0, \
1078910809
{"26.6", 1000, 1000, "Added new setting to control maximum limit value that allows to use query plan for lazy join indexing optimization. If zero, there is no limit"}) \

‎src/Interpreters/HashJoin/HashJoin.cpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,11 @@ HashJoin::HashJoin(
527527
throw Exception(ErrorCodes::LOGICAL_ERROR, "HashJoin cannot choose JOIN method without keys");
528528

529529
data->type = build_layout.two_level ? toTwoLevelType(*selected_join_method) : *selected_join_method;
530+
if (table_join->enablePackedStringKeysInHashJoin() && (data->type == Type::key_string || data->type == Type::two_level_key_string))
531+
{
532+
data->type = data->type == Type::key_string ? Type::key_packed_string : Type::two_level_key_packed_string;
533+
LOG_TRACE(log, "{}Using packed keys for the single String join key", instance_log_id);
534+
}
530535

531536
LOG_TRACE(log, "{}Join hash table type: {}", instance_log_id, data->type);
532537
LOG_TEST(

‎src/Interpreters/HashJoin/HashJoin.h‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,13 +354,16 @@ class HashJoin : public IJoin
354354
M(range8_key64) \
355355
M(range16_key64) \
356356
M(range17_key64) \
357-
M(range18_key64)
357+
M(range18_key64) \
358+
M(two_level_key_packed_string) \
359+
M(key_packed_string)
358360

359361
/// Used for reading from StorageJoin and applying joinGet function. The single-LowCardinality-key
360362
/// maps store key values in maps physically identical to their non-LowCardinality counterparts, so
361363
/// they are read back the same way (the output key column is the parent LowCardinality type).
362364
/// The keysN maps hold the key columns packed into one fixed-width blob, so each key column is
363365
/// recovered from its own byte range. `hashed` is absent: its map key is a hash of the values.
366+
/// The packed `String` maps are absent too, because a key of 16 bytes or more is stored as its hash.
364367
/// Only the serial types are listed: a `JoinSource` reads a `StorageJoin` map, and `StorageJoin`
365368
/// always builds with the serial layout.
366369
#define APPLY_FOR_JOIN_VARIANTS_LIMITED(M) \
@@ -388,7 +391,8 @@ class HashJoin : public IJoin
388391
M(two_level_keys64 __VA_OPT__(,) __VA_ARGS__) \
389392
M(two_level_keys128 __VA_OPT__(,) __VA_ARGS__) \
390393
M(two_level_keys256 __VA_OPT__(,) __VA_ARGS__) \
391-
M(two_level_hashed __VA_OPT__(,) __VA_ARGS__)
394+
M(two_level_hashed __VA_OPT__(,) __VA_ARGS__) \
395+
M(two_level_key_packed_string __VA_OPT__(,) __VA_ARGS__)
392396

393397
/// The packed fixed-width maps, `keys32` to `keys256`, hold the keys of a clause if all of them are fixed-width
394398
/// and take at most this many bytes together.
@@ -509,6 +513,9 @@ class HashJoin : public IJoin
509513
std::shared_ptr<JoinFixedHashMapWithSizeBits<UInt64, Mapped, 16>> range16_key64;
510514
std::shared_ptr<JoinFixedHashMapWithSizeBits<UInt64, Mapped, 17>> range17_key64;
511515
std::shared_ptr<JoinFixedHashMapWithSizeBits<UInt64, Mapped, 18>> range18_key64;
516+
/// A single `String` key as a `PackedStringJoinKey`, see `enable_packed_string_keys_in_hash_join`.
517+
std::shared_ptr<JoinTwoLevelHashMap<UInt128, Mapped, UInt128HashCRC32>> two_level_key_packed_string;
518+
std::shared_ptr<JoinHashMap<UInt128, Mapped, UInt128HashCRC32>> key_packed_string;
512519

513520
void create(Type which)
514521
{

‎src/Interpreters/HashJoin/HashJoinMethodsImpl.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
namespace ProfileEvents
2020
{
2121
extern const Event HashJoinPreallocatedElementsInHashTables;
22+
extern const Event JoinPackedStringKeysInline;
23+
extern const Event JoinPackedStringKeysHashed;
2224
}
2325

2426
namespace DB
@@ -367,6 +369,13 @@ BuildResult insertFromBlockImplTypeCase(
367369
};
368370

369371
slots.insert(per_slot, insert_slot);
372+
373+
/// `insertSlotRows` takes a key getter that is not trivially copyable by reference, so these counts cover all slots.
374+
if constexpr (requires { key_getter.hashed_keys; })
375+
{
376+
ProfileEvents::increment(ProfileEvents::JoinPackedStringKeysInline, key_getter.emplaced_keys - key_getter.hashed_keys);
377+
ProfileEvents::increment(ProfileEvents::JoinPackedStringKeysHashed, key_getter.hashed_keys);
378+
}
370379
return result;
371380
}
372381

‎src/Interpreters/HashJoin/KeyGetter.h‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@
22
#include <Interpreters/HashJoin/HashJoin.h>
33
#include <Common/ColumnsHashing.h>
44
#include <Common/HashTable/Prefetching.h>
5+
#include <Common/SipHash.h>
56
#include <Columns/ColumnLowCardinality.h>
7+
#include <Columns/ColumnString.h>
68
#include <Columns/ColumnsNumber.h>
9+
#include <base/PackedStringRef.h>
710

811
#include <algorithm>
12+
#include <bit>
913
#include <concepts>
1014
#include <span>
1115

@@ -457,6 +461,98 @@ struct HashMethodHashedJoinKey : public ColumnsHashing::columns_hashing_impl::Ha
457461
void buildKeys(size_t begin, size_t end, UInt128 * keys, const UInt8 * skip) { key.buildRange(begin, end, keys, skip); }
458462
};
459463

464+
/// The 16-byte key of a single `String` join key in the `key_packed_string` and `two_level_key_packed_string` maps.
465+
///
466+
/// - Up to 15 bytes: the `UnhashedPackedStringRef` of the string. It is exact: byte 15 holds the length, and the bytes
467+
/// past the end are zero. The empty string is the zero key.
468+
/// - 16 bytes or more: the unkeyed `sipHash128Padded` of the string with bit 7 of byte 15 set. No short key has that
469+
/// bit set, so a hashed key never equals a short one. Two long strings whose other 127 hash bits match share a key.
470+
///
471+
/// `build` and `buildRange` read up to 16 bytes from the start of a string; the chars of a `ColumnString` have that
472+
/// padding.
473+
struct PackedStringJoinKey
474+
{
475+
static constexpr size_t max_inline_size = UnhashedPackedStringRef::MAX_SMALL_LEN;
476+
477+
/// Bit 7 of byte 15, which is in `items[1]` on both byte orders.
478+
static constexpr UInt64 hashed_flag = UInt64(UnhashedPackedStringRef::LARGE_TAG_BYTE)
479+
<< (std::endian::native == std::endian::little ? 56 : 0);
480+
481+
static ALWAYS_INLINE UInt128 build(const char * data, size_t size)
482+
{
483+
if (size <= max_inline_size)
484+
return std::bit_cast<UInt128>(UnhashedPackedStringRef::buildShort(data, size));
485+
486+
UInt128 key = sipHash128Padded(data, size);
487+
key.items[1] |= hashed_flag;
488+
return key;
489+
}
490+
491+
/// `keys[i - begin]` = the key of row `i` of a `ColumnString`, for the rows [begin, end). The rows `i` with
492+
/// `skip[i] != 0` are not hashed, and their keys are unspecified. On aarch64 and on x86 with AVX2 it hashes long
493+
/// strings 8 at a time: 4 in NEON lanes and 4 in general registers, or all 8 in AVX2 lanes.
494+
static void buildRange(
495+
const char * chars, const IColumn::Offset * offsets, size_t begin, size_t end, UInt128 * __restrict keys, const UInt8 * skip);
496+
};
497+
498+
/// Key getter of `key_packed_string` and `two_level_key_packed_string`. It builds the `PackedStringJoinKey` of a row,
499+
/// or reads keys built ahead, see `PreparedJoinKeys`.
500+
template <typename Value, typename Mapped>
501+
struct HashMethodPackedStringJoinKey : public ColumnsHashing::columns_hashing_impl::HashMethodBase<
502+
HashMethodPackedStringJoinKey<Value, Mapped>,
503+
Value,
504+
Mapped,
505+
/*consecutive_keys_optimization=*/false,
506+
use_offset>,
507+
public PreparedJoinKeys<HashMethodPackedStringJoinKey<Value, Mapped>>
508+
{
509+
using Base = ColumnsHashing::columns_hashing_impl::
510+
HashMethodBase<HashMethodPackedStringJoinKey<Value, Mapped>, Value, Mapped, false, use_offset>;
511+
512+
/// Hashing a long string is not cheap, but `true` lets the join loops prefetch: after `prepareRows`, they build
513+
/// each key once.
514+
static constexpr bool has_cheap_key_calculation = true;
515+
516+
const IColumn::Offset * offsets;
517+
const UInt8 * chars;
518+
519+
/// The number of `emplaceKey` calls, and how many of their keys are hashed.
520+
size_t emplaced_keys = 0;
521+
size_t hashed_keys = 0;
522+
523+
HashMethodPackedStringJoinKey(const ColumnRawPtrs & key_columns, const Sizes &, const ColumnsHashing::HashMethodContextPtr &)
524+
: HashMethodPackedStringJoinKey(assert_cast<const ColumnString &>(*key_columns[0]))
525+
{
526+
}
527+
528+
explicit HashMethodPackedStringJoinKey(const ColumnString & column)
529+
: PreparedJoinKeys<HashMethodPackedStringJoinKey>(column.size())
530+
, offsets(column.getOffsets().data())
531+
, chars(column.getChars().data())
532+
{
533+
}
534+
535+
ALWAYS_INLINE UInt128 buildKey(size_t row) const
536+
{
537+
return PackedStringJoinKey::build(
538+
reinterpret_cast<const char *>(chars) + offsets[ssize_t(row) - 1], offsets[row] - offsets[ssize_t(row) - 1]);
539+
}
540+
541+
void buildKeys(size_t begin, size_t end, UInt128 * keys, const UInt8 * skip) const
542+
{
543+
PackedStringJoinKey::buildRange(reinterpret_cast<const char *>(chars), offsets, begin, end, keys, skip);
544+
}
545+
546+
template <typename Data>
547+
ALWAYS_INLINE typename Base::EmplaceResult emplaceKey(Data & data, size_t row, Arena & pool)
548+
{
549+
auto result = Base::emplaceKey(data, row, pool);
550+
++emplaced_keys;
551+
hashed_keys += (result.getKey().items[1] & PackedStringJoinKey::hashed_flag) != 0;
552+
return result;
553+
}
554+
};
555+
460556
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<HashJoin::Type::key8, Value, Mapped>
461557
{
462558
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt8, false, use_offset>;
@@ -555,6 +651,14 @@ template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<HashJoin:
555651
{
556652
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt16, false, use_offset>;
557653
};
654+
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<HashJoin::Type::two_level_key_packed_string, Value, Mapped>
655+
{
656+
using Type = HashMethodPackedStringJoinKey<Value, Mapped>;
657+
};
658+
template <typename Value, typename Mapped> struct KeyGetterForTypeImpl<HashJoin::Type::key_packed_string, Value, Mapped>
659+
{
660+
using Type = HashMethodPackedStringJoinKey<Value, Mapped>;
661+
};
558662
#define KEYGETTER_RANGE_IMPL(TYPE, FIELD_TYPE) \
559663
template <typename Value, typename Mapped> \
560664
struct KeyGetterForTypeImpl<HashJoin::Type::TYPE, Value, Mapped> \

0 commit comments

Comments
 (0)