Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::GroupedAggregateHashTable Class Reference
Inheritance diagram for duckdb::GroupedAggregateHashTable:
Collaboration diagram for duckdb::GroupedAggregateHashTable:

Classes

struct  AggregateDictionaryState
struct  AggregateHTAppendState
 Append state. More...

Public Member Functions

 GroupedAggregateHashTable (ClientContext &context, Allocator &allocator, vector< LogicalType > group_types, vector< LogicalType > payload_types, const vector< BoundAggregateExpression * > &aggregates, idx_t initial_capacity=InitialCapacity(), idx_t radix_bits=0, TupleDataValidityType group_validity=TupleDataValidityType::CAN_HAVE_NULL_VALUES)
 GroupedAggregateHashTable (ClientContext &context, Allocator &allocator, vector< LogicalType > group_types, vector< LogicalType > payload_types, vector< AggregateObject > aggregates, idx_t initial_capacity=InitialCapacity(), idx_t radix_bits=0, TupleDataValidityType group_validity=TupleDataValidityType::CAN_HAVE_NULL_VALUES)
 GroupedAggregateHashTable (ClientContext &context, Allocator &allocator, vector< LogicalType > group_types, TupleDataValidityType group_validity=TupleDataValidityType::CAN_HAVE_NULL_VALUES)
shared_ptr< TupleDataLayout > GetLayoutPtr ()
 Get the layout of this HT.
const TupleDataLayout & GetLayout () const
idx_t Count () const
 Number of groups in the HT.
idx_t Capacity () const
 Current capacity of the HT.
idx_t ResizeThreshold () const
 Threshold at which to resize the HT.
idx_t AddChunk (DataChunk &groups, DataChunk &payload, const unsafe_vector< idx_t > &filter)
idx_t AddChunk (DataChunk &groups, Vector &group_hashes, DataChunk &payload, const unsafe_vector< idx_t > &filter)
idx_t AddChunk (DataChunk &groups, DataChunk &payload, AggregateType filter)
optional_idx TryAddCompressedGroups (DataChunk &groups, DataChunk &payload, const unsafe_vector< idx_t > &filter)
optional_idx TryAddDictionaryGroups (DataChunk &groups, DataChunk &payload, const unsafe_vector< idx_t > &filter)
optional_idx TryAddConstantGroups (DataChunk &groups, DataChunk &payload, const unsafe_vector< idx_t > &filter)
void FetchAggregates (DataChunk &groups, DataChunk &result)
 Fetch the aggregates for specific groups from the HT and place them in the result.
void InitializeScan (AggregateHTScanState &scan_state)
bool Scan (AggregateHTScanState &scan_state, DataChunk &distinct_rows, DataChunk &payload_rows)
idx_t FindOrCreateGroups (DataChunk &groups, Vector &group_hashes, Vector &addresses_out, SelectionVector &new_groups_out)
idx_t FindOrCreateGroups (DataChunk &groups, Vector &addresses_out, SelectionVector &new_groups_out)
void FindOrCreateGroups (DataChunk &groups, Vector &addresses_out)
const PartitionedTupleData & GetPartitionedData () const
unique_ptr< PartitionedTupleData > AcquirePartitionedData ()
void Abandon ()
void Repartition ()
shared_ptr< ArenaAllocator > GetAggregateAllocator ()
void Resize (idx_t size)
 Resize the HT to the specified size. Must be larger than the current size.
void ClearPointerTable ()
 Resets the pointer table of the HT to all 0's.
void SetRadixBits (idx_t radix_bits)
 Set the radix bits for this HT.
idx_t GetRadixBits () const
 Get the radix bits for this HT.
idx_t GetSinkCount () const
 Get the total number of tuples sunk into this HT.
idx_t GetMaterializedCount () const
 Get the total number of tuples materialized currently in this HT.
void SkipLookups ()
 Skips lookups from here on out.
void EnableHLL (bool enable)
 Enable/disable HLL.
bool HLLEnabled () const
 Whether HLL is enabled.
idx_t GetHLLUpperBound () const
 Get HLL count.
void Combine (GroupedAggregateHashTable &other)
 Executes the filter(if any) and update the aggregates.
void Combine (TupleDataCollection &other_data, optional_ptr< atomic< double > > progress=nullptr)
Public Member Functions inherited from duckdb::BaseAggregateHashTable
 BaseAggregateHashTable (ClientContext &context, Allocator &allocator, const vector< AggregateObject > &aggregates, vector< LogicalType > payload_types)

Static Public Member Functions

static idx_t InitialCapacity ()
 Initial capacity of the HT.
static idx_t GetCapacityForCount (idx_t count)
 Capacity that can hold 'count' entries without resizing.
static idx_t ResizeThreshold (idx_t capacity)

Static Public Attributes

static constexpr double LOAD_FACTOR = 1.5
 The hash table load factor, when a resize is triggered.

Private Member Functions

 GroupedAggregateHashTable (const GroupedAggregateHashTable &)=delete
 Disabled the copy constructor.
void Destroy ()
 Destroy the HT.
void InitializePartitionedData ()
 Initializes the PartitionedTupleData.
void InitializeUnpartitionedData ()
 Initializes the PartitionedTupleData that only has 1 partition.
idx_t ApplyBitMask (hash_t hash) const
 Apply bitmask to get the entry in the HT.
void ReinsertTuples (PartitionedTupleData &data)
 Reinserts tuples (triggered by Resize).
void UpdateAggregates (DataChunk &payload, const unsafe_vector< idx_t > &filter)
idx_t FindOrCreateGroupsInternal (DataChunk &groups, Vector &group_hashes, Vector &addresses, SelectionVector &new_groups)
 Does the actual group matching / creation.
void Verify ()
 Verify the pointer table of the HT.

Private Attributes

ClientContext & context
RowMatcher row_matcher
 Efficiently matches groups.
idx_t radix_bits
 The number of radix bits to partition by.
unique_ptr< PartitionedTupleData > partitioned_data
 The data of the HT.
unique_ptr< PartitionedTupleData > unpartitioned_data
vector< ExpressionType > predicates
 Predicates for matching groups (always ExpressionType::COMPARE_EQUAL).
idx_t count
 The number of groups in the HT.
idx_t capacity
 The capacity of the HT. This can be increased using GroupedAggregateHashTable::Resize.
AllocatedData hash_map
 The hash map (pointer table) of the HT: allocated data and pointer into it.
ht_entry_t * entries
idx_t hash_offset
 Offset of the hash column in the rows.
hash_t bitmask
 Bitmask for getting relevant bits from the hashes to determine the position.
idx_t sink_count
 How many tuples went into this HT (before de-duplication).
bool skip_lookups
 If true, we just append, skipping HT lookups.
bool enable_hll
 Whether to enable HLL counting the hashes.
HyperLogLog hll
 The associated HLL.
shared_ptr< ArenaAllocator > aggregate_allocator
 The active arena allocator used by the aggregates for their internal state.
vector< shared_ptr< ArenaAllocator > > stored_allocators
 Owning arena allocators that this HT has data from.
struct duckdb::GroupedAggregateHashTable::AggregateHTAppendState state

Static Private Attributes

static constexpr idx_t UNPARTITIONED_RADIX_BITS_THRESHOLD = 3
 If we have this many or more radix bits, we use the unpartitioned data collection too.

Additional Inherited Members

Protected Attributes inherited from duckdb::BaseAggregateHashTable
Allocator & allocator
BufferManager & buffer_manager
shared_ptr< TupleDataLayout > layout_ptr
 A helper for managing offsets into the data buffers.
vector< LogicalType > payload_types
 The types of the payload columns stored in the hashtable.
AggregateFilterDataSet filter_set
 Intermediate structures and data for aggregate filters.

Constructor & Destructor Documentation

◆ GroupedAggregateHashTable() [1/3]

duckdb::GroupedAggregateHashTable::GroupedAggregateHashTable ( ClientContext & context,
Allocator & allocator,
vector< LogicalType > group_types,
vector< LogicalType > payload_types,
const vector< BoundAggregateExpression * > & aggregates,
idx_t initial_capacity = InitialCapacity(),
idx_t radix_bits = 0,
TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES )
146030 : GroupedAggregateHashTable(context, allocator, std::move(group_types), std::move(payload_types),
146031 AggregateObject::CreateAggregateObjects(bindings), initial_capacity, radix_bits,
146032 group_validity) {
146033}
vector< LogicalType > payload_types
The types of the payload columns stored in the hashtable.
Definition duckdb.cpp:145679
idx_t radix_bits
The number of radix bits to partition by.
Definition duckdb.cpp:145927

◆ GroupedAggregateHashTable() [2/3]

duckdb::GroupedAggregateHashTable::GroupedAggregateHashTable ( ClientContext & context,
Allocator & allocator,
vector< LogicalType > group_types,
vector< LogicalType > payload_types,
vector< AggregateObject > aggregates,
idx_t initial_capacity = InitialCapacity(),
idx_t radix_bits = 0,
TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES )
146054 : BaseAggregateHashTable(context_p, allocator, aggregate_objects_p, std::move(payload_types_p)), context(context_p),
146056 aggregate_allocator(make_shared_ptr<ArenaAllocator>(allocator)), state(*aggregate_allocator) {
146057 // Append hash column to the end and initialise the row layout
146058 group_types_p.emplace_back(LogicalType::HASH);
146059
146060 auto layout = make_shared_ptr<TupleDataLayout>();
146061 layout->Initialize(std::move(group_types_p), std::move(aggregate_objects_p), group_validity);
146062 layout_ptr = std::move(layout);
146063
146064 hash_offset = layout_ptr->GetOffsets()[layout_ptr->ColumnCount() - 1];
146065
146066 // Partitioned data and pointer table
146070 }
146071 Resize(initial_capacity);
146072
146073 // Predicates
146074 const auto expr_type =
146075 layout_ptr->AllValid() ? ExpressionType::COMPARE_EQUAL : ExpressionType::COMPARE_NOT_DISTINCT_FROM;
146076 predicates.resize(layout_ptr->ColumnCount() - 1, expr_type);
146077 row_matcher.Initialize(true, *layout_ptr, predicates);
146078}
shared_ptr< TupleDataLayout > layout_ptr
A helper for managing offsets into the data buffers.
Definition duckdb.cpp:145677
shared_ptr< ArenaAllocator > aggregate_allocator
The active arena allocator used by the aggregates for their internal state.
Definition duckdb.cpp:145957
void InitializePartitionedData()
Initializes the PartitionedTupleData.
Definition duckdb.cpp:146080
idx_t count
The number of groups in the HT.
Definition duckdb.cpp:145936
void Resize(idx_t size)
Resize the HT to the specified size. Must be larger than the current size.
Definition duckdb.cpp:146287
void InitializeUnpartitionedData()
Initializes the PartitionedTupleData that only has 1 partition.
Definition duckdb.cpp:146098
vector< ExpressionType > predicates
Predicates for matching groups (always ExpressionType::COMPARE_EQUAL).
Definition duckdb.cpp:145933
idx_t sink_count
How many tuples went into this HT (before de-duplication).
Definition duckdb.cpp:145948
idx_t hash_offset
Offset of the hash column in the rows.
Definition duckdb.cpp:145943
RowMatcher row_matcher
Efficiently matches groups.
Definition duckdb.cpp:145908
bool enable_hll
Whether to enable HLL counting the hashes.
Definition duckdb.cpp:145952
static constexpr idx_t UNPARTITIONED_RADIX_BITS_THRESHOLD
If we have this many or more radix bits, we use the unpartitioned data collection too.
Definition duckdb.cpp:145925
idx_t capacity
The capacity of the HT. This can be increased using GroupedAggregateHashTable::Resize.
Definition duckdb.cpp:145938
bool skip_lookups
If true, we just append, skipping HT lookups.
Definition duckdb.cpp:145950

◆ GroupedAggregateHashTable() [3/3]

duckdb::GroupedAggregateHashTable::GroupedAggregateHashTable ( ClientContext & context,
Allocator & allocator,
vector< LogicalType > group_types,
TupleDataValidityType group_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES )
146038 : GroupedAggregateHashTable(context, allocator, std::move(group_types), {}, vector<AggregateObject>(),
146039 InitialCapacity(), 0, group_validity) {
146040}
static idx_t InitialCapacity()
Initial capacity of the HT.
Definition duckdb.cpp:146202

◆ ~GroupedAggregateHashTable()

duckdb::GroupedAggregateHashTable::~GroupedAggregateHashTable ( )
override
146164 {
146165 Destroy();
146166}
void Destroy()
Destroy the HT.
Definition duckdb.cpp:146168

Member Function Documentation

◆ GetLayoutPtr()

shared_ptr< TupleDataLayout > duckdb::GroupedAggregateHashTable::GetLayoutPtr ( )

Get the layout of this HT.

146190 {
146191 return partitioned_data->GetLayoutPtr();
146192}
unique_ptr< PartitionedTupleData > partitioned_data
The data of the HT.
Definition duckdb.cpp:145929

◆ GetLayout()

const TupleDataLayout & duckdb::GroupedAggregateHashTable::GetLayout ( ) const
146194 {
146195 return partitioned_data->GetLayout();
146196}

◆ Count()

idx_t duckdb::GroupedAggregateHashTable::Count ( ) const

Number of groups in the HT.

146198 {
146199 return count;
146200}
Here is the caller graph for this function:

◆ InitialCapacity()

idx_t duckdb::GroupedAggregateHashTable::InitialCapacity ( )
static

Initial capacity of the HT.

146202 {
146203 return STANDARD_VECTOR_SIZE * 2ULL;
146204}
Here is the caller graph for this function:

◆ GetCapacityForCount()

idx_t duckdb::GroupedAggregateHashTable::GetCapacityForCount ( idx_t count)
static

Capacity that can hold 'count' entries without resizing.

146206 {
146207 count = MaxValue<idx_t>(InitialCapacity(), count);
146208 return NextPowerOfTwo(LossyNumericCast<uint64_t>(static_cast<double>(count) * LOAD_FACTOR));
146209}
static constexpr double LOAD_FACTOR
The hash table load factor, when a resize is triggered.
Definition duckdb.cpp:145833
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Capacity()

idx_t duckdb::GroupedAggregateHashTable::Capacity ( ) const

Current capacity of the HT.

146211 {
146212 return capacity;
146213}
Here is the caller graph for this function:

◆ ResizeThreshold() [1/2]

idx_t duckdb::GroupedAggregateHashTable::ResizeThreshold ( ) const

Threshold at which to resize the HT.

146215 {
146216 return ResizeThreshold(Capacity());
146217}
idx_t Capacity() const
Current capacity of the HT.
Definition duckdb.cpp:146211
idx_t ResizeThreshold() const
Threshold at which to resize the HT.
Definition duckdb.cpp:146215
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResizeThreshold() [2/2]

idx_t duckdb::GroupedAggregateHashTable::ResizeThreshold ( idx_t capacity)
static
146219 {
146220 return LossyNumericCast<idx_t>(static_cast<double>(capacity) / LOAD_FACTOR);
146221}

◆ AddChunk() [1/3]

idx_t duckdb::GroupedAggregateHashTable::AddChunk ( DataChunk & groups,
DataChunk & payload,
const unsafe_vector< idx_t > & filter )

Add the given data to the HT, computing the aggregates grouped by the data in the group chunk. When resize = true, aggregates will not be computed but instead just assigned.

146525 {
146526 sink_count += groups.size();
146527
146528 // check if we can use an optimized path that utilizes compressed vectors
146529 auto result = TryAddCompressedGroups(groups, payload, filter);
146530 if (result.IsValid()) {
146531 return result.GetIndex();
146532 }
146533 // otherwise append the raw values
146534 groups.Hash(state.hashes);
146535
146536 return AddChunk(groups, state.hashes, payload, filter);
146537}
DUCKDB_API void Hash(Vector &result)
Hashes the DataChunk to the target vector.
Definition duckdb.cpp:117097
idx_t AddChunk(DataChunk &groups, DataChunk &payload, const unsafe_vector< idx_t > &filter)
Definition duckdb.cpp:146525
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AddChunk() [2/3]

idx_t duckdb::GroupedAggregateHashTable::AddChunk ( DataChunk & groups,
Vector & group_hashes,
DataChunk & payload,
const unsafe_vector< idx_t > & filter )
146571 {
146572 if (groups.size() == 0) {
146573 return 0;
146574 }
146575
146576#ifdef DEBUG
146577 D_ASSERT(groups.ColumnCount() + 1 == layout_ptr->ColumnCount());
146578 for (idx_t i = 0; i < groups.ColumnCount(); i++) {
146579 D_ASSERT(groups.GetTypes()[i] == layout_ptr->GetTypes()[i]);
146580 }
146581#endif
146582
146583 const auto new_group_count = FindOrCreateGroups(groups, group_hashes, state.addresses, state.new_groups);
146584 VectorOperations::AddInPlace(state.addresses, NumericCast<int64_t>(layout_ptr->GetAggrOffset()), payload.size());
146585
146586 UpdateAggregates(payload, filter);
146587
146588 return new_group_count;
146589}
DUCKDB_API vector< LogicalType > GetTypes() const
Returns a list of types of the vectors of this data chunk.
Definition duckdb.cpp:116995
idx_t FindOrCreateGroups(DataChunk &groups, Vector &group_hashes, Vector &addresses_out, SelectionVector &new_groups_out)
Definition duckdb.cpp:146824
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
static void AddInPlace(Vector &left, int64_t delta, idx_t count)
left += delta
Definition duckdb.cpp:143413

◆ AddChunk() [3/3]

idx_t duckdb::GroupedAggregateHashTable::AddChunk ( DataChunk & groups,
DataChunk & payload,
AggregateType filter )
146348 {
146349 unsafe_vector<idx_t> aggregate_filter;
146350
146351 auto &aggregates = layout_ptr->GetAggregates();
146352 for (idx_t i = 0; i < aggregates.size(); i++) {
146353 auto &aggregate = aggregates[i];
146354 if (aggregate.aggr_type == filter) {
146355 aggregate_filter.push_back(i);
146356 }
146357 }
146358 return AddChunk(groups, payload, aggregate_filter);
146359}

◆ TryAddCompressedGroups()

optional_idx duckdb::GroupedAggregateHashTable::TryAddCompressedGroups ( DataChunk & groups,
DataChunk & payload,
const unsafe_vector< idx_t > & filter )
146513 {
146514 // all groups must be compressed
146515 if (groups.AllConstant()) {
146516 return TryAddConstantGroups(groups, payload, filter);
146517 }
146518 if (groups.ColumnCount() == 1 && groups.data[0].GetVectorType() == VectorType::DICTIONARY_VECTOR &&
146519 groups.data[0].GetType().InternalType() != PhysicalType::STRUCT) {
146520 return TryAddDictionaryGroups(groups, payload, filter);
146521 }
146522 return optional_idx();
146523}
DUCKDB_API bool AllConstant() const
Returns true if all vectors in the DataChunk are constant.
Definition duckdb.cpp:116870
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
@ STRUCT
Struct of logical types.
Definition duckdb.hpp:2816

◆ TryAddDictionaryGroups()

optional_idx duckdb::GroupedAggregateHashTable::TryAddDictionaryGroups ( DataChunk & groups,
DataChunk & payload,
const unsafe_vector< idx_t > & filter )
146366 {
146367 static constexpr idx_t MAX_DICTIONARY_SIZE_THRESHOLD = 20000;
146368 static constexpr idx_t DICTIONARY_THRESHOLD = 2;
146369 // dictionary vector - check if this is a duplicate eliminated dictionary from the storage
146370 auto &dict_col = groups.data[0];
146371 auto opt_dict_size = DictionaryVector::DictionarySize(dict_col);
146372 if (!opt_dict_size.IsValid()) {
146373 // dict size not known - this is not a dictionary that comes from the storage
146374 return optional_idx();
146375 }
146376 idx_t dict_size = opt_dict_size.GetIndex();
146377 auto &dictionary_id = DictionaryVector::DictionaryId(dict_col);
146378 if (dictionary_id.empty()) {
146379 // dictionary has no id, we can't cache across vectors
146380 // only use dictionary compression if there are fewer entries than groups
146381 if (dict_size * DICTIONARY_THRESHOLD >= groups.size()) {
146382 // dictionary is too large - use regular aggregation
146383 return optional_idx();
146384 }
146385 } else {
146386 // dictionary has an id - we can cache across vectors
146387 // use a much larger limit for dictionary
146388 if (dict_size >= MAX_DICTIONARY_SIZE_THRESHOLD) {
146389 // dictionary is too large - use regular aggregation
146390 return optional_idx();
146391 }
146392 }
146393 auto &dictionary_vector = DictionaryVector::Child(dict_col);
146394 auto &offsets = DictionaryVector::SelVector(dict_col);
146395 auto &dict_state = state.dict_state;
146396 if (dict_state.dictionary_id.empty() || dict_state.dictionary_id != dictionary_id) {
146397 // new dictionary - initialize the index state
146398 if (dict_size > dict_state.capacity) {
146399 dict_state.dictionary_addresses = make_uniq<Vector>(LogicalType::POINTER, dict_size);
146400 dict_state.found_entry = make_unsafe_uniq_array<bool>(dict_size);
146401 dict_state.capacity = dict_size;
146402 }
146403 memset(dict_state.found_entry.get(), 0, dict_size * sizeof(bool));
146404 dict_state.dictionary_id = dictionary_id;
146405 } else if (dict_size > dict_state.capacity) {
146406 throw InternalException("AggregateHT - using cached dictionary data but dictionary has changed (dictionary id "
146407 "%s - dict size %d, current capacity %d)",
146408 dict_state.dictionary_id, dict_size, dict_state.capacity);
146409 }
146410
146411 auto &found_entry = dict_state.found_entry;
146412 auto &unique_entries = dict_state.unique_entries;
146413 idx_t unique_count = 0;
146414 // for each of the dictionary entries - check if we have already done a look-up into the hash table
146415 // if we have, we can just use the cached group pointers
146416 for (idx_t i = 0; i < groups.size(); i++) {
146417 auto dict_idx = offsets.get_index(i);
146418 unique_entries.set_index(unique_count, dict_idx);
146419 unique_count += !found_entry[dict_idx];
146420 found_entry[dict_idx] = true;
146421 }
146422 auto &new_dictionary_pointers = dict_state.new_dictionary_pointers;
146423 idx_t new_group_count = 0;
146424 if (unique_count > 0) {
146425 auto &unique_values = dict_state.unique_values;
146426 if (unique_values.ColumnCount() == 0) {
146427 unique_values.InitializeEmpty(groups.GetTypes());
146428 }
146429 // slice the dictionary
146430 unique_values.data[0].Slice(dictionary_vector, unique_entries, unique_count);
146431 unique_values.SetCardinality(unique_count);
146432 // now we know which entries we are going to add - hash them
146433 auto &hashes = dict_state.hashes;
146434 unique_values.Hash(hashes);
146435
146436 // add the dictionary groups to the hash table
146437 new_group_count = FindOrCreateGroups(unique_values, hashes, new_dictionary_pointers, state.new_groups);
146438 }
146439 auto &aggregates = layout_ptr->GetAggregates();
146440 if (aggregates.empty()) {
146441 // early-out - no aggregates to update
146442 return new_group_count;
146443 }
146444
146445 // set the addresses that we found for each of the unique groups in the main addresses vector
146446 auto new_dict_addresses = FlatVector::GetData<uintptr_t>(new_dictionary_pointers);
146447 // for each of the new groups, add them to the global (cached) list of addresses for the dictionary
146448 auto &dictionary_addresses = *dict_state.dictionary_addresses;
146449 auto dict_addresses = FlatVector::GetData<uintptr_t>(dictionary_addresses);
146450 for (idx_t i = 0; i < unique_count; i++) {
146451 auto dict_idx = unique_entries.get_index(i);
146452 dict_addresses[dict_idx] = new_dict_addresses[i] + layout_ptr->GetAggrOffset();
146453 }
146454 // now set up the addresses for the aggregates
146455 auto result_addresses = FlatVector::GetData<uintptr_t>(state.addresses);
146456 for (idx_t i = 0; i < groups.size(); i++) {
146457 auto dict_idx = offsets.get_index(i);
146458 result_addresses[i] = dict_addresses[dict_idx];
146459 }
146460
146461 // finally process the aggregates
146462 UpdateAggregates(payload, filter);
146463
146464 return new_group_count;
146465}

◆ TryAddConstantGroups()

optional_idx duckdb::GroupedAggregateHashTable::TryAddConstantGroups ( DataChunk & groups,
DataChunk & payload,
const unsafe_vector< idx_t > & filter )
146468 {
146469#ifndef DEBUG
146470 if (groups.size() <= 1) {
146471 // this only has a point if we have multiple groups
146472 return optional_idx();
146473 }
146474#endif
146475 auto &dict_state = state.dict_state;
146476 auto &unique_values = dict_state.unique_values;
146477 if (unique_values.ColumnCount() == 0) {
146478 unique_values.InitializeEmpty(groups.GetTypes());
146479 }
146480 // slice the dictionary
146481 unique_values.Reference(groups);
146482 unique_values.SetCardinality(1);
146483 unique_values.Flatten();
146484
146485 auto &hashes = dict_state.hashes;
146486 unique_values.Hash(hashes);
146487
146488 // add the single constant group to the hash table
146489 auto &new_dictionary_pointers = dict_state.new_dictionary_pointers;
146490 auto new_group_count = FindOrCreateGroups(unique_values, hashes, new_dictionary_pointers, state.new_groups);
146491
146492 auto &aggregates = layout_ptr->GetAggregates();
146493 if (aggregates.empty()) {
146494 // early-out - no aggregates to update
146495 return new_group_count;
146496 }
146497
146498 auto new_dict_addresses = FlatVector::GetData<uintptr_t>(new_dictionary_pointers);
146499 auto result_addresses = FlatVector::GetData<uintptr_t>(state.addresses);
146500 uintptr_t aggregate_address = new_dict_addresses[0] + layout_ptr->GetAggrOffset();
146501 for (idx_t i = 0; i < payload.size(); i++) {
146502 result_addresses[i] = aggregate_address;
146503 }
146504
146505 // process the aggregates
146506 // FIXME: we can use simple_update here if the aggregates support it
146507 UpdateAggregates(payload, filter);
146508
146509 return new_group_count;
146510}

◆ FetchAggregates()

void duckdb::GroupedAggregateHashTable::FetchAggregates ( DataChunk & groups,
DataChunk & result )

Fetch the aggregates for specific groups from the HT and place them in the result.

146591 {
146592#ifdef DEBUG
146593 groups.Verify();
146594 D_ASSERT(groups.ColumnCount() + 1 == layout_ptr->ColumnCount());
146595 for (idx_t i = 0; i < result.ColumnCount(); i++) {
146596 D_ASSERT(result.data[i].GetType() == payload_types[i]);
146597 }
146598#endif
146599
146600 result.SetCardinality(groups);
146601 if (groups.size() == 0) {
146602 return;
146603 }
146604
146605 // find the groups associated with the addresses
146606 // FIXME: this should not use the FindOrCreateGroups, creating them is unnecessary
146607 FindOrCreateGroups(groups, state.addresses);
146608 // now fetch the aggregates
146609 RowOperations::FinalizeStates(state.row_state, *layout_ptr, state.addresses, result, 0);
146610}
DUCKDB_API void Verify()
Definition duckdb.cpp:117115
static void FinalizeStates(RowOperationsState &state, TupleDataLayout &layout, Vector &addresses, DataChunk &result, idx_t aggr_idx)
finalize - unaligned addresses, updated
Definition duckdb.cpp:99866
Here is the call graph for this function:

◆ InitializeScan()

void duckdb::GroupedAggregateHashTable::InitializeScan ( AggregateHTScanState & scan_state)
146924 {
146925 scan_state.partition_idx = 0;
146926 vector<idx_t> group_indexes(layout_ptr->ColumnCount() - 1);
146927 for (idx_t i = 0; i < group_indexes.size(); i++) {
146928 group_indexes[i] = i;
146929 }
146930
146931 auto &partition = partitioned_data->GetPartitions()[scan_state.partition_idx];
146932 partition->InitializeScan(scan_state.scan_states, group_indexes);
146933}
int partition(const std::vector< _Tp > &_vec, std::vector< int > &labels, _EqPredicate predicate=_EqPredicate())

◆ Scan()

bool duckdb::GroupedAggregateHashTable::Scan ( AggregateHTScanState & scan_state,
DataChunk & distinct_rows,
DataChunk & payload_rows )
146936 {
146937 if (scan_state.partition_idx >= partitioned_data->PartitionCount()) {
146938 return false;
146939 }
146940
146941 payload_rows.Reset();
146942 distinct_rows.Reset();
146943 auto &current_partition = partitioned_data->GetPartitions()[scan_state.partition_idx];
146944
146945 if (current_partition->Scan(scan_state.scan_states, distinct_rows)) {
146946 FetchAggregates(distinct_rows, payload_rows);
146947 return true;
146948 } else {
146949 if (++(scan_state.partition_idx) >= partitioned_data->PartitionCount()) {
146950 return false;
146951 } else {
146952 auto &new_partition = partitioned_data->GetPartitions()[scan_state.partition_idx];
146953 new_partition->InitializeScan(scan_state.scan_states);
146954 return true;
146955 }
146956 }
146957}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
void FetchAggregates(DataChunk &groups, DataChunk &result)
Fetch the aggregates for specific groups from the HT and place them in the result.
Definition duckdb.cpp:146591

◆ FindOrCreateGroups() [1/3]

idx_t duckdb::GroupedAggregateHashTable::FindOrCreateGroups ( DataChunk & groups,
Vector & group_hashes,
Vector & addresses_out,
SelectionVector & new_groups_out )

Finds or creates groups in the hashtable using the specified group keys. The addresses vector will be filled with pointers to the groups in the hash table, and the new_groups selection vector will point to the newly created groups. The return value is the amount of newly created groups.

146825 {
146826 return FindOrCreateGroupsInternal(groups, group_hashes, addresses_out, new_groups_out);
146827}
idx_t FindOrCreateGroupsInternal(DataChunk &groups, Vector &group_hashes, Vector &addresses, SelectionVector &new_groups)
Does the actual group matching / creation.
Definition duckdb.cpp:146647
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindOrCreateGroups() [2/3]

idx_t duckdb::GroupedAggregateHashTable::FindOrCreateGroups ( DataChunk & groups,
Vector & addresses_out,
SelectionVector & new_groups_out )
146835 {
146836 groups.Hash(state.hashes);
146837 return FindOrCreateGroups(groups, state.hashes, addresses_out, new_groups_out);
146838}

◆ FindOrCreateGroups() [3/3]

void duckdb::GroupedAggregateHashTable::FindOrCreateGroups ( DataChunk & groups,
Vector & addresses_out )
146829 {
146830 // create a dummy new_groups sel vector
146831 FindOrCreateGroups(groups, addresses, state.new_groups);
146832}

◆ GetPartitionedData()

const PartitionedTupleData & duckdb::GroupedAggregateHashTable::GetPartitionedData ( ) const
146110 {
146111 return *partitioned_data;
146112}

◆ AcquirePartitionedData()

unique_ptr< PartitionedTupleData > duckdb::GroupedAggregateHashTable::AcquirePartitionedData ( )
146114 {
146116 // Flush/unpin unpartitioned data and append to partitioned data
146117 if (unpartitioned_data) {
146118 unpartitioned_data->FlushAppendState(state.unpartitioned_append_state);
146119 unpartitioned_data->Unpin();
146120 unpartitioned_data->Repartition(context, *partitioned_data);
146121 }
146123 }
146124
146125 // Flush/unpin partitioned data
146126 partitioned_data->FlushAppendState(state.partitioned_append_state);
146127 partitioned_data->Unpin();
146128
146129 // Return and re-initialize
146130 auto result = std::move(partitioned_data);
146132 return result;
146133}

◆ Abandon()

void duckdb::GroupedAggregateHashTable::Abandon ( )
146135 {
146137 // Flush/unpin unpartitioned data and append to partitioned data
146138 if (unpartitioned_data) {
146139 unpartitioned_data->FlushAppendState(state.unpartitioned_append_state);
146140 unpartitioned_data->Unpin();
146141 unpartitioned_data->Repartition(context, *partitioned_data);
146142 }
146144 }
146145
146146 // Start over
146148 count = 0;
146149
146150 // Resetting the id ensures the dict state is reset properly when needed
146151 state.dict_state.dictionary_id = string();
146152}
void ClearPointerTable()
Resets the pointer table of the HT to all 0's.
Definition duckdb.cpp:146246

◆ Repartition()

void duckdb::GroupedAggregateHashTable::Repartition ( )
146154 {
146155 auto old = AcquirePartitionedData();
146156 D_ASSERT(old->GetPartitions().size() != partitioned_data->GetPartitions().size());
146157 old->Repartition(context, *partitioned_data);
146158}

◆ GetAggregateAllocator()

shared_ptr< ArenaAllocator > duckdb::GroupedAggregateHashTable::GetAggregateAllocator ( )
146160 {
146161 return aggregate_allocator;
146162}

◆ Resize()

void duckdb::GroupedAggregateHashTable::Resize ( idx_t size)

Resize the HT to the specified size. Must be larger than the current size.

146287 {
146288 D_ASSERT(size >= STANDARD_VECTOR_SIZE);
146289 D_ASSERT(IsPowerOfTwo(size));
146290 if (Count() != 0 && size < capacity) {
146291 throw InternalException("Cannot downsize a non-empty hash table!");
146292 }
146293 D_ASSERT(Count() == 0 || Count() == GetMaterializedCount());
146294
146295 capacity = size;
146296 hash_map = buffer_manager.GetBufferAllocator().Allocate(capacity * sizeof(ht_entry_t));
146297 entries = reinterpret_cast<ht_entry_t *>(hash_map.get());
146299 bitmask = capacity - 1;
146300
146301 if (Count() != 0) {
146304 ReinsertTuples(*unpartitioned_data);
146305 }
146306 }
146307
146308 Verify();
146309}
AllocatedData hash_map
The hash map (pointer table) of the HT: allocated data and pointer into it.
Definition duckdb.cpp:145940
hash_t bitmask
Bitmask for getting relevant bits from the hashes to determine the position.
Definition duckdb.cpp:145945
idx_t Count() const
Number of groups in the HT.
Definition duckdb.cpp:146198
void Verify()
Verify the pointer table of the HT.
Definition duckdb.cpp:146227
void ReinsertTuples(PartitionedTupleData &data)
Reinserts tuples (triggered by Resize).
Definition duckdb.cpp:146319
idx_t GetMaterializedCount() const
Get the total number of tuples materialized currently in this HT.
Definition duckdb.cpp:146262
GOpaque< Size > size(const GMat &src)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ClearPointerTable()

void duckdb::GroupedAggregateHashTable::ClearPointerTable ( )

Resets the pointer table of the HT to all 0's.

146246 {
146247 std::fill_n(entries, capacity, ht_entry_t());
146248}
Here is the caller graph for this function:

◆ SetRadixBits()

void duckdb::GroupedAggregateHashTable::SetRadixBits ( idx_t radix_bits)

Set the radix bits for this HT.

146250 {
146251 radix_bits = radix_bits_p;
146252}

◆ GetRadixBits()

idx_t duckdb::GroupedAggregateHashTable::GetRadixBits ( ) const

Get the radix bits for this HT.

146254 {
146255 return radix_bits;
146256}

◆ GetSinkCount()

idx_t duckdb::GroupedAggregateHashTable::GetSinkCount ( ) const

Get the total number of tuples sunk into this HT.

146258 {
146259 return sink_count;
146260}

◆ GetMaterializedCount()

idx_t duckdb::GroupedAggregateHashTable::GetMaterializedCount ( ) const

Get the total number of tuples materialized currently in this HT.

146262 {
146263 auto result = partitioned_data->Count();
146264 if (unpartitioned_data) {
146265 result += unpartitioned_data->Count();
146266 }
146267 return result;
146268}
Here is the caller graph for this function:

◆ SkipLookups()

void duckdb::GroupedAggregateHashTable::SkipLookups ( )

Skips lookups from here on out.

146270 {
146271 skip_lookups = true;
146272}

◆ EnableHLL()

void duckdb::GroupedAggregateHashTable::EnableHLL ( bool enable)

Enable/disable HLL.

146274 {
146275 enable_hll = enable;
146276}

◆ HLLEnabled()

bool duckdb::GroupedAggregateHashTable::HLLEnabled ( ) const

Whether HLL is enabled.

146278 {
146279 return enable_hll;
146280}

◆ GetHLLUpperBound()

idx_t duckdb::GroupedAggregateHashTable::GetHLLUpperBound ( ) const

Get HLL count.

146282 {
146283 D_ASSERT(enable_hll);
146284 return LossyNumericCast<idx_t>((1 + HyperLogLog::GetErrorRate()) * static_cast<double>(hll.Count()));
146285}
HyperLogLog hll
The associated HLL.
Definition duckdb.cpp:145954

◆ Combine() [1/2]

void duckdb::GroupedAggregateHashTable::Combine ( GroupedAggregateHashTable & other)

Executes the filter(if any) and update the aggregates.

146877 {
146878 auto other_partitioned_data = other.AcquirePartitionedData();
146879 auto other_data = other_partitioned_data->GetUnpartitioned();
146880 Combine(*other_data);
146881
146882 // Inherit ownership to all stored aggregate allocators
146883 stored_allocators.emplace_back(other.aggregate_allocator);
146884 for (const auto &stored_allocator : other.stored_allocators) {
146885 stored_allocators.emplace_back(stored_allocator);
146886 }
146887}
vector< shared_ptr< ArenaAllocator > > stored_allocators
Owning arena allocators that this HT has data from.
Definition duckdb.cpp:145959
void Combine(GroupedAggregateHashTable &other)
Executes the filter(if any) and update the aggregates.
Definition duckdb.cpp:146877
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Combine() [2/2]

void duckdb::GroupedAggregateHashTable::Combine ( TupleDataCollection & other_data,
optional_ptr< atomic< double > > progress = nullptr )
146889 {
146890 D_ASSERT(other_data.GetLayout().GetAggrWidth() == layout_ptr->GetAggrWidth());
146891 D_ASSERT(other_data.GetLayout().GetDataWidth() == layout_ptr->GetDataWidth());
146892 D_ASSERT(other_data.GetLayout().GetRowWidth() == layout_ptr->GetRowWidth());
146893
146894 if (other_data.Count() == 0) {
146895 return;
146896 }
146897
146898 FlushMoveState fm_state(other_data);
146899
146900 idx_t chunk_idx = 0;
146901 const auto chunk_count = other_data.ChunkCount();
146902 while (fm_state.Scan()) {
146903 // Check for interrupts with each chunk
146904 if (context.interrupted.load(std::memory_order_relaxed)) {
146905 throw InterruptException();
146906 }
146907 const auto input_chunk_size = fm_state.groups.size();
146908 FindOrCreateGroups(fm_state.groups, fm_state.hashes, fm_state.group_addresses, fm_state.new_groups_sel);
146909 RowOperations::CombineStates(state.row_state, *layout_ptr, fm_state.scan_state.chunk_state.row_locations,
146910 fm_state.group_addresses, input_chunk_size);
146911 if (layout_ptr->HasDestructor()) {
146912 RowOperations::DestroyStates(state.row_state, *layout_ptr, fm_state.scan_state.chunk_state.row_locations,
146913 input_chunk_size);
146914 }
146915
146916 if (progress) {
146917 *progress = static_cast<double>(++chunk_idx) / static_cast<double>(chunk_count);
146918 }
146919 }
146920
146921 Verify();
146922}
static void CombineStates(RowOperationsState &state, TupleDataLayout &layout, Vector &sources, Vector &targets, idx_t count)
combine - unaligned addresses, updated
Definition duckdb.cpp:99834
static void DestroyStates(RowOperationsState &state, TupleDataLayout &layout, Vector &addresses, idx_t count)
destructor - unaligned addresses, updated
Definition duckdb.cpp:99798

◆ Destroy()

void duckdb::GroupedAggregateHashTable::Destroy ( )
private

Destroy the HT.

146168 {
146169 if (!partitioned_data || partitioned_data->Count() == 0 || !layout_ptr->HasDestructor()) {
146170 return;
146171 }
146172
146173 // There are aggregates with destructors: Call the destructor for each of the aggregates
146174 // Currently does not happen because aggregate destructors are called while scanning in RadixPartitionedHashTable
146175 // LCOV_EXCL_START
146176 for (auto &data_collection : partitioned_data->GetPartitions()) {
146177 if (data_collection->Count() == 0) {
146178 continue;
146179 }
146180 TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::DESTROY_AFTER_DONE, false);
146181 auto &row_locations = iterator.GetChunkState().row_locations;
146182 do {
146183 RowOperations::DestroyStates(state.row_state, *layout_ptr, row_locations, iterator.GetCurrentChunkCount());
146184 } while (iterator.Next());
146185 data_collection->Reset();
146186 }
146187 // LCOV_EXCL_STOP
146188}
@ DESTROY_AFTER_DONE
Destroys blocks after they are done (for reading only).
Definition duckdb.cpp:56603
Here is the call graph for this function:

◆ InitializePartitionedData()

void duckdb::GroupedAggregateHashTable::InitializePartitionedData ( )
private

Initializes the PartitionedTupleData.

146080 {
146081 if (!partitioned_data ||
146083 D_ASSERT(!partitioned_data || partitioned_data->Count() == 0);
146084 partitioned_data = make_uniq<RadixPartitionedTupleData>(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE,
146085 radix_bits, layout_ptr->ColumnCount() - 1);
146086 } else {
146087 partitioned_data->Reset();
146088 }
146089
146090 D_ASSERT(GetLayout().GetAggrWidth() == layout_ptr->GetAggrWidth());
146091 D_ASSERT(GetLayout().GetDataWidth() == layout_ptr->GetDataWidth());
146092 D_ASSERT(GetLayout().GetRowWidth() == layout_ptr->GetRowWidth());
146093
146094 partitioned_data->InitializeAppendState(state.partitioned_append_state,
146096}
@ KEEP_EVERYTHING_PINNED
Keeps all passed blocks pinned while scanning/iterating over the chunks (for both reading/writing).
Definition duckdb.cpp:56599
static idx_t RadixBitsOfPowerOfTwo(idx_t n_partitions)
Inverse of NumberOfPartitions, given a number of partitions, get the number of radix bits.
Definition duckdb.cpp:93435
Here is the call graph for this function:

◆ InitializeUnpartitionedData()

void duckdb::GroupedAggregateHashTable::InitializeUnpartitionedData ( )
private

Initializes the PartitionedTupleData that only has 1 partition.

146098 {
146100 if (!unpartitioned_data) {
146101 unpartitioned_data = make_uniq<RadixPartitionedTupleData>(buffer_manager, layout_ptr, MemoryTag::HASH_TABLE,
146102 0ULL, layout_ptr->ColumnCount() - 1);
146103 } else {
146104 unpartitioned_data->Reset();
146105 }
146106 unpartitioned_data->InitializeAppendState(state.unpartitioned_append_state,
146108}

◆ ApplyBitMask()

idx_t duckdb::GroupedAggregateHashTable::ApplyBitMask ( hash_t hash) const
inlineprivate

Apply bitmask to get the entry in the HT.

146223 {
146224 return hash & bitmask;
146225}
Here is the caller graph for this function:

◆ ReinsertTuples()

void duckdb::GroupedAggregateHashTable::ReinsertTuples ( PartitionedTupleData & data)
private

Reinserts tuples (triggered by Resize).

146319 {
146320 for (auto &data_collection : data.GetPartitions()) {
146321 if (data_collection->Count() == 0) {
146322 continue;
146323 }
146324 TupleDataChunkIterator iterator(*data_collection, TupleDataPinProperties::ALREADY_PINNED, false);
146325 const auto row_locations = iterator.GetRowLocations();
146326 do {
146327 for (idx_t i = 0; i < iterator.GetCurrentChunkCount(); i++) {
146328 const auto &row_location = row_locations[i];
146329 const auto hash = Load<hash_t>(row_location + hash_offset);
146330 const auto salt = ht_entry_t::ExtractSalt(hash);
146331
146332 // Find an empty entry
146333 auto ht_offset = ApplyBitMask(hash);
146334 D_ASSERT(ht_offset == hash % capacity);
146335 while (entries[ht_offset].IsOccupied()) {
146336 SaltIncrementAndWrap(ht_offset, salt, bitmask);
146337 }
146338 auto &entry = entries[ht_offset];
146339 D_ASSERT(!entry.IsOccupied());
146340 entry.SetSalt(salt);
146341 entry.SetPointer(row_location);
146342 D_ASSERT(entry.IsOccupied());
146343 }
146344 } while (iterator.Next());
146345 }
146346}
idx_t ApplyBitMask(hash_t hash) const
Apply bitmask to get the entry in the HT.
Definition duckdb.cpp:146223
@ ALREADY_PINNED
Assumes all blocks are already pinned (for reading only).
Definition duckdb.cpp:56605
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateAggregates()

void duckdb::GroupedAggregateHashTable::UpdateAggregates ( DataChunk & payload,
const unsafe_vector< idx_t > & filter )
private
146539 {
146540 // Now every cell has an entry, update the aggregates
146541 auto &aggregates = layout_ptr->GetAggregates();
146542 idx_t filter_idx = 0;
146543 idx_t payload_idx = 0;
146544 for (idx_t i = 0; i < aggregates.size(); i++) {
146545 auto &aggr = aggregates[i];
146546 if (filter_idx >= filter.size() || i < filter[filter_idx]) {
146547 // Skip all the aggregates that are not in the filter
146548 payload_idx += aggr.child_count;
146549 VectorOperations::AddInPlace(state.addresses, NumericCast<int64_t>(aggr.payload_size), payload.size());
146550 continue;
146551 }
146552 D_ASSERT(i == filter[filter_idx]);
146553
146554 if (aggr.aggr_type != AggregateType::DISTINCT && aggr.filter) {
146555 RowOperations::UpdateFilteredStates(state.row_state, filter_set.GetFilterData(i), aggr, state.addresses,
146556 payload, payload_idx);
146557 } else {
146558 RowOperations::UpdateStates(state.row_state, aggr, state.addresses, payload, payload_idx, payload.size());
146559 }
146560
146561 // Move to the next aggregate
146562 payload_idx += aggr.child_count;
146563 VectorOperations::AddInPlace(state.addresses, NumericCast<int64_t>(aggr.payload_size), payload.size());
146564 filter_idx++;
146565 }
146566
146567 Verify();
146568}
AggregateFilterDataSet filter_set
Intermediate structures and data for aggregate filters.
Definition duckdb.cpp:145681
void filter(InputArray image, InputArray kernel, OutputArray output)
static void UpdateFilteredStates(RowOperationsState &state, AggregateFilterData &filter_data, AggregateObject &aggr, Vector &addresses, DataChunk &payload, idx_t arg_idx)
filtered update - aligned addresses
Definition duckdb.cpp:99821
static void UpdateStates(RowOperationsState &state, AggregateObject &aggr, Vector &addresses, DataChunk &payload, idx_t arg_idx, idx_t count)
update - aligned addresses
Definition duckdb.cpp:99814

◆ FindOrCreateGroupsInternal()

idx_t duckdb::GroupedAggregateHashTable::FindOrCreateGroupsInternal ( DataChunk & groups,
Vector & group_hashes,
Vector & addresses,
SelectionVector & new_groups )
private

Does the actual group matching / creation.

146648 {
146649 D_ASSERT(groups.ColumnCount() + 1 == layout_ptr->ColumnCount());
146650 D_ASSERT(group_hashes_v.GetType() == LogicalType::HASH);
146651 D_ASSERT(state.ht_offsets.GetVectorType() == VectorType::FLAT_VECTOR);
146652 D_ASSERT(state.ht_offsets.GetType() == LogicalType::UBIGINT);
146653 D_ASSERT(addresses_v.GetType() == LogicalType::POINTER);
146654 D_ASSERT(state.hash_salts.GetType() == LogicalType::HASH);
146655
146656 // Need to fit the entire vector, and resize at threshold
146657 const auto chunk_size = groups.size();
146658 if (Count() + chunk_size > capacity || Count() + chunk_size > ResizeThreshold()) {
146659 Verify();
146660 Resize(capacity * 2);
146661 }
146662 D_ASSERT(capacity - Count() >= chunk_size); // we need to be able to fit at least one vector of data
146663
146664 // we start out with all entries [0, 1, 2, ..., chunk_size]
146665 const SelectionVector *sel_vector = FlatVector::IncrementalSelectionVector();
146666
146667 // Make a chunk that references the groups and the hashes and convert to unified format
146668 if (state.group_chunk.ColumnCount() == 0) {
146669 state.group_chunk.InitializeEmpty(layout_ptr->GetTypes());
146670 }
146671 D_ASSERT(state.group_chunk.ColumnCount() == layout_ptr->GetTypes().size());
146672 for (idx_t grp_idx = 0; grp_idx < groups.ColumnCount(); grp_idx++) {
146673 state.group_chunk.data[grp_idx].Reference(groups.data[grp_idx]);
146674 }
146675 state.group_chunk.data[groups.ColumnCount()].Reference(group_hashes_v);
146676 state.group_chunk.SetCardinality(groups);
146677
146678 // convert all vectors to unified format
146679 TupleDataCollection::ToUnifiedFormat(state.partitioned_append_state.chunk_state, state.group_chunk);
146680
146681 if (enable_hll) {
146682 hll.Update(group_hashes_v, group_hashes_v, groups.size());
146683 }
146684
146685 group_hashes_v.Flatten(chunk_size);
146686 const auto hashes = FlatVector::GetData<hash_t>(group_hashes_v);
146687
146688 addresses_v.Flatten(chunk_size);
146689 const auto addresses = FlatVector::GetData<data_ptr_t>(addresses_v);
146690
146691 if (skip_lookups) {
146692 // Just appending now
146693 partitioned_data->AppendUnified(state.partitioned_append_state, state.group_chunk,
146694 *FlatVector::IncrementalSelectionVector(), chunk_size);
146695 RowOperations::InitializeStates(*layout_ptr, state.partitioned_append_state.chunk_state.row_locations,
146696 *FlatVector::IncrementalSelectionVector(), chunk_size);
146697
146698 const auto row_locations =
146699 FlatVector::GetData<data_ptr_t>(state.partitioned_append_state.chunk_state.row_locations);
146700 const auto &row_sel = state.partitioned_append_state.reverse_partition_sel;
146701 for (idx_t i = 0; i < chunk_size; i++) {
146702 const auto row_idx = row_sel.get_index_unsafe(i);
146703 const auto &row_location = row_locations[row_idx];
146704 addresses[i] = row_location;
146705 }
146706 count += chunk_size;
146707 return chunk_size;
146708 }
146709
146710 // Compute the entry in the table based on the hash using a modulo,
146711 // and precompute the hash salts for faster comparison below
146712 const auto ht_offsets = FlatVector::GetData<uint64_t>(state.ht_offsets);
146713 const auto hash_salts = FlatVector::GetData<hash_t>(state.hash_salts);
146714
146715 // We also compute the occupied count, which is essentially useless.
146716 // However, this loop is branchless, while the main lookup loop below is not.
146717 // So, by doing the lookups here, we better amortize cache misses.
146718 idx_t occupied_count = 0;
146719 for (idx_t r = 0; r < chunk_size; r++) {
146720 const auto &hash = hashes[r];
146721 auto &ht_offset = ht_offsets[r];
146722 ht_offset = ApplyBitMask(hash);
146723 occupied_count += entries[ht_offset].IsOccupied(); // Lookup
146724 D_ASSERT(ht_offset == hash % capacity);
146725 hash_salts[r] = ht_entry_t::ExtractSalt(hash);
146726 }
146727
146728 SelectionVector empty_vector;
146729 idx_t new_group_count = 0;
146730 idx_t remaining_entries = chunk_size;
146731 idx_t iteration_count;
146732 for (iteration_count = 0; remaining_entries > 0 && iteration_count < capacity; iteration_count++) {
146733 idx_t new_entry_count = 0;
146734 idx_t need_compare_count = 0;
146735 idx_t no_match_count = 0;
146736
146737 // "new_groups_out" contains ALL groups for the chunk, "empty_vector" only the groups for this iteration,
146738 // so it's just the same selection vector, but offset by the current "new_group_count".
146739 empty_vector.Initialize(new_groups_out.data() + new_group_count);
146740 if (sel_vector->IsSet()) {
146741 GroupedAggregateHashTableInnerLoop<true>(entries, capacity, bitmask, hash_salts, ht_offsets, sel_vector,
146742 remaining_entries, empty_vector, state.group_compare_vector,
146743 new_entry_count, need_compare_count);
146744 } else {
146745 GroupedAggregateHashTableInnerLoop<false>(entries, capacity, bitmask, hash_salts, ht_offsets, sel_vector,
146746 remaining_entries, empty_vector, state.group_compare_vector,
146747 new_entry_count, need_compare_count);
146748 }
146749 new_group_count += new_entry_count;
146750
146751 if (DUCKDB_UNLIKELY(occupied_count > new_entry_count + need_compare_count)) {
146752 // We use the useless occupied_count we summed above here so the variable is used,
146753 // and the compiler cannot optimize away the vectorized lookups above. This should never be triggered.
146754 throw InternalException("Internal validation failed in GroupedAggregateHashTable");
146755 }
146756 occupied_count = 0; // Have to set to 0 for next iterations
146757
146758 if (new_entry_count != 0) {
146759 // Append everything that belongs to an empty group
146760 optional_ptr<PartitionedTupleData> data;
146761 optional_ptr<PartitionedTupleDataAppendState> append_state;
146763 new_entry_count / RadixPartitioning::NumberOfPartitions(radix_bits) <= 4) {
146764 TupleDataCollection::ToUnifiedFormat(state.unpartitioned_append_state.chunk_state, state.group_chunk);
146765 data = unpartitioned_data.get();
146766 append_state = &state.unpartitioned_append_state;
146767 } else {
146768 data = partitioned_data.get();
146769 append_state = &state.partitioned_append_state;
146770 }
146771 data->AppendUnified(*append_state, state.group_chunk, empty_vector, new_entry_count);
146772 RowOperations::InitializeStates(*layout_ptr, append_state->chunk_state.row_locations,
146773 *FlatVector::IncrementalSelectionVector(), new_entry_count);
146774
146775 // Set the entry pointers in the 1st part of the HT now that the data has been appended
146776 const auto row_locations = FlatVector::GetData<data_ptr_t>(append_state->chunk_state.row_locations);
146777 const auto &row_sel = append_state->reverse_partition_sel;
146778 for (idx_t new_entry_idx = 0; new_entry_idx < new_entry_count; new_entry_idx++) {
146779 const auto index = empty_vector.get_index_unsafe(new_entry_idx);
146780 const auto row_idx = row_sel.get_index_unsafe(index);
146781 const auto &row_location = row_locations[row_idx];
146782
146783 auto &entry = entries[ht_offsets[index]];
146784
146785 entry.SetPointer(row_location);
146786 addresses[index] = row_location;
146787 }
146788 }
146789
146790 if (need_compare_count != 0) {
146791 // Get the pointers to the rows that need to be compared
146792 for (idx_t need_compare_idx = 0; need_compare_idx < need_compare_count; need_compare_idx++) {
146793 const auto index = state.group_compare_vector.get_index_unsafe(need_compare_idx);
146794 const auto &entry = entries[ht_offsets[index]];
146795 addresses[index] = entry.GetPointer();
146796 }
146797
146798 // Perform group comparisons
146799 row_matcher.Match(state.group_chunk, state.partitioned_append_state.chunk_state.vector_data,
146800 state.group_compare_vector, need_compare_count, addresses_v, &state.no_match_vector,
146801 no_match_count);
146802 }
146803
146804 // Linear probing: each of the entries that do not match move to the next entry in the HT
146805 for (idx_t i = 0; i < no_match_count; i++) {
146806 const auto index = state.no_match_vector.get_index_unsafe(i);
146807 auto &ht_offset = ht_offsets[index];
146808 const auto salt = hash_salts[index];
146809 SaltIncrementAndWrap(ht_offset, salt, bitmask);
146810 }
146811 sel_vector = &state.no_match_vector;
146812 remaining_entries = no_match_count;
146813 }
146814 if (iteration_count == capacity) {
146815 throw InternalException("Maximum outer iteration count reached in GroupedAggregateHashTable");
146816 }
146817
146818 count += new_group_count;
146819 return new_group_count;
146820}
static void ToUnifiedFormat(TupleDataChunkState &chunk_state, DataChunk &new_chunk)
Creates a UnifiedVectorFormat in the given Chunk state for the given DataChunk.
Definition duckdb.cpp:125999
index
static constexpr idx_t NumberOfPartitions(idx_t radix_bits)
The number of partitions for a given number of radix bits.
Definition duckdb.cpp:93425
static void InitializeStates(TupleDataLayout &layout, Vector &addresses, const SelectionVector &sel, idx_t count)
initialize - unaligned addresses
Definition duckdb.cpp:99774
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Verify()

void duckdb::GroupedAggregateHashTable::Verify ( )
private

Verify the pointer table of the HT.

146227 {
146228#ifdef DEBUG
146229 if (skip_lookups) {
146230 return;
146231 }
146232 idx_t total_count = 0;
146233 for (idx_t i = 0; i < capacity; i++) {
146234 const auto &entry = entries[i];
146235 if (!entry.IsOccupied()) {
146236 continue;
146237 }
146238 auto hash = Load<hash_t>(entry.GetPointer() + hash_offset);
146239 D_ASSERT(entry.GetSalt() == ht_entry_t::ExtractSalt(hash));
146240 total_count++;
146241 }
146242 D_ASSERT(total_count == Count());
146243#endif
146244}
Here is the call graph for this function:
Here is the caller graph for this function:

The documentation for this class was generated from the following file: