diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index d4f1f2a13..dd5d956e4 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -344,6 +344,14 @@ struct HugeintSumOperation } }; +struct UhugeintSumOperation + : public ClusteredSumOperation, ClusteredAddOp> { + template + static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) { + RepeatedSumState::Combine(source, target, input, count); + } +}; + //! The sum of a DECIMAL is a DECIMAL(38) - finalizing throws if the sum does not fit in it template struct DecimalSumOperation : public OP { @@ -556,6 +564,15 @@ AggregateFunction GetSumAggregate(PhysicalType type) { function.SetFallible(); // adding HUGEINT values to the HUGEINT accumulator throws on overflow return function; } + case PhysicalType::UINT128: { + auto function = + AggregateFunction::UnaryAggregate, uhugeint_t, uhugeint_t, UhugeintSumOperation>( + LogicalType::UHUGEINT, LogicalType::UHUGEINT); + function.GetSignature().GetParameter(0).SetName("arg"); + function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT); + function.SetFallible(); // adding UHUGEINT values to the UHUGEINT accumulator throws on overflow + return function; + } default: throw InternalException("Unimplemented sum aggregate"); } @@ -843,6 +860,7 @@ AggregateFunctionSet SumFun::GetFunctions() { sum.AddFunction(GetSumAggregate(PhysicalType::INT32)); sum.AddFunction(GetSumAggregate(PhysicalType::INT64)); sum.AddFunction(GetSumAggregate(PhysicalType::INT128)); + sum.AddFunction(GetSumAggregate(PhysicalType::UINT128)); auto sum_double = AggregateFunction::UnaryAggregate, double, double, NumericSumOperation>( LogicalType::DOUBLE, LogicalType::DOUBLE); sum_double.GetSignature().GetParameter(0).SetName("arg"); diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp index 404fd7725..7b40dea4a 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp @@ -6,13 +6,14 @@ #include "duckdb/execution/reservoir_sample.hpp" #include "core_functions/aggregate/holistic_functions.hpp" #include "duckdb/planner/expression.hpp" -#include "duckdb/common/queue.hpp" #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" +#include "pcg_random.hpp" + #include #include -#include +#include namespace duckdb { @@ -22,36 +23,77 @@ namespace { constexpr double DEFAULT_QUANTILE = 0.5; constexpr int32_t DEFAULT_SAMPLE_SIZE = 8192; +//! The reservoir sampling of BaseReservoirSampling with all memory in the aggregate's arena +struct ReservoirQuantileSampler : public ReservoirSampler { + using Weight = std::pair; + + explicit ReservoirQuantileSampler(Weight *weights_p) : weights(weights_p) { + random.seed(1); + } + + pcg32 random; + //! The next element to sample + idx_t next_index_to_sample = 0; + //! The reservoir threshold of the current min entry + double min_weight_threshold = 0; + //! The reservoir index of the current min entry + idx_t min_weighted_entry_index = 0; + //! The number of entries seen since the last sample + idx_t num_entries_to_skip_b4_next_sample = 0; + //! Max-heap of [-random key, index] with room for the whole sample + Weight *weights; + idx_t weight_count = 0; + + const Weight &TopWeight() const { + D_ASSERT(weight_count > 0); + return weights[0]; + } + void PopWeight() { + std::pop_heap(weights, weights + weight_count); + weight_count--; + } + void PushWeight(double weight, idx_t index) { + new (weights + weight_count++) Weight(weight, index); + std::push_heap(weights, weights + weight_count); + } +}; +static_assert(std::is_trivially_destructible::value, "the sampler lives in an arena"); + +//! All memory of the state is allocated from the aggregate's arena, so the state needs no destructor template struct ReservoirQuantileState { T *v; idx_t len; idx_t pos; - BaseReservoirSampling *r_samp; - - void Resize(idx_t new_len) { - if (new_len <= len) { - return; - } - T *old_v = v; - v = (T *)realloc(v, new_len * sizeof(T)); - if (!v) { - free(old_v); - throw InternalException("Memory allocation failure"); - } - len = new_len; - } + idx_t capacity; + ReservoirQuantileSampler *r_samp; void ReplaceElement(T &input) { v[r_samp->min_weighted_entry_index] = input; r_samp->ReplaceElement(); } - void FillReservoir(idx_t sample_size, T element) { + void FillReservoir(idx_t sample_size, T element, ArenaAllocator &allocator) { if (pos < sample_size) { + if (pos == capacity) { + // grow lazily, so that small groups do not pay for the full sample size + const auto new_capacity = MinValue(len, MaxValue(1, capacity * 2)); + D_ASSERT(new_capacity > pos); + const auto new_size = new_capacity * sizeof(T); + v = reinterpret_cast( + v ? allocator.ReallocateAligned(data_ptr_cast(v), AlignValue(capacity * sizeof(T)), new_size) + : allocator.AllocateAligned(new_size)); + capacity = new_capacity; + } v[pos++] = element; - r_samp->InitializeReservoirWeights(pos, len); } else { + if (!r_samp) { + auto weights = allocator.AllocateAligned(len * sizeof(ReservoirQuantileSampler::Weight)); + auto sampler = allocator.Make( + reinterpret_cast(weights)); + sampler->InitializeReservoirWeights(pos, len); + r_samp = sampler; + } D_ASSERT(r_samp->next_index_to_sample >= r_samp->num_entries_to_skip_b4_next_sample); if (r_samp->next_index_to_sample == r_samp->num_entries_to_skip_b4_next_sample) { ReplaceElement(element); @@ -62,6 +104,28 @@ struct ReservoirQuantileState { } }; +struct ReservoirQuantileFinalizeState : FunctionLocalState { + static unique_ptr Init(const BoundAggregateFunction &, optional_ptr) { + return make_uniq(); + } + + template ::type> + static T *CopySample(const STATE &state, AggregateFinalizeData &finalize_data) { + D_ASSERT(finalize_data.input.local_state); + auto &scratch = finalize_data.input.local_state->Cast(); + const auto size = state.pos * sizeof(T); + if (scratch.buffer.GetSize() < size) { + scratch.buffer.Reset(); + scratch.buffer = finalize_data.input.allocator.GetUnderlyingAllocator().Allocate(NextPowerOfTwo(size)); + } + auto result = reinterpret_cast(scratch.buffer.get()); + memcpy(result, state.v, size); + return result; + } + + AllocatedData buffer; +}; + struct ReservoirQuantileBindData : public FunctionData { ReservoirQuantileBindData() : decimal_type(LogicalType::INVALID) { } @@ -119,40 +183,21 @@ struct ReservoirQuantileOperation { static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { auto &bind_data = unary_input.input.bind_data->template Cast(); if (state.pos == 0) { - state.Resize(bind_data.sample_size); + state.len = MaxValue(state.len, bind_data.sample_size); } - if (!state.r_samp) { - state.r_samp = new BaseReservoirSampling(); - } - D_ASSERT(state.v); - state.FillReservoir(bind_data.sample_size, input); + state.FillReservoir(bind_data.sample_size, input, unary_input.input.allocator); } template - static void Combine(const STATE &source, STATE &target, AggregateInputData &) { + static void Combine(const STATE &source, STATE &target, AggregateInputData &aggr_input_data) { if (source.pos == 0) { return; } if (target.pos == 0) { - target.Resize(source.len); - } - if (!target.r_samp) { - target.r_samp = new BaseReservoirSampling(); + target.len = MaxValue(target.len, source.len); } for (idx_t src_idx = 0; src_idx < source.pos; src_idx++) { - target.FillReservoir(target.len, source.v[src_idx]); - } - } - - template - static void Destroy(STATE &state, AggregateInputData &aggr_input_data) { - if (state.v) { - free(state.v); - state.v = nullptr; - } - if (state.r_samp) { - delete state.r_samp; - state.r_samp = nullptr; + target.FillReservoir(target.len, source.v[src_idx], aggr_input_data.allocator); } } @@ -171,7 +216,7 @@ struct ReservoirQuantileScalarOperation : public ReservoirQuantileOperation { D_ASSERT(state.v); D_ASSERT(finalize_data.input.bind_data); auto &bind_data = finalize_data.input.bind_data->template Cast(); - auto v_t = state.v; + auto v_t = ReservoirQuantileFinalizeState::CopySample(state, finalize_data); D_ASSERT(bind_data.quantiles.size() == 1); auto offset = (idx_t)((double)(state.pos - 1) * bind_data.quantiles[0]); std::nth_element(v_t, v_t + offset, v_t + state.pos); @@ -179,7 +224,7 @@ struct ReservoirQuantileScalarOperation : public ReservoirQuantileOperation { } }; -AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) { +AggregateFunction GetReservoirQuantileAggregateFunctionInternal(PhysicalType type) { switch (type) { case PhysicalType::INT8: return AggregateFunction::UnaryAggregate, int8_t, int8_t, @@ -218,6 +263,12 @@ AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) { } } +AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) { + auto fun = GetReservoirQuantileAggregateFunctionInternal(type); + fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init); + return fun; +} + template struct ReservoirQuantileListOperation : public ReservoirQuantileOperation { template @@ -235,12 +286,14 @@ struct ReservoirQuantileListOperation : public ReservoirQuantileOperation { ListVector::Reserve(finalize_data.result, ridx + bind_data.quantiles.size()); auto rdata = FlatVector::GetDataMutable(result); - auto v_t = state.v; - D_ASSERT(v_t); - + D_ASSERT(state.v); auto &entry = target; entry.offset = ridx; entry.length = bind_data.quantiles.size(); + if (entry.length == 0) { + return; + } + auto v_t = ReservoirQuantileFinalizeState::CopySample(state, finalize_data); for (size_t q = 0; q < entry.length; ++q) { const auto &quantile = bind_data.quantiles[q]; auto offset = (idx_t)((double)(state.pos - 1) * quantile); @@ -255,11 +308,13 @@ struct ReservoirQuantileListOperation : public ReservoirQuantileOperation { template AggregateFunction ReservoirQuantileListAggregate(const LogicalType &input_type, const LogicalType &child_type) { LogicalType result_type = LogicalType::LIST(child_type); - return AggregateFunction( + auto fun = AggregateFunction( {input_type}, result_type, AggregateFunction::StateSize, AggregateFunction::StateInitialize, AggregateFunction::UnaryScatterUpdate, AggregateFunction::StateCombine, AggregateFunction::StateFinalize, FunctionNullHandling::DEFAULT_NULL_HANDLING, - AggregateFunction::NoClusterUpdate(), AggregateFunction::NoBind(), AggregateFunction::StateDestroy); + AggregateFunction::NoClusterUpdate(), AggregateFunction::NoBind(), nullptr); + fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init); + return fun; } template @@ -377,6 +432,7 @@ static void SetDecimalImplementation(BoundAggregateFunction &function, const Log default: throw NotImplementedException("Invalid physical type for decimal reservoir quantile"); } + function.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init); } for (idx_t i = function.GetArguments().size(); i < declared_arguments.size(); i++) { function.GetArguments().push_back(declared_arguments[i]); @@ -463,6 +519,7 @@ void GetReservoirQuantileDecimalFunction(AggregateFunctionSet &set, const vector const LogicalType &return_value) { auto fun = AggregateFunction::UnaryAggregate, int64_t, int64_t, ReservoirQuantileScalarOperation>(arguments[0], return_value); + fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init); fun.SetBindCallback(BindReservoirQuantileDecimal); fun.SetSerializeCallback(ReservoirQuantileBindData::Serialize); fun.SetDeserializeCallback(DeserializeReservoirQuantileDecimal); diff --git a/src/duckdb/extension/core_functions/function_list.cpp b/src/duckdb/extension/core_functions/function_list.cpp index f3a50e279..41a1ac548 100644 --- a/src/duckdb/extension/core_functions/function_list.cpp +++ b/src/duckdb/extension/core_functions/function_list.cpp @@ -205,7 +205,6 @@ static const StaticFunctionDefinition core_functions[] = { DUCKDB_SCALAR_FUNCTION_SET(GreatestCommonDivisorFun), DUCKDB_AGGREGATE_FUNCTION_SET_ALIAS(GroupConcatFun), DUCKDB_SCALAR_FUNCTION(HammingFun), - DUCKDB_SCALAR_FUNCTION(HashFun), DUCKDB_SCALAR_FUNCTION_SET(HexFun), DUCKDB_AGGREGATE_FUNCTION_SET(HistogramFun), DUCKDB_AGGREGATE_FUNCTION(HistogramExactFun), diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp index 58f5d5330..0d9204152 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/sum_helpers.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/bignum.hpp" #include "duckdb/common/types/bignum.hpp" #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/types/uhugeint.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" @@ -85,6 +86,8 @@ struct RepeatedStateValue { return input * static_cast(count); } else if constexpr (std::is_same()) { return Hugeint::Multiply(input, Hugeint::Convert(count)); + } else if constexpr (std::is_same()) { + return Uhugeint::Multiply(input, Uhugeint::Convert(count)); } else if constexpr (std::is_same()) { const auto count64 = Cast::Operation(count); return MultiplyOperator::Operation(input, count64); @@ -140,6 +143,8 @@ template static inline void CombineSumStateValue(T &target, const T &source) { if constexpr (std::is_same::value) { target = Hugeint::Add(target, source); + } else if constexpr (std::is_same::value) { + target = Uhugeint::Add(target, source); } else { target += source; } @@ -192,6 +197,18 @@ struct HugeintAdd { } }; +struct UhugeintAdd { + template + static void AddNumber(STATE &state, T input) { + state.value = Uhugeint::Add(state.value, input); + } + + template + static void AddConstant(STATE &state, T input, idx_t count) { + RepeatedStateValue::AddRepeated(state, input, count); + } +}; + struct IntervalAdd { template static void AddNumber(STATE &state, T input) { diff --git a/src/duckdb/extension/core_functions/include/core_functions/scalar/generic_functions.hpp b/src/duckdb/extension/core_functions/include/core_functions/scalar/generic_functions.hpp index bab3b7f07..91e4b28d3 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/scalar/generic_functions.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/scalar/generic_functions.hpp @@ -35,16 +35,6 @@ struct CurrentSettingFun { static ScalarFunction GetFunction(); }; -struct HashFun { - static constexpr const char *Name = "hash"; - static constexpr const char *Parameters = "value"; - static constexpr const char *Description = "Returns a `UBIGINT` with the hash of the `value`. Note that this is not a cryptographic hash."; - static constexpr const char *Example = "hash('🦆')"; - static constexpr const char *Categories = "string"; - - static ScalarFunction GetFunction(); -}; - struct LeastFun { static constexpr const char *Name = "least"; static constexpr const char *Parameters = "arg1,..."; diff --git a/src/duckdb/extension/core_functions/scalar/date/date_trunc.cpp b/src/duckdb/extension/core_functions/scalar/date/date_trunc.cpp index af1bc0b62..2e71de05e 100644 --- a/src/duckdb/extension/core_functions/scalar/date/date_trunc.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/date_trunc.cpp @@ -611,7 +611,10 @@ ScalarFunctionSet DateTruncFun::GetFunctions() { ScalarFunction({}, LogicalType::INTERVAL, DateTruncFunction), LogicalType::INTERVAL)); date_trunc.ApplyToFunctions([](ScalarFunction &func) { func.SetFallible(); - func.SetArgProperties(1, ArgProperties().NonDecreasing()); + // Truncated interval components need not preserve the normalized interval ordering. + if (func.GetSignature().GetParameter(1).GetType() != LogicalType::INTERVAL) { + func.SetArgProperties(1, ArgProperties().NonDecreasing()); + } }); return date_trunc; } diff --git a/src/duckdb/extension/core_functions/scalar/generic/hash.cpp b/src/duckdb/extension/core_functions/scalar/generic/hash.cpp deleted file mode 100644 index d5280d4ec..000000000 --- a/src/duckdb/extension/core_functions/scalar/generic/hash.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "core_functions/scalar/generic_functions.hpp" - -namespace duckdb { - -static void HashFunction(DataChunk &args, ExpressionState &state, Vector &result) { - args.Hash(result); -} - -ScalarFunction HashFun::GetFunction() { - auto hash_fun = ScalarFunction({}, LogicalType::HASH, HashFunction); - hash_fun.GetSignature().AddParameter("value", LogicalType::ANY); - hash_fun.GetSignature().AddArgs("args", LogicalType::ANY); - hash_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); - // hash the arguments after their combinable collations - hash_fun.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); - return hash_fun; -} - -} // namespace duckdb diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 6c985fd54..99438ab47 100644 --- a/src/duckdb/generated_extension_loader_package_build.cpp +++ b/src/duckdb/generated_extension_loader_package_build.cpp @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de descriptor->version = 1; descriptor->name = "core_functions"; descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS; - descriptor->api_version = "v2.1.0-alpha57049"; + descriptor->api_version = "v2.1.0-alpha57096"; descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init; return 0; } @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto descriptor->version = 1; descriptor->name = "parquet"; descriptor->extension_version = EXT_VERSION_PARQUET; - descriptor->api_version = "v2.1.0-alpha57049"; + descriptor->api_version = "v2.1.0-alpha57096"; descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init; return 0; } @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) { descriptor->version = 1; descriptor->name = "icu"; descriptor->extension_version = EXT_VERSION_ICU; - descriptor->api_version = "v2.1.0-alpha57049"; + descriptor->api_version = "v2.1.0-alpha57096"; descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init; return 0; } @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor) descriptor->version = 1; descriptor->name = "json"; descriptor->extension_version = EXT_VERSION_JSON; - descriptor->api_version = "v2.1.0-alpha57049"; + descriptor->api_version = "v2.1.0-alpha57096"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/hive_partitioning.cpp b/src/duckdb/src/common/hive_partitioning.cpp index 8efac22e1..44b53db5f 100644 --- a/src/duckdb/src/common/hive_partitioning.cpp +++ b/src/duckdb/src/common/hive_partitioning.cpp @@ -518,7 +518,7 @@ static void GetHivePartitionValuesTypeSwitch(const Vector &input, vector global_state) : PartitionedColumnData(PartitionedColumnDataType::HIVE, context, std::move(types)), global_state(std::move(global_state)), group_by_columns(std::move(partition_by_cols)), - hashes_v(LogicalType::HASH) { + hasher(context, this->types, group_by_columns), hashes_v(LogicalType::HASH) { InitializeKeys(); CreateAllocator(); } diff --git a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp index 1e0f6abf1..499098891 100644 --- a/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_column_mapper.cpp @@ -497,8 +497,8 @@ static ColumnMapResult MapColumnStruct(ClientContext &context, const MultiFileCo child_mapping.column_index->SetType(local_column.type); child_mapping.column_index->SetPushdownExtract(); - mapping->child_mapping.emplace(MultiFileGlobalIndex(0), std::move(child_mapping.mapping)); - child_mapping.mapping = std::move(mapping); + // The scan returns the extracted value in this slot, so keep the selected field's child mapping. + child_mapping.mapping->index = mapping->index; } return child_mapping; } diff --git a/src/duckdb/src/common/random_engine.cpp b/src/duckdb/src/common/random_engine.cpp index 83c0ff760..ab93811b3 100644 --- a/src/duckdb/src/common/random_engine.cpp +++ b/src/duckdb/src/common/random_engine.cpp @@ -53,13 +53,11 @@ RandomEngine::~RandomEngine() { } double RandomEngine::NextRandom(double min, double max) { - D_ASSERT(max >= min); - return min + (NextRandom() * (max - min)); + return NextRandom(random_state->pcg, min, max); } double RandomEngine::NextRandom() { - auto uint64 = NextRandomInteger64(); - return std::ldexp(uint64, -64); + return NextRandom(random_state->pcg); } double RandomEngine::NextRandom32(double min, double max) { @@ -68,8 +66,7 @@ double RandomEngine::NextRandom32(double min, double max) { } double RandomEngine::NextRandom32() { - auto uint32 = NextRandomInteger(); - return std::ldexp(uint32, -32); + return NextRandom32(random_state->pcg); } uint32_t RandomEngine::NextRandomInteger() { @@ -77,7 +74,7 @@ uint32_t RandomEngine::NextRandomInteger() { } uint64_t RandomEngine::NextRandomInteger64() { - return (static_cast(NextRandomInteger()) << UINT64_C(32)) | static_cast(NextRandomInteger()); + return NextRandomInteger64(random_state->pcg); } uint32_t RandomEngine::NextRandomInteger(uint32_t min, uint32_t max) { diff --git a/src/duckdb/src/common/sort/full_sort.cpp b/src/duckdb/src/common/sort/full_sort.cpp index 40339704e..f2a8333bd 100644 --- a/src/duckdb/src/common/sort/full_sort.cpp +++ b/src/duckdb/src/common/sort/full_sort.cpp @@ -15,8 +15,6 @@ class FullSortGroup { public: FullSortGroup(ClientContext &client, const Sort &sort); - atomic count; - // Sink unique_ptr sort_global; @@ -24,7 +22,7 @@ class FullSortGroup { unique_ptr sort_source; }; -FullSortGroup::FullSortGroup(ClientContext &client, const Sort &sort) : count(0) { +FullSortGroup::FullSortGroup(ClientContext &client, const Sort &sort) { sort_global = sort.GetGlobalSinkState(client); } @@ -175,7 +173,6 @@ SinkResultType FullSort::Sink(ExecutionContext &context, DataChunk &input_chunk, auto &hash_group = *gstate.hash_group; OperatorSinkInput input {*hash_group.sort_global, *sort_local, sink.interrupt_state}; sort->Sink(context, payload_chunk, input); - hash_group.count += payload_chunk.size(); return SinkResultType::NEED_MORE_INPUT; } @@ -218,7 +215,11 @@ FullSortGlobalSourceState::FullSortGlobalSourceState(ClientContext &client, Full auto &hash_group = gsink.hash_group; if (hash_group) { - chunk_row.count = hash_group->count; + chunk_row.count = gsink.count; + const auto &partition_limit = gsink.full_sort.partition_limit; + if (partition_limit.IsValid()) { + chunk_row.count = MinValue(chunk_row.count, partition_limit.GetIndex()); + } chunk_row.chunks = (chunk_row.count + STANDARD_VECTOR_SIZE - 1) / STANDARD_VECTOR_SIZE; } @@ -229,8 +230,8 @@ FullSortGlobalSourceState::FullSortGlobalSourceState(ClientContext &client, Full // FullSort //===--------------------------------------------------------------------===// FullSort::FullSort(ClientContext &client, const vector &order_bys, const Types &input_types, - bool require_payload) - : SortStrategy(input_types) { + bool require_payload, optional_idx partition_limit) + : SortStrategy(input_types, partition_limit) { // We have to compute ordering expressions ourselves and materialise them. // To do this, we scan the orders and add generate extra payload columns that we can reference. for (const auto &order : order_bys) { @@ -322,7 +323,11 @@ FullSort::HashGroupPtr FullSort::GetColumnData(idx_t hash_bin, OperatorSourceInp // Just because MaterializeColumnData returned FINISHED doesn't mean that the same thread will // get the result... - if (result && result->Count() == hash_group.count) { + if (result && result->Count() == gsink.count) { + const auto &partition_limit = gsink.full_sort.partition_limit; + if (partition_limit.IsValid()) { + result->Truncate(partition_limit.GetIndex()); + } return result; } @@ -346,7 +351,7 @@ FullSort::SortedRunPtr FullSort::GetSortedRun(ClientContext &client, idx_t hash_ auto result = sort->GetSortedRun(sort_global); if (!result) { - D_ASSERT(hash_group.count == 0); + D_ASSERT(gsink.count == 0); result = make_uniq(client, *sort, false); } diff --git a/src/duckdb/src/common/sort/hashed_sort.cpp b/src/duckdb/src/common/sort/hashed_sort.cpp index 5e4fa5829..bf18a3856 100644 --- a/src/duckdb/src/common/sort/hashed_sort.cpp +++ b/src/duckdb/src/common/sort/hashed_sort.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/sorting/hashed_sort.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" #include "duckdb/main/client_context.hpp" @@ -9,7 +10,6 @@ #include "duckdb/common/types/row/integer_partitioned_tuple_data.hpp" #include "duckdb/storage/statistics/numeric_stats.hpp" #include "duckdb/common/types/hyperloglog.hpp" -#include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/parallel/thread_context.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -372,6 +372,7 @@ class HashedSortLocalSinkState : public LocalSinkState { ExpressionExecutor hash_exec; ExpressionExecutor sort_exec; DataChunk group_chunk; + unique_ptr group_hasher; DataChunk sort_chunk; DataChunk payload_chunk; @@ -409,6 +410,9 @@ HashedSortLocalSinkState::HashedSortLocalSinkState(ExecutionContext &context, co auto hash_types = hashed_sort.payload_types; group_chunk.Initialize(allocator, group_types); + if (!group_types.empty()) { + group_hasher = make_uniq(context.client, group_types); + } hash_types.emplace_back(LogicalType::HASH); payload_chunk.Initialize(allocator, hash_types); @@ -430,11 +434,7 @@ void HashedSortLocalSinkState::Hash(DataChunk &input_chunk, Vector &hash_vector) // OVER(PARTITION BY...) (hash grouping) group_chunk.Reset(); hash_exec.Execute(input_chunk, group_chunk); - const idx_t count = group_chunk.size(); - VectorOperations::Hash(group_chunk.data[0], hash_vector, count); - for (idx_t prt_idx = 1; prt_idx < group_chunk.ColumnCount(); ++prt_idx) { - VectorOperations::CombineHash(hash_vector, group_chunk.data[prt_idx], count); - } + group_hasher->Hash(group_chunk, hash_vector); } SinkResultType HashedSort::Sink(ExecutionContext &context, DataChunk &input_chunk, OperatorSinkInput &sink) const { diff --git a/src/duckdb/src/common/sort/sort_strategy.cpp b/src/duckdb/src/common/sort/sort_strategy.cpp index a30e64dff..0366bab2f 100644 --- a/src/duckdb/src/common/sort/sort_strategy.cpp +++ b/src/duckdb/src/common/sort/sort_strategy.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/sorting/hashed_sort.hpp" #include "duckdb/common/sorting/natural_sort.hpp" #include "duckdb/common/sorting/partitioned_sort.hpp" +#include "duckdb/common/sorting/topn_sort.hpp" #include "duckdb/common/types/row/tuple_data_collection.hpp" namespace duckdb { @@ -10,7 +11,8 @@ namespace duckdb { //===--------------------------------------------------------------------===// // SortStrategy //===--------------------------------------------------------------------===// -SortStrategy::SortStrategy(const Types &input_types) : payload_types(input_types) { +SortStrategy::SortStrategy(const Types &input_types, optional_idx partition_limit) + : payload_types(input_types), partition_limit(partition_limit) { // The payload prefix is the same as the input schema for (column_t i = 0; i < payload_types.size(); ++i) { scan_ids.emplace_back(i); @@ -36,14 +38,17 @@ unique_ptr SortStrategy::Factory(ClientContext &client, const vector &order_bys, const Types &payload_types, const vector> &partitions_stats, const OperatorPartitionInfo &partition_info, idx_t estimated_cardinality, - bool require_payload) { + bool require_payload, optional_idx partition_limit) { if (partition_info.RequiresPartitionColumns()) { return make_uniq(client, order_bys, payload_types, partition_info, require_payload); } else if (!partition_bys.empty()) { return make_uniq(client, partition_bys, order_bys, payload_types, partitions_stats, estimated_cardinality, require_payload); } else if (!order_bys.empty()) { - return make_uniq(client, order_bys, payload_types, require_payload); + if (TopNSort::CanOptimize(partition_limit, estimated_cardinality)) { + return make_uniq(client, order_bys, payload_types, partition_limit); + } + return make_uniq(client, order_bys, payload_types, require_payload, partition_limit); } else { return make_uniq(payload_types); } diff --git a/src/duckdb/src/common/sort/topn_heap.cpp b/src/duckdb/src/common/sort/topn_heap.cpp new file mode 100644 index 000000000..9b88229d5 --- /dev/null +++ b/src/duckdb/src/common/sort/topn_heap.cpp @@ -0,0 +1,538 @@ +#include "duckdb/common/sorting/topn_heap.hpp" +#include "duckdb/storage/buffer_manager.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// TopOneFunc +//===--------------------------------------------------------------------===// +// Simple scalar min/max aggregation +template +struct TopOneState { + using value_type = T; + bool is_set = false; + bool is_null; + value_type value; +}; + +template +struct TopOneOp { + using STATE = TopOneState; + + static idx_t Size() { + return sizeof(STATE); + } + + static optional_idx Update(data_ptr_t state_p, Vector &sort_key, const idx_t count) { + auto &state = *reinterpret_cast(state_p); + optional_idx result; + UnifiedVectorFormat format; + sort_key.ToUnifiedFormat(format); + const auto data = format.GetData(); + for (idx_t r = 0; r < count; ++r) { + const auto idx = format.sel->get_index(r); + STATE left; + left.is_null = !format.validity.RowIsValid(idx); + left.value = data[idx]; + auto &right = state; + if (!state.is_set || OP::Operation(left.value, right.value, left.is_null, right.is_null)) { + state = left; + state.is_set = true; + result = r; + } + } + + return result; + } + + static bool Combine(const_data_ptr_t source_p, data_ptr_t target_p) { + const auto &source = *reinterpret_cast(source_p); + auto &target = *reinterpret_cast(target_p); + if (!source.is_set) { + return false; + } else if (!target.is_set || OP::Operation(source.value, target.value, source.is_null, target.is_null)) { + target = source; + return true; + } + return false; + } +}; + +template +static unique_ptr MakeTopOneFunc() { + using OP = TopOneOp; + auto result = make_uniq(); + result->state_size = OP::Size; + result->update = OP::Update; + result->combine = OP::Combine; + + return result; +} + +template +static unique_ptr GetTopOneFunc(const BoundOrderByNode &order) { + auto &expr = *order.expression; + switch (expr.GetReturnType().InternalType()) { + case PhysicalType::BOOL: + return MakeTopOneFunc(); + case PhysicalType::INT8: + return MakeTopOneFunc(); + case PhysicalType::INT16: + return MakeTopOneFunc(); + case PhysicalType::INT32: + return MakeTopOneFunc(); + case PhysicalType::INT64: + return MakeTopOneFunc(); + case PhysicalType::UINT8: + return MakeTopOneFunc(); + case PhysicalType::UINT16: + return MakeTopOneFunc(); + case PhysicalType::UINT32: + return MakeTopOneFunc(); + case PhysicalType::UINT64: + return MakeTopOneFunc(); + case PhysicalType::INT128: + return MakeTopOneFunc(); + case PhysicalType::UINT128: + return MakeTopOneFunc(); + case PhysicalType::FLOAT: + return MakeTopOneFunc(); + case PhysicalType::DOUBLE: + return MakeTopOneFunc(); + case PhysicalType::INTERVAL: + return MakeTopOneFunc(); + default: + return nullptr; + } +} + +static unique_ptr TopOneFactory(const TopNHeap &heap) { + if (heap.offset > 0 || heap.limit != 1) { + return nullptr; + } + + const auto &orders = heap.orders; + if (orders.size() != 1) { + return nullptr; + } + + const auto &order = orders.front(); + switch (order.type) { + case OrderType::ASCENDING: + switch (order.null_order) { + case OrderByNullType::NULLS_LAST: + return GetTopOneFunc(order); + case OrderByNullType::NULLS_FIRST: + return GetTopOneFunc(order); + default: + break; + } + break; + case OrderType::DESCENDING: + switch (order.null_order) { + case OrderByNullType::NULLS_LAST: + return GetTopOneFunc(order); + case OrderByNullType::NULLS_FIRST: + return GetTopOneFunc(order); + default: + break; + } + break; + default: + break; + } + + return nullptr; +} + +//===--------------------------------------------------------------------===// +// TopNHeap +//===--------------------------------------------------------------------===// +TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types_p, + const vector &orders_p, const vector> ¬_distinct_from_p, + idx_t limit, idx_t offset) + : allocator(allocator), buffer_manager(BufferManager::GetBufferManager(context)), arena_allocator(allocator), + heap(arena_allocator), payload_types(payload_types_p), orders(orders_p), limit(limit), offset(offset), + heap_size(limit + offset), executor(context), sort_key_heap(allocator), matching_sel(STANDARD_VECTOR_SIZE), + final_sel(STANDARD_VECTOR_SIZE), true_sel(STANDARD_VECTOR_SIZE), false_sel(STANDARD_VECTOR_SIZE), + new_remaining_sel(STANDARD_VECTOR_SIZE) { + // initialize the executor and the sort_chunk + vector sort_types; + for (auto &order : orders) { + auto &expr = order.expression; + sort_types.push_back(expr->GetReturnType()); + executor.AddExpression(*expr); + not_distinct_from.push_back( + make_uniq(executor.GetContext(), *not_distinct_from_p[not_distinct_from.size()])); + modifiers.emplace_back(order.type, order.null_order); + } + vector sort_keys_type {LogicalType::BLOB}; + sort_keys.Initialize(allocator, sort_keys_type); + sort_chunk.Initialize(allocator, sort_types); + heap_data.Initialize(allocator, payload_types, InitialHeapAllocSize()); + + // Can we use a fast aggregate? + topone = TopOneFactory(*this); + if (topone) { + topone_state.resize(topone->state_size()); + } else { + // Set up heap-only data structures + heap.reserve(InitialHeapAllocSize()); + compare_chunk.Initialize(allocator, sort_types); + boundary_values.Initialize(allocator, sort_types); + auto boundary_compare_types = sort_types; + boundary_compare_types.insert(boundary_compare_types.end(), sort_types.begin(), sort_types.end()); + boundary_compare_chunk.InitializeEmpty(boundary_compare_types); + } +} + +TopNHeap::TopNHeap(ClientContext &context, const vector &payload_types, + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset) + : TopNHeap(context, BufferAllocator::Get(context), payload_types, orders, not_distinct_from, limit, offset) { +} + +TopNHeap::TopNHeap(ExecutionContext &context, const vector &payload_types, + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset) + : TopNHeap(context.client, BufferAllocator::Get(context.client), payload_types, orders, not_distinct_from, limit, + offset) { +} + +bool TopNHeap::CanOptimize(idx_t limit, idx_t cardinality) { + // only check if we should switch to full sorting if we have estimated cardinality + auto constant_limit = static_cast(limit); + auto child_card = static_cast(cardinality); + + // if the limit is > 0.7% of the child cardinality, sorting the whole table is faster + bool limit_is_large = constant_limit > 5000; + if (constant_limit > child_card * 0.007 && limit_is_large) { + return false; + } + + return true; +} + +void TopNHeap::AddSingleHeap(DataChunk &input, optional_ptr global_boundary) { + const auto count = input.size(); + const auto best = topone->update(topone_state.data(), sort_chunk.data[0], count); + if (!best.IsValid()) { + return; + } + + // copy over the input row to the payload chunk + idx_t match_count = 0; + matching_sel.set_index(match_count++, best.GetIndex()); + heap_data.Reset(); + heap_data.Append(input, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); + + // the new best row tightens the dynamic filter + if (global_boundary && global_boundary->dynamic_filter) { + sort_chunk.Slice(matching_sel, match_count); + sort_keys.Reset(); + auto &sort_keys_vec = sort_keys.data[0]; + CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec, sort_key_state); + global_boundary->UpdateValue(FlatVector::GetData(sort_keys_vec)[0]); + } +} + +void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { + // insert the sort keys into the priority queue + constexpr idx_t BASE_INDEX = NumericLimits::Maximum(); + + bool any_added = false; + auto sort_key_values = FlatVector::GetData(sort_keys_vec); + for (idx_t r = 0; r < input.size(); r++) { + auto &sort_key = sort_key_values[r]; + if (!EntryShouldBeAdded(sort_key)) { + continue; + } + // replace the previous top entry with the new entry + TopNEntry entry; + entry.sort_key = sort_key; + entry.index = BASE_INDEX + r; + AddEntryToHeap(entry); + any_added = true; + } + if (!any_added) { + // early-out: no matches + return; + } + + // for all matching entries we need to copy over the corresponding payload values + idx_t match_count = 0; + for (auto &entry : heap) { + if (entry.index < BASE_INDEX) { + continue; + } + // this entry was added in this chunk + // copy over the string to the string heap + entry.sort_key = sort_key_heap.AddBlob(entry.sort_key); + // to finalize the addition of this entry we need to move over the payload data + matching_sel.set_index(match_count, entry.index - BASE_INDEX); + entry.index = heap_data.size() + match_count; + match_count++; + } + + // copy over the input rows to the payload chunk + heap_data.Append(input, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); +} + +void TopNHeap::AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec) { + auto sort_key_values = FlatVector::GetData(sort_keys_vec); + idx_t base_index = heap_data.size(); + idx_t match_count = 0; + for (idx_t r = 0; r < input.size(); r++) { + auto &sort_key = sort_key_values[r]; + if (!EntryShouldBeAdded(sort_key)) { + continue; + } + // replace the previous top entry with the new entry + TopNEntry entry; + entry.sort_key = sort_key_heap.AddBlob(sort_key); + entry.index = base_index + match_count; + AddEntryToHeap(entry); + matching_sel.set_index(match_count++, r); + } + if (match_count == 0) { + // early-out: no matches + return; + } + + // copy over the input rows to the payload chunk + heap_data.Append(input, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); +} + +bool TopNHeap::CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &global_boundary) { + // An older local boundary remains valid if refreshing it would block. + const auto boundary_updated = global_boundary.TryGetBoundaryValue(boundary_val); + if (boundary_val.empty()) { + // no boundary value (yet) - don't do anything + return true; + } + if (boundary_updated) { + // new boundary value - decode + boundary_values.Reset(); + CreateSortKeyHelpers::DecodeSortKey(string_t(boundary_val), boundary_values, 0, modifiers); + for (auto &col : boundary_values.data) { + col.SetVectorType(VectorType::CONSTANT_VECTOR); + } + } + boundary_values.SetChildCardinality(sort_chunk.size()); + for (idx_t i = 0; i < orders.size(); i++) { + boundary_compare_chunk.data[i].Reference(sort_chunk.data[i]); + boundary_compare_chunk.data[orders.size() + i].Reference(boundary_values.data[i]); + } + boundary_compare_chunk.CheckCardinality(sort_chunk.size()); + + // we have boundary values + // from these boundary values, determine which values we should insert (if any) + idx_t final_count = 0; + + SelectionVector remaining_sel(nullptr); + idx_t remaining_count = sort_chunk.size(); + for (idx_t i = 0; i < orders.size() && remaining_count > 0; i++) { + if (remaining_sel.data()) { + compare_chunk.data[i].Slice(sort_chunk.data[i], remaining_sel, remaining_count); + } else { + compare_chunk.data[i].Reference(sort_chunk.data[i]); + } + bool is_last = i + 1 == orders.size(); + idx_t true_count; + if (orders[i].null_order == OrderByNullType::NULLS_LAST) { + if (orders[i].type == OrderType::ASCENDING) { + true_count = VectorOperations::DistinctLessThan(compare_chunk.data[i], boundary_values.data[i], + &remaining_sel, remaining_count, &true_sel, &false_sel); + } else { + true_count = VectorOperations::DistinctGreaterThanNullsFirst(compare_chunk.data[i], + boundary_values.data[i], &remaining_sel, + remaining_count, &true_sel, &false_sel); + } + } else { + D_ASSERT(orders[i].null_order == OrderByNullType::NULLS_FIRST); + if (orders[i].type == OrderType::ASCENDING) { + true_count = VectorOperations::DistinctLessThanNullsFirst(compare_chunk.data[i], + boundary_values.data[i], &remaining_sel, + remaining_count, &true_sel, &false_sel); + } else { + true_count = + VectorOperations::DistinctGreaterThan(compare_chunk.data[i], boundary_values.data[i], + &remaining_sel, remaining_count, &true_sel, &false_sel); + } + } + + if (true_count > 0) { + memcpy(final_sel.data() + final_count, true_sel.data(), true_count * sizeof(sel_t)); + final_count += true_count; + } + idx_t false_count = remaining_count - true_count; + if (!is_last && false_count > 0) { + // check what we should continue to check + remaining_count = not_distinct_from[i]->SelectExpression(boundary_compare_chunk, &new_remaining_sel, + nullptr, &false_sel, false_count); + remaining_sel.Initialize(new_remaining_sel); + } else { + break; + } + } + if (final_count == 0) { + return false; + } + if (final_count < sort_chunk.size()) { + sort_chunk.Slice(final_sel, final_count); + payload.Slice(final_sel, final_count); + } + return true; +} + +void TopNHeap::Sink(DataChunk &input, optional_ptr global_boundary) { + static constexpr idx_t SMALL_HEAP_THRESHOLD = 100; + + if (heap_size == 0) { + // LIMIT 0 without OFFSET - the heap can never hold any entry, so there is nothing to do + return; + } + + // compute the ordering values for the new chunk + sort_chunk.Reset(); + executor.Execute(input, sort_chunk); + + // LIMIT 1 without OFFSET and a single scalar column with NULLS LAST + if (topone) { + AddSingleHeap(input, global_boundary); + return; + } + + if (global_boundary) { + // if we have a global boundary value check which rows pass before doing anything + if (!CheckBoundaryValues(sort_chunk, input, *global_boundary)) { + // nothing in this chunk can be in the final result + return; + } + } + + // construct the sort key from the sort chunk + sort_keys.Reset(); + auto &sort_keys_vec = sort_keys.data[0]; + CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec, sort_key_state); + + if (heap_size <= SMALL_HEAP_THRESHOLD) { + AddSmallHeap(input, sort_keys_vec); + } else { + AddLargeHeap(input, sort_keys_vec); + } + + // if we modified the heap we might be able to update the global boundary + // note that the global boundary only applies to FULL heaps + if (!heap.empty() && heap.size() >= heap_size && global_boundary) { + global_boundary->UpdateValue(heap.front().sort_key); + } +} + +void TopNHeap::Combine(TopNHeap &other) { + // "other" is sorted at this point + idx_t match_count = 0; + if (topone) { + if (topone->combine(other.topone_state.data(), topone_state.data())) { + matching_sel.set_index(match_count++, 0); + heap_data.Reset(); + heap_data.Append(other.heap_data, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); + } + return; + } + + // merge the heap of other into this + for (idx_t i = 0; i < other.heap.size(); i++) { + // heap is full - check the latest entry + auto &other_entry = other.heap[i]; + auto &sort_key = other_entry.sort_key; + if (!EntryShouldBeAdded(sort_key)) { + break; // We can break out of the loop here since we sorted the heap + } + // add this entry + TopNEntry new_entry; + new_entry.sort_key = sort_key_heap.AddBlob(sort_key); + new_entry.index = heap_data.size() + match_count; + AddEntryToHeap(new_entry); + + matching_sel.set_index(match_count++, other_entry.index); + if (match_count >= STANDARD_VECTOR_SIZE) { + // flush + heap_data.Append(other.heap_data, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); + match_count = 0; + } + } + if (match_count > 0) { + // flush + heap_data.Append(other.heap_data, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); + match_count = 0; + } + Reduce(); +} + +void TopNHeap::Finalize() { + // For TopOne there is at most one entry. + if (topone && heap_data.size()) { + TopNEntry entry; + entry.index = 0; + AddEntryToHeap(entry); + } + + std::sort(heap.begin(), heap.end()); +} + +void TopNHeap::Reduce() { + if (heap_data.size() < ReduceThreshold()) { + // only reduce when we pass the reduce threshold + return; + } + // we have too many values in the heap - reduce them + StringHeap new_sort_heap(allocator); + DataChunk new_heap_data; + new_heap_data.Initialize(allocator, payload_types, heap.size()); + + SelectionVector new_payload_sel(heap.size()); + for (idx_t i = 0; i < heap.size(); i++) { + auto &entry = heap[i]; + // move the sort key to the new sort heap + entry.sort_key = new_sort_heap.AddBlob(entry.sort_key); + // move this heap entry to position X in the payload chunk + new_payload_sel.set_index(i, entry.index); + entry.index = i; + } + + // copy over the data from the current payload chunk to the new payload chunk + new_heap_data.Slice(heap_data, new_payload_sel, heap.size()); + new_heap_data.Flatten(); + + sort_key_heap.Destroy(); + sort_key_heap.Move(new_sort_heap); + heap_data.Reference(new_heap_data); +} + +void TopNHeap::InitializeScan(TopNScanState &state, bool exclude_offset) { + auto heap_copy = heap; + state.scan_order.resize(heap_copy.size()); + + // we sorted the heap in Finalize(), so we can sequentially here + // we do this because sorting the heap is much more efficient than popping one by one + for (idx_t i = 0; i < heap_copy.size(); i++) { + state.scan_order[i] = UnsafeNumericCast(heap_copy[i].index); + } + + state.pos = exclude_offset ? offset : 0; +} + +void TopNHeap::Scan(TopNScanState &state, DataChunk &chunk, idx_t &pos) { + if (pos >= state.scan_order.size()) { + return; + } + SelectionVector sel(state.scan_order.data() + pos, state.scan_order.size() - pos); + idx_t count = MinValue(STANDARD_VECTOR_SIZE, state.scan_order.size() - pos); + pos += STANDARD_VECTOR_SIZE; + + chunk.Reset(); + chunk.Slice(heap_data, sel, count); +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/sort/topn_sort.cpp b/src/duckdb/src/common/sort/topn_sort.cpp new file mode 100644 index 000000000..9b2cd00f2 --- /dev/null +++ b/src/duckdb/src/common/sort/topn_sort.cpp @@ -0,0 +1,326 @@ +#include "duckdb/common/sorting/topn_sort.hpp" +#include "duckdb/common/sorting/topn_heap.hpp" +#include "duckdb/common/types/column/column_data_collection.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/common/sorting/sorted_run.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// TopNSortGlobalSinkState +//===--------------------------------------------------------------------===// +class TopNSortGlobalSinkState : public GlobalSinkState { +public: + TopNSortGlobalSinkState(ClientContext &client, const TopNSort &topn); + + ProgressData GetSinkProgress(ClientContext &context, const ProgressData source) const { + // there is nothing to sort + return source; + } + + //! System and query state + ClientContext &client; + mutable mutex lock; + TopNHeap heap; + shared_ptr dynamic_filter; + TopNBoundaryValue boundary_value; + + // Threading + atomic count; + //! Keeps the sink progress monotonic + MonotonicProgress sink_progress; +}; + +TopNSortGlobalSinkState::TopNSortGlobalSinkState(ClientContext &client, const TopNSort &topn) + : client(client), + heap(client, topn.payload_types, topn.orders, topn.not_distinct_from, topn.partition_limit.GetIndex(), 0), + boundary_value(topn.orders[0], dynamic_filter), count(0) { +} + +//===--------------------------------------------------------------------===// +// TopNSortLocalSinkState +//===--------------------------------------------------------------------===// +class TopNSortLocalSinkState : public LocalSinkState { +public: + using LocalSortStatePtr = unique_ptr; + + TopNSortLocalSinkState(ExecutionContext &context, const TopNSort &topn); + + //! Global state + const TopNSort &topn; + + TopNHeap heap; + + //! Shared expression evaluation + ExpressionExecutor sort_exec; + DataChunk group_chunk; + DataChunk sort_chunk; + DataChunk payload_chunk; +}; + +TopNSortLocalSinkState::TopNSortLocalSinkState(ExecutionContext &context, const TopNSort &topn) + : topn(topn), + heap(context, topn.payload_types, topn.orders, topn.not_distinct_from, topn.partition_limit.GetIndex(), 0), + sort_exec(context.client) { + vector sort_types; + for (const auto &expr : topn.sort_exprs) { + sort_types.emplace_back(expr->GetReturnType()); + sort_exec.AddExpression(*expr); + } + sort_chunk.Initialize(context.client, sort_types); + + auto payload_types = topn.payload_types; + payload_chunk.Initialize(context.client, payload_types); +} + +//===--------------------------------------------------------------------===// +// Sink +//===--------------------------------------------------------------------===// +SinkResultType TopNSort::Sink(ExecutionContext &context, DataChunk &input_chunk, OperatorSinkInput &sink) const { + auto &gstate = sink.global_state.Cast(); + auto &lstate = sink.local_state.Cast(); + gstate.count += input_chunk.size(); + + // Payload prefix is the input data + auto &payload_chunk = lstate.payload_chunk; + payload_chunk.Reset(); + for (column_t i = 0; i < input_chunk.ColumnCount(); ++i) { + payload_chunk.data[i].Reference(input_chunk.data[i]); + } + + // Compute any sort columns that are not references and append them to the end of the payload + auto &sort_chunk = lstate.sort_chunk; + auto &sort_exec = lstate.sort_exec; + if (!sort_exprs.empty()) { + sort_chunk.Reset(); + sort_exec.Execute(input_chunk, sort_chunk); + for (column_t i = 0; i < sort_chunk.ColumnCount(); ++i) { + payload_chunk.data[input_chunk.ColumnCount() + i].Reference(sort_chunk.data[i]); + } + } + + // OVER(ORDER BY...) + lstate.heap.Sink(payload_chunk, &gstate.boundary_value); + lstate.heap.Reduce(); + + return SinkResultType::NEED_MORE_INPUT; +} + +//===--------------------------------------------------------------------===// +// Combine +//===--------------------------------------------------------------------===// +SinkCombineResultType TopNSort::Combine(ExecutionContext &context, OperatorSinkCombineInput &combine) const { + auto &gstate = combine.global_state.Cast(); + auto &lstate = combine.local_state.Cast(); + + // OVER(ORDER BY...) + // scan the local top N and append it to the global heap + lstate.heap.Finalize(); + lock_guard guard(gstate.lock); + gstate.heap.Combine(lstate.heap); + + return SinkCombineResultType::FINISHED; +} + +//===--------------------------------------------------------------------===// +// Finalize +//===--------------------------------------------------------------------===// +SinkFinalizeType TopNSort::Finalize(ClientContext &client, OperatorSinkFinalizeInput &finalize) const { + auto &gsink = finalize.global_state.Cast(); + + // Did we get any data? + if (!gsink.count) { + return SinkFinalizeType::NO_OUTPUT_POSSIBLE; + } + + // OVER(ORDER BY...) + gsink.heap.Finalize(); + + return SinkFinalizeType::READY; +} + +//===--------------------------------------------------------------------===// +// GetSinkProgress +//===--------------------------------------------------------------------===// +ProgressData TopNSort::GetSinkProgress(ClientContext &client, GlobalSinkState &gstate, + const ProgressData source) const { + auto &gsink = gstate.Cast(); + return gsink.GetSinkProgress(client, source); +} + +//===--------------------------------------------------------------------===// +// TopNSortGlobalSourceState +//===--------------------------------------------------------------------===// +class TopNSortGlobalSourceState : public GlobalSourceState { +public: + using ChunkRow = TopNSort::ChunkRow; + using ChunkRows = TopNSort::ChunkRows; + + TopNSortGlobalSourceState(ClientContext &client, TopNSortGlobalSinkState &gsink); + + TopNSortGlobalSinkState &gsink; + TopNScanState scan; + ChunkRows chunk_rows; + + // Parallel scan and build + static constexpr idx_t CHUNKS_PER_BATCH = 60; + static constexpr idx_t TUPLES_PER_BATCH = CHUNKS_PER_BATCH * STANDARD_VECTOR_SIZE; + + vector> batches; + idx_t total_rows; + atomic rows_scanned {0}; +}; + +TopNSortGlobalSourceState::TopNSortGlobalSourceState(ClientContext &client, TopNSortGlobalSinkState &gsink) + : gsink(gsink) { + if (!gsink.count) { + return; + } + + gsink.heap.InitializeScan(scan, true); + total_rows = scan.scan_order.size(); + + // One sorted group + ChunkRow chunk_row; + chunk_row.count = total_rows; + chunk_row.chunks = (chunk_row.count + STANDARD_VECTOR_SIZE - 1) / STANDARD_VECTOR_SIZE; + + chunk_rows.emplace_back(chunk_row); +} + +//===--------------------------------------------------------------------===// +// TopNSort +//===--------------------------------------------------------------------===// +bool TopNSort::CanOptimize(optional_idx limit, idx_t cardinality) { + if (!limit.IsValid() || !cardinality) { + return false; + } + + return TopNHeap::CanOptimize(limit.GetIndex(), cardinality); +} + +TopNSort::TopNSort(ClientContext &client, const vector &order_bys, const Types &input_types, + optional_idx partition_limit) + : SortStrategy(input_types, partition_limit) { + // We have to compute ordering expressions ourselves and materialise them. + // To do this, we scan the orders and add generate extra payload columns that we can reference. + for (const auto &order : order_bys) { + orders.emplace_back(order.Copy()); + } + + for (auto &order : orders) { + auto &expr = *order.expression; + if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) { + auto &ref = expr.Cast(); + sort_ids.emplace_back(ref.Index()); + continue; + } + + // Real expression - replace with a ref and save the expression + auto saved = std::move(order.expression); + const auto type = saved->GetReturnType(); + const auto idx = payload_types.size(); + order.expression = make_uniq(type, idx); + sort_ids.emplace_back(idx); + payload_types.emplace_back(type); + sort_exprs.emplace_back(std::move(saved)); + } + + const auto order_count = orders.size(); + for (idx_t order_idx = 0; order_idx < order_count; order_idx++) { + auto &type = orders[order_idx].expression->GetReturnType(); + not_distinct_from.push_back(BoundComparisonExpression::CreateOnColumns( + client, ExpressionType::COMPARE_NOT_DISTINCT_FROM, type, order_idx, type, order_count + order_idx)); + } +} + +unique_ptr TopNSort::GetGlobalSinkState(ClientContext &client) const { + return make_uniq(client, *this); +} + +unique_ptr TopNSort::GetLocalSinkState(ExecutionContext &context) const { + return make_uniq(context, *this); +} + +unique_ptr TopNSort::GetGlobalSourceState(ClientContext &client, GlobalSinkState &sink) const { + return make_uniq(client, sink.Cast()); +} + +const TopNSort::ChunkRows &TopNSort::GetHashGroups(GlobalSourceState &gstate) const { + auto &gsource = gstate.Cast(); + return gsource.chunk_rows; +} + +SourceResultType TopNSort::MaterializeColumnData(ExecutionContext &execution, idx_t hash_bin, + OperatorSourceInput &source) const { + auto &gsource = source.global_state.Cast(); + auto &gsink = gsource.gsink; + + // Build a range into a PartitionedColumnData + idx_t pos = DConstants::INVALID_INDEX; + idx_t end = DConstants::INVALID_INDEX; + optional_ptr batch_data; + + DataChunk chunk; + chunk.Initialize(execution.client, payload_types); + ColumnDataAppendState append; + for (;;) { + if (pos == end) { + // Obtain new scan indices from the global state + annotated_lock_guard guard(gsource.lock); + pos = gsource.scan.pos; + gsource.scan.pos += TopNSortGlobalSourceState::TUPLES_PER_BATCH; + end = gsource.scan.pos; + auto batch = make_uniq(execution.client, payload_types); + batch->InitializeAppend(append); + batch_data = batch.get(); + gsource.batches.emplace_back(std::move(batch)); + } + + chunk.Reset(); + gsink.heap.Scan(gsource.scan, chunk, pos); + if (chunk.size() == 0) { + break; + } + gsource.rows_scanned.fetch_add(chunk.size(), std::memory_order_relaxed); + batch_data->Append(append, chunk); + } + + return SourceResultType::FINISHED; +} + +TopNSort::HashGroupPtr TopNSort::GetColumnData(idx_t hash_bin, OperatorSourceInput &source) const { + auto &gsource = source.global_state.Cast(); + + D_ASSERT(hash_bin == 0); + + annotated_lock_guard guard(gsource.lock); + unique_ptr result; + for (auto &batch : gsource.batches) { + if (!result) { + result = std::move(batch); + } else { + result->Combine(*batch); + } + } + + if (result && result->Count() == gsource.rows_scanned.load()) { + return result; + } + + return nullptr; +} + +SourceResultType TopNSort::MaterializeSortedRun(ExecutionContext &context, idx_t hash_bin, + OperatorSourceInput &source) const { + return MaterializeColumnData(context, hash_bin, source); +} + +TopNSort::SortedRunPtr TopNSort::GetSortedRun(ClientContext &client, idx_t hash_bin, + OperatorSourceInput &source) const { + throw InternalException("TopNSort::GetSortedRun is not supported"); +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/types/column/column_data_collection.cpp b/src/duckdb/src/common/types/column/column_data_collection.cpp index 5b6acfb62..92cc89331 100644 --- a/src/duckdb/src/common/types/column/column_data_collection.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection.cpp @@ -3,7 +3,6 @@ #include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" -#include "duckdb/common/vector/map_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" @@ -1737,6 +1736,55 @@ void ColumnDataCollection::Swap(ColumnDataCollection &other) { std::swap(partition_index, other.partition_index); } +void ColumnDataCollection::Truncate(idx_t new_count) { + if (Count() <= new_count) { + return; + } + + // Run through the segments until we have too many rows + idx_t segment_index = 0; + idx_t segment_rows = 0; + for (; segment_index < segments.size(); ++segment_index) { + auto &segment = segments[segment_index]; + if (segment_rows + segment->count <= new_count) { + segment_rows += segment->count; + if (segment_rows <= new_count) { + continue; + } + segments.resize(segment_index + 1); + count = new_count; + break; + } + + // Replace the last partial segment with a truncated copy. + auto truncated = std::move(segment); + segments.resize(segment_index); + this->count = segment_rows; + + ColumnDataScanState scan; + DataChunk chunk; + InitializeScan(scan); + InitializeScanChunk(scan, chunk); + + // If this collection has finished_append true, then calling InitializeAppend is not valid. + // So build the tail into a new collection and Combine it back in. + auto tail = make_uniq(allocator, types); + ColumnDataAppendState append; + tail->InitializeAppend(append); + idx_t chunk_index = 0; + while (segment_rows < new_count) { + scan.current_chunk_state.properties = scan.properties; + truncated->ReadChunk(chunk_index++, scan.current_chunk_state, chunk, scan.column_ids); + idx_t append_count = MinValue(chunk.size(), new_count - segment_rows); + chunk.SetChildCardinality(append_count); + tail->Append(append, chunk); + segment_rows += append_count; + } + Combine(*tail); + break; + } +} + //===--------------------------------------------------------------------===// // Fetch //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/types/data_chunk.cpp b/src/duckdb/src/common/types/data_chunk.cpp index cb097b55f..db0b86454 100644 --- a/src/duckdb/src/common/types/data_chunk.cpp +++ b/src/duckdb/src/common/types/data_chunk.cpp @@ -430,25 +430,6 @@ unsafe_unique_array DataChunk::ToUnifiedFormat() { return unified_data; } -void DataChunk::Hash(Vector &result) { - D_ASSERT(result.GetType().id() == LogicalType::HASH); - auto hash_count = size(); - VectorOperations::Hash(data[0], result, hash_count); - for (idx_t i = 1; i < ColumnCount(); i++) { - VectorOperations::CombineHash(result, data[i], hash_count); - } -} - -void DataChunk::Hash(vector &column_ids, Vector &result) { - D_ASSERT(result.GetType().id() == LogicalType::HASH); - D_ASSERT(!column_ids.empty()); - auto hash_count = size(); - VectorOperations::Hash(data[column_ids[0]], result, hash_count); - for (idx_t i = 1; i < column_ids.size(); i++) { - VectorOperations::CombineHash(result, data[column_ids[i]], hash_count); - } -} - void DataChunk::Verify(ClientContext &context) { Verify(DatabaseInstance::GetDatabase(context)); } diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index 29850659f..a410b5444 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -111,15 +111,13 @@ bool Uhugeint::TryMultiply(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result) { } // if any of these products are set to a non-zero value, there is always an overflow - if (products[2][1] || products[1][0] || products[2][0]) { + if (products[3][0] || products[3][1] || products[3][2] || products[2][0] || products[2][1] || products[1][0]) { return false; } // if the high bits of any of these are set, there is always an overflow - if (products[1][1] & 0xffffffff00000000 || products[3][0] & 0xffffffff00000000 || - products[3][3] & 0xffffffff00000000 || products[3][2] & 0xffffffff00000000 || - products[3][1] & 0xffffffff00000000 || products[2][2] & 0xffffffff00000000 || - products[0][0] & 0xffffffff00000000) { + if (products[0][0] & 0xffffffff00000000 || products[1][1] & 0xffffffff00000000 || + products[2][2] & 0xffffffff00000000 || products[3][3] & 0xffffffff00000000) { return false; } @@ -146,6 +144,11 @@ bool Uhugeint::TryMultiply(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result) { second32 += third32 >> 32; first32 += second32 >> 32; + // check if the combination of the different products resulted in an overflow + if (first32 & 0xffffffff00000000) { + return false; + } + // remove carry from current digit fourth32 &= 0xffffffff; third32 &= 0xffffffff; diff --git a/src/duckdb/src/execution/aggregate_hashtable.cpp b/src/duckdb/src/execution/aggregate_hashtable.cpp index 89bb8b189..b46a8edc0 100644 --- a/src/duckdb/src/execution/aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/aggregate_hashtable.cpp @@ -1,4 +1,5 @@ #include "duckdb/execution/aggregate_hashtable.hpp" +#include "duckdb/planner/expression/bound_hash_expression.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/main/client_context.hpp" @@ -76,6 +77,11 @@ GroupedAggregateHashTable::GroupedAggregateHashTable(ClientContext &context_p, A layout_ptr = std::move(layout); hash_offset = layout_ptr->GetOffsets()[layout_ptr->ColumnCount() - 1]; + auto group_types = layout_ptr->GetTypes(); + group_types.pop_back(); + if (!group_types.empty()) { + hash_expression = BoundHashExpression::CreateOnColumns(context, group_types); + } // Partitioned data and pointer table InitializePartitionedData(); @@ -95,6 +101,15 @@ GroupedAggregateHashTable::GroupedAggregateHashTable(ClientContext &context_p, A state.unpartitioned_append_state.compute_reverse_partition_sel = true; } +void GroupedAggregateHashTable::HashGroups(DataChunk &groups, AggregateHTProbeState &probe_state, + Vector &hashes) const { + D_ASSERT(hash_expression); + if (!probe_state.hash_executor) { + probe_state.hash_executor = make_uniq(context, *hash_expression); + } + BoundHashExpression::Execute(*probe_state.hash_executor, groups, hashes); +} + void GroupedAggregateHashTable::InitializePartitionedData() { tuple_size_cache.count.SetInvalid(); if (!partitioned_data || @@ -449,7 +464,7 @@ idx_t GroupedAggregateHashTable::AddChunk(DataChunk &groups, DataChunk &payload, } adaptivity.AddInput(groups.size()); - groups.Hash(state.hashes); + HashGroups(groups, state, state.hashes); const auto new_group_count = FindOrCreateGroups(groups, state.hashes, state.addresses, state.new_groups); before_update(state.addresses, state.new_groups, new_group_count); VectorOperations::AddInPlace(state.addresses, NumericCast(layout_ptr->GetAggrOffset())); @@ -471,7 +486,7 @@ idx_t GroupedAggregateHashTable::AddChunkAndGetNewGroups(DataChunk &groups, Data } adaptivity.AddInput(groups.size()); - groups.Hash(state.hashes); + HashGroups(groups, state, state.hashes); const auto new_group_count = FindOrCreateGroups(groups, state.hashes, state.addresses, state.new_groups); auto source_addresses = FlatVector::GetData(state.addresses); auto target_addresses = FlatVector::GetDataMutable(new_group_addresses); @@ -568,7 +583,7 @@ optional_idx GroupedAggregateHashTable::TryAddDictionaryGroups(DataChunk &groups unique_values.CheckCardinality(unique_count); // now we know which entries we are going to add - hash them auto &hashes = dict_state.hashes; - unique_values.Hash(hashes); + HashGroups(unique_values, state, hashes); // add the dictionary groups to the hash table new_group_count = FindOrCreateGroups(unique_values, hashes, new_dictionary_pointers, state.new_groups); @@ -640,7 +655,7 @@ optional_idx GroupedAggregateHashTable::TryAddConstantGroups(DataChunk &groups, groups.SetChildCardinality(row_count); auto &hashes = dict_state.hashes; - unique_values.Hash(hashes); + HashGroups(unique_values, state, hashes); // add the single constant group to the hash table auto &new_dictionary_pointers = dict_state.new_dictionary_pointers; @@ -699,7 +714,7 @@ idx_t GroupedAggregateHashTable::AddChunk(DataChunk &groups, DataChunk &payload, return result.GetIndex(); } // otherwise append the raw values - groups.Hash(state.hashes); + HashGroups(groups, state, state.hashes); return AddChunk(groups, state.hashes, payload, filter); } @@ -1066,7 +1081,7 @@ void GroupedAggregateHashTable::FindOrCreateGroups(DataChunk &groups, Vector &ad idx_t GroupedAggregateHashTable::FindOrCreateGroups(DataChunk &groups, Vector &addresses_out, SelectionVector &new_groups_out) { - groups.Hash(state.hashes); + HashGroups(groups, state, state.hashes); return FindOrCreateGroups(groups, state.hashes, addresses_out, new_groups_out); } @@ -1097,7 +1112,7 @@ idx_t GroupedAggregateHashTable::LookupGroups(DataChunk &groups, AggregateHTLook } InitializeLookupState(lookup_state); - groups.Hash(lookup_state.hashes); + HashGroups(groups, lookup_state, lookup_state.hashes); for (idx_t group_idx = 0; group_idx < groups.ColumnCount(); group_idx++) { lookup_state.group_chunk.data[group_idx].Reference(groups.data[group_idx]); } diff --git a/src/duckdb/src/execution/expression_executor/execute_operator.cpp b/src/duckdb/src/execution/expression_executor/execute_operator.cpp index be0ca9679..be793cabb 100644 --- a/src/duckdb/src/execution/expression_executor/execute_operator.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_operator.cpp @@ -159,8 +159,8 @@ bool ExpressionExecutor::ExecuteErrorCapture(const Expression &child, Expression flag_writer = make_uniq>(*error_flags, count, 0ULL); } for (idx_t i = 0; i < count; i++) { + // the reset vector is empty: a CASE/COALESCE result only covers the row it writes, not the rows below it intermediate.Reset(); - intermediate.SetChildCardinality(1); // clear any dictionary states in the child expression, so that it is executed anew for every row child_state.ResetDictionaryStates(); diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 52887954a..bc52ae94e 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -1,6 +1,7 @@ #include #include "duckdb/execution/join_hashtable.hpp" +#include "duckdb/planner/expression/bound_hash_expression.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/vector/dictionary_vector.hpp" @@ -145,6 +146,10 @@ JoinHashTable::JoinHashTable(ClientContext &context_p, const PhysicalOperator &o } // at least one equality is necessary D_ASSERT(!equality_types.empty()); + hash_expression = BoundHashExpression::CreateOnColumns(context, equality_types); + for (idx_t key_idx = 0; key_idx < equality_types.size(); key_idx++) { + key_hash_expressions.push_back(BoundHashExpression::CreateOnColumns(context, equality_types, {key_idx})); + } if (join_type == JoinType::SINGLE) { single_join_error_on_multiple_rows = Settings::Get(context); @@ -461,7 +466,7 @@ void JoinHashTable::GetRowPointers(DataChunk &keys, TupleDataChunkState &key_sta } auto &hashes = precomputed_hashes ? *precomputed_hashes : state.hashes; if (!precomputed_hashes) { - Hash(keys, sel ? *sel : *FlatVector::IncrementalSelectionVector(), count, hashes); + Hash(keys, state.hash_executor, hashes); } auto entries = GetEntries(); if (UseSalt()) { @@ -473,20 +478,12 @@ void JoinHashTable::GetRowPointers(DataChunk &keys, TupleDataChunkState &key_sta } } -void JoinHashTable::Hash(DataChunk &keys, const SelectionVector &sel, idx_t count, Vector &hashes) { - if (count == keys.size()) { - // no null values are filtered: use regular hash functions - VectorOperations::Hash(keys.data[0], hashes, count); - for (idx_t i = 1; i < equality_types.size(); i++) { - VectorOperations::CombineHash(hashes, keys.data[i], count); - } - } else { - // null values were filtered: use selection vector - VectorOperations::Hash(keys.data[0], hashes, sel, count); - for (idx_t i = 1; i < equality_types.size(); i++) { - VectorOperations::CombineHash(hashes, keys.data[i], sel, count); - } +void JoinHashTable::Hash(DataChunk &keys, unique_ptr &executor, Vector &hashes) const { + // rows that are filtered out (e.g., NULL keys) are hashed too, their hashes are not read + if (!executor) { + executor = make_uniq(context, *hash_expression); } + BoundHashExpression::Execute(*executor, keys, hashes); } static idx_t FilterNullValues(UnifiedVectorFormat &vdata, const SelectionVector &sel, idx_t count, @@ -812,7 +809,7 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu // hash the keys and obtain an entry in the list // note that we only hash the keys used in the equality comparison - Hash(keys, *current_sel, added_count, hash_values); + Hash(keys, build_hash_executor, hash_values); if (!bloom_filters.empty() && HasSingleEqualityKey()) { // The hash-table hashes already describe this one key. auto &filter = bloom_filters[0]; @@ -822,17 +819,16 @@ void JoinHashTable::Build(PartitionedTupleDataAppendState &append_state, DataChu } else if (!bloom_filters.empty()) { // the per-key-column filters of an external join with several equality keys auto &key_hashes = state.hashes.data[1]; + if (!build_key_hash_executor) { + build_key_hash_executor = make_uniq(context, key_hash_expressions); + } for (idx_t key_idx = 0; key_idx < bloom_filters.size(); key_idx++) { auto &filter = bloom_filters[key_idx]; if (!filter) { continue; } D_ASSERT(!filter->IsSealed()); - if (added_count == keys.size()) { - VectorOperations::Hash(keys.data[key_idx], key_hashes, added_count); - } else { - VectorOperations::Hash(keys.data[key_idx], key_hashes, *current_sel, added_count); - } + BoundHashExpression::Execute(*build_key_hash_executor, keys, key_hashes, key_idx); filter->InsertHashes(key_hashes, *current_sel, added_count); } } @@ -1260,7 +1256,8 @@ void JoinHashTable::MergePrefixRangeBuildState(PrefixRangeBuildStates &states) { } } -JoinHashTable::KeyFilterBuildScratch::KeyFilterBuildScratch(JoinHashTable &ht) : hashes(LogicalType::HASH) { +JoinHashTable::KeyFilterBuildScratch::KeyFilterBuildScratch(JoinHashTable &ht) + : hashes(LogicalType::HASH), key_hash_executor(ht.context, ht.key_hash_expressions) { vector types; for (idx_t key_idx = 0; key_idx < ht.equality_predicate_columns.size(); key_idx++) { types.push_back(ht.layout_ptr->GetTypes()[key_idx]); @@ -1278,7 +1275,9 @@ void JoinHashTable::InsertKeyBloomFilterChunk(TupleDataChunkState &chunk_state, } auto &build_keys = scratch.keys.data[key_idx]; GatherKeyColumn(chunk_state, count, key_idx, build_keys); - VectorOperations::Hash(build_keys, scratch.hashes, count); + // only the gathered key column is read + scratch.keys.SetCardinalityUnsafe(count); + BoundHashExpression::Execute(scratch.key_hash_executor, scratch.keys, scratch.hashes, key_idx); filter->InsertHashes(scratch.hashes, *FlatVector::IncrementalSelectionVector(), count); } } @@ -3124,7 +3123,7 @@ void JoinHashTable::ProbeAndSpill(ScanStructure &scan_structure, DataChunk &prob } probe_state.spill_hashes->Reset(); auto &hashes = probe_state.spill_hashes->data[0]; - Hash(probe_keys, *FlatVector::IncrementalSelectionVector(), probe_keys.size(), hashes); + Hash(probe_keys, probe_state.hash_executor, hashes); // Probe keys and output can retain this selection until the next batch has already started. SelectionVector true_sel(STANDARD_VECTOR_SIZE); diff --git a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp index a60bfeef0..7f819a52e 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp @@ -34,8 +34,7 @@ class StreamingWindowState : public OperatorState { public: AggregateState(ClientContext &client, BoundWindowExpression &wexpr, Allocator &allocator) : wexpr(wexpr), arena_allocator(BufferAllocator::Get((client))), executor(client), filter_executor(client), - statev(LogicalType::POINTER, data_ptr_cast(&state_ptr), 1ULL), hashes(LogicalType::HASH), - addresses(LogicalType::POINTER) { + statev(LogicalType::POINTER, data_ptr_cast(&state_ptr), 1ULL), addresses(LogicalType::POINTER) { D_ASSERT(wexpr.GetExpressionType() == ExpressionType::WINDOW_AGGREGATE); auto &aggregate = *wexpr.AggregateFunction(); bind_data = wexpr.BindInfo().get(); @@ -106,8 +105,6 @@ class StreamingWindowState : public OperatorState { unique_ptr distinct; //! Filtered arguments for checking distinctness DataChunk distinct_args; - //! Reusable hash vector - Vector hashes; //! Rows that produced new distinct values SelectionVector distinct_sel; //! Pointers to groups in the hash table. @@ -269,11 +266,8 @@ void StreamingWindowState::AggregateState::Execute(ExecutionContext &context, Da auto &distinct_sel = aggr_state.distinct_sel; if (filtered) { // FindOrCreateGroups assumes non-empty input - auto &hashes = aggr_state.hashes; - distinct_args.Hash(hashes); - auto &addresses = aggr_state.addresses; - distinct = aggr_state.distinct->FindOrCreateGroups(distinct_args, hashes, addresses, distinct_sel); + distinct = aggr_state.distinct->FindOrCreateGroups(distinct_args, addresses, distinct_sel); } // Translate the distinct selection from filtered row numbers diff --git a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp index 3b0c69684..fb26a303e 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp @@ -269,10 +269,10 @@ class WindowLocalSinkState : public LocalSinkState { // this implements a sorted window functions variant PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, vector> select_list_p, idx_t estimated_cardinality, - vector partitions) + vector partitions, optional_idx partition_limit) : PhysicalOperator(physical_plan, TYPE, std::move(types), estimated_cardinality), select_list(std::move(select_list_p)), order_idx(0), is_order_dependent(false), - partition_info(std::move(partitions)) { + partition_info(std::move(partitions)), partition_limit(partition_limit) { idx_t max_orders = 0; for (idx_t i = 0; i < select_list.size(); ++i) { auto &expr = select_list[i]; @@ -315,9 +315,10 @@ PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &conte } PhysicalWindow::PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, - vector> select_list, idx_t estimated_cardinality) + vector> select_list, idx_t estimated_cardinality, + optional_idx partition_limit) : PhysicalWindow(physical_plan, context, std::move(types), std::move(select_list), estimated_cardinality, - vector()) { + vector(), partition_limit) { } unique_ptr WindowExecutor::Factory(BoundWindowExpression &wexpr, ClientContext &client, @@ -345,7 +346,8 @@ WindowGlobalSinkState::WindowGlobalSinkState(const PhysicalWindow &op, ClientCon } sort_strategy = SortStrategy::Factory(client, wexpr.Partitions(), wexpr.OrderBy(), op.children[0].get().GetTypes(), - wexpr.PartitionsStats(), op.partition_info, op.estimated_cardinality); + wexpr.PartitionsStats(), op.partition_info, op.estimated_cardinality, false, + op.partition_limit); strategy_sink = sort_strategy->GetGlobalSinkState(client); } @@ -1264,6 +1266,11 @@ InsertionOrderPreservingMap PhysicalWindow::ParamsToString() const { projections += select_list[i]->GetName(); } result["Projections"] = projections; + + if (partition_limit.IsValid()) { + result["Limit"] = to_string(partition_limit.GetIndex()); + } + SetEstimatedCardinality(result, estimated_cardinality); return result; } diff --git a/src/duckdb/src/execution/operator/join/physical_recursive_cte_key_join.cpp b/src/duckdb/src/execution/operator/join/physical_recursive_cte_key_join.cpp index c85084f96..9141c5f1f 100644 --- a/src/duckdb/src/execution/operator/join/physical_recursive_cte_key_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_recursive_cte_key_join.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/chrono.hpp" #include "duckdb/common/row_operations/row_operations.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" @@ -129,7 +130,8 @@ class RecursiveCTEKeyJoinState : public CachingOperatorState { matched_input_sel(STANDARD_VECTOR_SIZE), candidate_input_sel(STANDARD_VECTOR_SIZE), candidate_match_sel(STANDARD_VECTOR_SIZE), candidate_addresses(LogicalType::POINTER), matched_addresses(LogicalType::POINTER), probe_hashes(LogicalType::HASH), - key_formats(op.Layout().ProbeKeyTypes().size()), arena(Allocator::Get(context)), row_state(arena) { + probe_hasher(context, op.Layout().ProbeKeyTypes()), key_formats(op.Layout().ProbeKeyTypes().size()), + arena(Allocator::Get(context)), row_state(arena) { probe_keys.Initialize(Allocator::Get(context), op.Layout().ProbeKeyTypes()); if (!op.Layout().ProbeKeyNormalizers().empty()) { probe_key_executor = make_uniq(context); @@ -187,6 +189,7 @@ class RecursiveCTEKeyJoinState : public CachingOperatorState { Vector candidate_addresses; Vector matched_addresses; Vector probe_hashes; + ChunkHasher probe_hasher; vector key_formats; unique_ptr probe_key_executor; unique_ptr hash_table_state; @@ -314,7 +317,7 @@ RecursiveCTEKeyJoinResult RecursiveCTEKeyJoinState::ProbePartialKey(DataChunk &i if (valid_probe_count == 0) { return {0, OperatorResultType::NEED_MORE_INPUT}; } - probe_keys.Hash(probe_hashes); + probe_hasher.Hash(probe_keys, probe_hashes); valid_probe_position = 0; active_probe = false; partial_input_initialized = true; diff --git a/src/duckdb/src/execution/operator/order/physical_top_n.cpp b/src/duckdb/src/execution/operator/order/physical_top_n.cpp index b96808dc2..8a0662665 100644 --- a/src/duckdb/src/execution/operator/order/physical_top_n.cpp +++ b/src/duckdb/src/execution/operator/order/physical_top_n.cpp @@ -2,14 +2,12 @@ #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/common/atomic.hpp" -#include "duckdb/common/assert.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/arena_containers/arena_vector.hpp" +#include "duckdb/common/sorting/topn_heap.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/function/create_sort_key.hpp" -#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/data_table.hpp" -#include "duckdb/planner/filter/table_filter_function_helpers.hpp" namespace duckdb { @@ -29,491 +27,11 @@ PhysicalTopN::PhysicalTopN(PhysicalPlan &physical_plan, ClientContext &context, PhysicalTopN::~PhysicalTopN() { } -//===--------------------------------------------------------------------===// -// Heaps -//===--------------------------------------------------------------------===// -class TopNHeap; - -struct TopNEntry { - string_t sort_key; - idx_t index; - - bool operator<(const TopNEntry &other) const { - return sort_key < other.sort_key; - } -}; - -struct TopNScanState { - TopNScanState() : pos(0), sel(STANDARD_VECTOR_SIZE) { - } - - idx_t pos; - vector scan_order; - SelectionVector sel; -}; - -struct TopNBoundaryValue { - explicit TopNBoundaryValue(const PhysicalTopN &op) - : op(op), boundary_vector(op.orders[0].expression->GetReturnType()), - boundary_modifiers(op.orders[0].type, op.orders[0].null_order) { - } - - const PhysicalTopN &op; - mutex lock; - string boundary_value; - bool is_set = false; - Vector boundary_vector; - OrderModifiers boundary_modifiers; - - bool TryGetBoundaryValue(string ¤t_boundary) { - unique_lock l(lock, std::try_to_lock); - if (!l.owns_lock() || boundary_value == current_boundary) { - return false; - } - current_boundary = boundary_value; - return true; - } - - void UpdateValue(string_t boundary_val) { - unique_lock l(lock); - if (!is_set || boundary_val < string_t(boundary_value)) { - boundary_value = boundary_val.GetString(); - is_set = true; - if (op.dynamic_filter) { - CreateSortKeyHelpers::DecodeSortKey(boundary_val, boundary_vector, 0, boundary_modifiers); - auto new_dynamic_value = boundary_vector.GetValue(0); - l.unlock(); - op.dynamic_filter->SetValue(std::move(new_dynamic_value)); - } - } - } -}; - -class TopNHeap { -public: - TopNHeap(ClientContext &context, const vector &payload_types, const vector &orders, - const vector> ¬_distinct_from, idx_t limit, idx_t offset); - TopNHeap(ExecutionContext &context, const vector &payload_types, - const vector &orders, const vector> ¬_distinct_from, - idx_t limit, idx_t offset); - TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types, - const vector &orders, const vector> ¬_distinct_from, - idx_t limit, idx_t offset); - - Allocator &allocator; - BufferManager &buffer_manager; - ArenaAllocator arena_allocator; - unsafe_arena_vector heap; - const vector &payload_types; - const vector &orders; - vector modifiers; - idx_t limit; - idx_t offset; - idx_t heap_size; - ExpressionExecutor executor; - //! NOT DISTINCT FROM comparison of every sort column - vector> not_distinct_from; - DataChunk sort_chunk; - DataChunk heap_data; - DataChunk payload_chunk; - DataChunk sort_keys; - CreateSortKeyState sort_key_state; - StringHeap sort_key_heap; - - SelectionVector matching_sel; - - DataChunk compare_chunk; - //! Cached global boundary value as a set of constant vectors - DataChunk boundary_values; - //! The input of not_distinct_from: [sort columns..., boundary values...] - DataChunk boundary_compare_chunk; - //! Cached global boundary value in sort-key format - string boundary_val; - SelectionVector final_sel; - SelectionVector true_sel; - SelectionVector false_sel; - SelectionVector new_remaining_sel; - -public: - void Sink(DataChunk &input, optional_ptr boundary_value = nullptr); - void Combine(TopNHeap &other); - void Reduce(); - void Finalize(); - - void InitializeScan(TopNScanState &state, bool exclude_offset); - void Scan(TopNScanState &state, DataChunk &chunk, idx_t &pos); - - bool CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &boundary_val); - void AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec); - void AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec); - -public: - idx_t ReduceThreshold() const { - return MaxValue(STANDARD_VECTOR_SIZE * 5ULL, 2ULL * heap_size); - } - - idx_t InitialHeapAllocSize() const { - return MinValue(STANDARD_VECTOR_SIZE * 100ULL, ReduceThreshold()) + STANDARD_VECTOR_SIZE; - } - -private: - inline bool EntryShouldBeAdded(const string_t &sort_key) { - if (heap_size == 0) { - // the heap has no capacity (LIMIT 0) - no entry can ever be added - return false; - } - if (heap.size() < heap_size) { - // heap is not full yet - the entry can be added - return true; - } - if (sort_key < heap.front().sort_key) { - // sort key is smaller than current max value - return true; - } - // heap is full and there is no room for the entry - return false; - } - - inline void AddEntryToHeap(const TopNEntry &entry) { - D_ASSERT(heap_size > 0); - if (heap.size() >= heap_size) { - D_ASSERT(!heap.empty()); - std::pop_heap(heap.begin(), heap.end()); - heap.pop_back(); - } - heap.push_back(entry); - std::push_heap(heap.begin(), heap.end()); - } -}; - -//===--------------------------------------------------------------------===// -// TopNHeap -//===--------------------------------------------------------------------===// -TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types_p, - const vector &orders_p, const vector> ¬_distinct_from_p, - idx_t limit, idx_t offset) - : allocator(allocator), buffer_manager(BufferManager::GetBufferManager(context)), arena_allocator(allocator), - heap(arena_allocator), payload_types(payload_types_p), orders(orders_p), limit(limit), offset(offset), - heap_size(limit + offset), executor(context), sort_key_heap(allocator), matching_sel(STANDARD_VECTOR_SIZE), - final_sel(STANDARD_VECTOR_SIZE), true_sel(STANDARD_VECTOR_SIZE), false_sel(STANDARD_VECTOR_SIZE), - new_remaining_sel(STANDARD_VECTOR_SIZE) { - // initialize the executor and the sort_chunk - vector sort_types; - for (auto &order : orders) { - auto &expr = order.expression; - sort_types.push_back(expr->GetReturnType()); - executor.AddExpression(*expr); - not_distinct_from.push_back( - make_uniq(executor.GetContext(), *not_distinct_from_p[not_distinct_from.size()])); - modifiers.emplace_back(order.type, order.null_order); - } - heap.reserve(InitialHeapAllocSize()); - vector sort_keys_type {LogicalType::BLOB}; - sort_keys.Initialize(allocator, sort_keys_type); - heap_data.Initialize(allocator, payload_types, InitialHeapAllocSize()); - payload_chunk.Initialize(allocator, payload_types); - sort_chunk.Initialize(allocator, sort_types); - compare_chunk.Initialize(allocator, sort_types); - boundary_values.Initialize(allocator, sort_types); - auto boundary_compare_types = sort_types; - boundary_compare_types.insert(boundary_compare_types.end(), sort_types.begin(), sort_types.end()); - boundary_compare_chunk.InitializeEmpty(boundary_compare_types); -} - -TopNHeap::TopNHeap(ClientContext &context, const vector &payload_types, - const vector &orders, const vector> ¬_distinct_from, - idx_t limit, idx_t offset) - : TopNHeap(context, BufferAllocator::Get(context), payload_types, orders, not_distinct_from, limit, offset) { -} - -TopNHeap::TopNHeap(ExecutionContext &context, const vector &payload_types, - const vector &orders, const vector> ¬_distinct_from, - idx_t limit, idx_t offset) - : TopNHeap(context.client, BufferAllocator::Get(context.client), payload_types, orders, not_distinct_from, limit, - offset) { -} - -void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { - // insert the sort keys into the priority queue - constexpr idx_t BASE_INDEX = NumericLimits::Maximum(); - - bool any_added = false; - auto sort_key_values = FlatVector::GetData(sort_keys_vec); - for (idx_t r = 0; r < input.size(); r++) { - auto &sort_key = sort_key_values[r]; - if (!EntryShouldBeAdded(sort_key)) { - continue; - } - // replace the previous top entry with the new entry - TopNEntry entry; - entry.sort_key = sort_key; - entry.index = BASE_INDEX + r; - AddEntryToHeap(entry); - any_added = true; - } - if (!any_added) { - // early-out: no matches - return; - } - - // for all matching entries we need to copy over the corresponding payload values - idx_t match_count = 0; - for (auto &entry : heap) { - if (entry.index < BASE_INDEX) { - continue; - } - // this entry was added in this chunk - // copy over the string to the string heap - entry.sort_key = sort_key_heap.AddBlob(entry.sort_key); - // to finalize the addition of this entry we need to move over the payload data - matching_sel.set_index(match_count, entry.index - BASE_INDEX); - entry.index = heap_data.size() + match_count; - match_count++; - } - - // copy over the input rows to the payload chunk - heap_data.Append(input, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); -} - -void TopNHeap::AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec) { - auto sort_key_values = FlatVector::GetData(sort_keys_vec); - idx_t base_index = heap_data.size(); - idx_t match_count = 0; - for (idx_t r = 0; r < input.size(); r++) { - auto &sort_key = sort_key_values[r]; - if (!EntryShouldBeAdded(sort_key)) { - continue; - } - // replace the previous top entry with the new entry - TopNEntry entry; - entry.sort_key = sort_key_heap.AddBlob(sort_key); - entry.index = base_index + match_count; - AddEntryToHeap(entry); - matching_sel.set_index(match_count++, r); - } - if (match_count == 0) { - // early-out: no matches - return; - } - - // copy over the input rows to the payload chunk - heap_data.Append(input, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); -} - -bool TopNHeap::CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &global_boundary) { - // An older local boundary remains valid if refreshing it would block. - const auto boundary_updated = global_boundary.TryGetBoundaryValue(boundary_val); - if (boundary_val.empty()) { - // no boundary value (yet) - don't do anything - return true; - } - if (boundary_updated) { - // new boundary value - decode - boundary_values.Reset(); - CreateSortKeyHelpers::DecodeSortKey(string_t(boundary_val), boundary_values, 0, modifiers); - for (auto &col : boundary_values.data) { - col.SetVectorType(VectorType::CONSTANT_VECTOR); - } - } - boundary_values.SetChildCardinality(sort_chunk.size()); - for (idx_t i = 0; i < orders.size(); i++) { - boundary_compare_chunk.data[i].Reference(sort_chunk.data[i]); - boundary_compare_chunk.data[orders.size() + i].Reference(boundary_values.data[i]); - } - boundary_compare_chunk.CheckCardinality(sort_chunk.size()); - - // we have boundary values - // from these boundary values, determine which values we should insert (if any) - idx_t final_count = 0; - - SelectionVector remaining_sel(nullptr); - idx_t remaining_count = sort_chunk.size(); - for (idx_t i = 0; i < orders.size() && remaining_count > 0; i++) { - if (remaining_sel.data()) { - compare_chunk.data[i].Slice(sort_chunk.data[i], remaining_sel, remaining_count); - } else { - compare_chunk.data[i].Reference(sort_chunk.data[i]); - } - bool is_last = i + 1 == orders.size(); - idx_t true_count; - if (orders[i].null_order == OrderByNullType::NULLS_LAST) { - if (orders[i].type == OrderType::ASCENDING) { - true_count = VectorOperations::DistinctLessThan(compare_chunk.data[i], boundary_values.data[i], - &remaining_sel, remaining_count, &true_sel, &false_sel); - } else { - true_count = VectorOperations::DistinctGreaterThanNullsFirst(compare_chunk.data[i], - boundary_values.data[i], &remaining_sel, - remaining_count, &true_sel, &false_sel); - } - } else { - D_ASSERT(orders[i].null_order == OrderByNullType::NULLS_FIRST); - if (orders[i].type == OrderType::ASCENDING) { - true_count = VectorOperations::DistinctLessThanNullsFirst(compare_chunk.data[i], - boundary_values.data[i], &remaining_sel, - remaining_count, &true_sel, &false_sel); - } else { - true_count = - VectorOperations::DistinctGreaterThan(compare_chunk.data[i], boundary_values.data[i], - &remaining_sel, remaining_count, &true_sel, &false_sel); - } - } - - if (true_count > 0) { - memcpy(final_sel.data() + final_count, true_sel.data(), true_count * sizeof(sel_t)); - final_count += true_count; - } - idx_t false_count = remaining_count - true_count; - if (!is_last && false_count > 0) { - // check what we should continue to check - remaining_count = not_distinct_from[i]->SelectExpression(boundary_compare_chunk, &new_remaining_sel, - nullptr, &false_sel, false_count); - remaining_sel.Initialize(new_remaining_sel); - } else { - break; - } - } - if (final_count == 0) { - return false; - } - if (final_count < sort_chunk.size()) { - sort_chunk.Slice(final_sel, final_count); - payload.Slice(final_sel, final_count); - } - return true; -} - -void TopNHeap::Sink(DataChunk &input, optional_ptr global_boundary) { - static constexpr idx_t SMALL_HEAP_THRESHOLD = 100; - - if (heap_size == 0) { - // LIMIT 0 without OFFSET - the heap can never hold any entry, so there is nothing to do - return; - } - - // compute the ordering values for the new chunk - sort_chunk.Reset(); - executor.Execute(input, sort_chunk); - - if (global_boundary) { - // if we have a global boundary value check which rows pass before doing anything - if (!CheckBoundaryValues(sort_chunk, input, *global_boundary)) { - // nothing in this chunk can be in the final result - return; - } - } - - // construct the sort key from the sort chunk - sort_keys.Reset(); - auto &sort_keys_vec = sort_keys.data[0]; - CreateSortKeyHelpers::CreateSortKey(sort_chunk, modifiers, sort_keys_vec, sort_key_state); - - if (heap_size <= SMALL_HEAP_THRESHOLD) { - AddSmallHeap(input, sort_keys_vec); - } else { - AddLargeHeap(input, sort_keys_vec); - } - - // if we modified the heap we might be able to update the global boundary - // note that the global boundary only applies to FULL heaps - if (!heap.empty() && heap.size() >= heap_size && global_boundary) { - global_boundary->UpdateValue(heap.front().sort_key); - } -} - -void TopNHeap::Combine(TopNHeap &other) { - // "other" is sorted at this point - idx_t match_count = 0; - // merge the heap of other into this - for (idx_t i = 0; i < other.heap.size(); i++) { - // heap is full - check the latest entry - auto &other_entry = other.heap[i]; - auto &sort_key = other_entry.sort_key; - if (!EntryShouldBeAdded(sort_key)) { - break; // We can break out of the loop here since we sorted the heap - } - // add this entry - TopNEntry new_entry; - new_entry.sort_key = sort_key_heap.AddBlob(sort_key); - new_entry.index = heap_data.size() + match_count; - AddEntryToHeap(new_entry); - - matching_sel.set_index(match_count++, other_entry.index); - if (match_count >= STANDARD_VECTOR_SIZE) { - // flush - heap_data.Append(other.heap_data, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); - match_count = 0; - } - } - if (match_count > 0) { - // flush - heap_data.Append(other.heap_data, matching_sel, match_count, VectorAppendMode::ALLOW_RESIZE); - match_count = 0; - } - Reduce(); -} - -void TopNHeap::Finalize() { - std::sort(heap.begin(), heap.end()); -} - -void TopNHeap::Reduce() { - if (heap_data.size() < ReduceThreshold()) { - // only reduce when we pass the reduce threshold - return; - } - // we have too many values in the heap - reduce them - StringHeap new_sort_heap(allocator); - DataChunk new_heap_data; - new_heap_data.Initialize(allocator, payload_types, heap.size()); - - SelectionVector new_payload_sel(heap.size()); - for (idx_t i = 0; i < heap.size(); i++) { - auto &entry = heap[i]; - // move the sort key to the new sort heap - entry.sort_key = new_sort_heap.AddBlob(entry.sort_key); - // move this heap entry to position X in the payload chunk - new_payload_sel.set_index(i, entry.index); - entry.index = i; - } - - // copy over the data from the current payload chunk to the new payload chunk - new_heap_data.Slice(heap_data, new_payload_sel, heap.size()); - new_heap_data.Flatten(); - - sort_key_heap.Destroy(); - sort_key_heap.Move(new_sort_heap); - heap_data.Reference(new_heap_data); -} - -void TopNHeap::InitializeScan(TopNScanState &state, bool exclude_offset) { - auto heap_copy = heap; - state.scan_order.resize(heap_copy.size()); - - // we sorted the heap in Finalize(), so we can sequentially here - // we do this because sorting the heap is much more efficient than popping one by one - for (idx_t i = 0; i < heap_copy.size(); i++) { - state.scan_order[i] = UnsafeNumericCast(heap_copy[i].index); - } - - state.pos = exclude_offset ? offset : 0; -} - -void TopNHeap::Scan(TopNScanState &state, DataChunk &chunk, idx_t &pos) { - if (pos >= state.scan_order.size()) { - return; - } - SelectionVector sel(state.scan_order.data() + pos, state.scan_order.size() - pos); - idx_t count = MinValue(STANDARD_VECTOR_SIZE, state.scan_order.size() - pos); - pos += STANDARD_VECTOR_SIZE; - - chunk.Reset(); - chunk.Slice(heap_data, sel, count); -} - class TopNGlobalSinkState : public GlobalSinkState { public: TopNGlobalSinkState(ClientContext &context, const PhysicalTopN &op) - : heap(context, op.types, op.orders, op.not_distinct_from, op.limit, op.offset), boundary_value(op) { + : heap(context, op.types, op.orders, op.not_distinct_from, op.limit, op.offset), + boundary_value(op.orders[0], op.dynamic_filter) { } mutex lock; diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index ec9b58c5b..feaa4fc97 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -2,6 +2,7 @@ #include "duckdb/execution/operator/persistent/physical_copy_to_file.hpp" #include "duckdb/common/file_opener.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/common/path.hpp" #include "duckdb/common/optional.hpp" @@ -2586,6 +2587,7 @@ class IntegerPartitionInputLocalState : public PartitionedCopyInputLocalState { unique_ptr partitions; PartitionedTupleDataAppendState append_state; //! The key hashes feeding the partition count estimate + unique_ptr key_hasher; DataChunk hashes; optional_ptr hll; }; @@ -2827,6 +2829,8 @@ IntegerPartitionInput::GetLocalState(ExecutionContext &context, PartitionedCopyI auto result = make_uniq(); result->partitions = CreatePartitions(context.client); result->partitions->InitializeAppendState(result->append_state); + result->key_hasher = + make_uniq(context.client, partitioned_copy.op.expected_types, vector {key_col}); result->hashes.Initialize(Allocator::Get(context.client), {LogicalType::HASH}); result->hll = hll; return std::move(result); @@ -2840,7 +2844,7 @@ void IntegerPartitionInput::Sink(ExecutionContext &context, DataChunk &chunk, Pa // the flush heuristic estimates the number of partitions from key hashes auto &hashes = lstate.hashes; hashes.Reset(); - VectorOperations::Hash(chunk.data[key_col], hashes.data[0], chunk.size()); + lstate.key_hasher->Hash(chunk, hashes.data[0]); hashes.CheckCardinality(chunk.size()); lstate.hll->Update(hashes.data[0]); } diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp index 69a0f6255..da4da5cae 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_keyed.cpp @@ -463,9 +463,10 @@ RecursiveCTEKeyedState::RecursiveCTEKeyedState(ClientContext &context, const Phy } for (auto &spec : op.partial_key_index_specs) { partial_key_indexes.push_back( - make_uniq(Allocator::Get(context), op.hash_key_types, spec.Indices())); + make_uniq(context, op.hash_key_types, spec.Indices())); } if (op.keyed.can_preaggregate) { + preaggregation_hasher = make_uniq(context, op.hash_key_types); preaggregation_hashes.Initialize(); } distinct_rows.Initialize(Allocator::DefaultAllocator(), op.hash_key_types); @@ -606,7 +607,8 @@ enum class RecursiveCTELocalPreaggregationDecision : uint8_t { DEFER, PREAGGREGA class RecursiveCTELocalPreaggregationState { public: RecursiveCTELocalPreaggregationState(ClientContext &context_p, const PhysicalRecursiveCTE &op_p) - : context(context_p), op(op_p), extractor(context, op), hashes(LogicalType::HASH) { + : context(context_p), op(op_p), extractor(context, op), hashes(LogicalType::HASH), + hasher(context, op.hash_key_types) { for (auto &payload_aggregate : op.payload_aggregates) { auto &bound_aggregate = payload_aggregate->Cast(); aggregates.emplace_back(bound_aggregate); @@ -624,7 +626,7 @@ class RecursiveCTELocalPreaggregationState { candidates.InitializeScan(scan_state); while (candidates.Scan(scan_state, input)) { extractor.ExtractKeys(input, keys); - keys.Hash(hashes); + hasher.Hash(keys, hashes); cardinality.Update(hashes); } const auto distinct_upper_bound = @@ -671,6 +673,7 @@ class RecursiveCTELocalPreaggregationState { DataChunk payload; DataChunk input; Vector hashes; + ChunkHasher hasher; HyperLogLog cardinality; idx_t sampled_candidate_count = 0; }; @@ -794,7 +797,7 @@ bool RecursiveCTEKeyedState::ShouldPreaggregateUsingKeyUpdates(idx_t candidate_c intermediate_table.InitializeScan(sample_scan_state); while (intermediate_table.Scan(sample_scan_state, update_rows)) { extractor.ExtractKeys(update_rows, distinct_rows); - distinct_rows.Hash(preaggregation_hashes); + preaggregation_hasher->Hash(distinct_rows, preaggregation_hashes); key_cardinality.Update(preaggregation_hashes); const auto distinct_upper_bound = LossyNumericCast((1 + HyperLogLog::GetErrorRate()) * static_cast(key_cardinality.Count())); diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp index 822a82f81..7d1a1c5f7 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_state.cpp @@ -9,7 +9,7 @@ namespace duckdb { -RecursiveCTEPartialKeyIndex::RecursiveCTEPartialKeyIndex(Allocator &allocator, +RecursiveCTEPartialKeyIndex::RecursiveCTEPartialKeyIndex(ClientContext &context, const vector &full_key_types, vector key_indices_p) : key_indices(std::move(key_indices_p)), hashes(LogicalType::HASH) { @@ -18,8 +18,10 @@ RecursiveCTEPartialKeyIndex::RecursiveCTEPartialKeyIndex(Allocator &allocator, D_ASSERT(key_idx < full_key_types.size()); partial_key_types.push_back(full_key_types[key_idx]); } + auto &allocator = Allocator::Get(context); partial_keys.Initialize(allocator, partial_key_types); selected_keys.Initialize(allocator, partial_key_types); + hasher = make_uniq(context, partial_key_types); Resize(1024); } @@ -50,7 +52,7 @@ void RecursiveCTEPartialKeyIndex::AddGroups(DataChunk &full_keys, const Selectio partial_keys.CheckCardinality(full_keys.size()); selected_keys.Reset(); selected_keys.Slice(partial_keys, key_selection, group_count); - selected_keys.Hash(hashes); + hasher->Hash(selected_keys, hashes); const auto hash_values = hashes.Values(); const auto addresses = FlatVector::GetData(group_addresses); diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp index 6d1a60964..184f09b95 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp @@ -1,6 +1,7 @@ #include "duckdb/execution/operator/set/physical_recursive_cte_union_state.hpp" #include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/execution/operator/scan/physical_column_data_scan.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/storage/buffer_manager.hpp" @@ -45,12 +46,14 @@ class RecursiveCTEUnionLocalState : public LocalSinkState { output->InitializeAppend(append_state); if (!op.UnionAll()) { partition_chunk.Initialize(Allocator::Get(context), op.GetTypes()); + hasher = make_uniq(context, op.GetTypes()); } } const PhysicalRecursiveCTE &op; unique_ptr output; ColumnDataAppendState append_state; + unique_ptr hasher; Vector hashes; Vector partition_hashes; Vector dummy_addresses; @@ -171,7 +174,7 @@ void RecursiveCTEUnionState::SinkDistinct(DataChunk &chunk, RecursiveCTEUnionLoc lstate.InitializePartitions(partitions.size()); std::fill(lstate.partition_counts.begin(), lstate.partition_counts.end(), 0); - chunk.Hash(lstate.hashes); + lstate.hasher->Hash(chunk, lstate.hashes); auto hash_data = FlatVector::GetData(lstate.hashes); const auto partition_mask = partitions.size() - 1; for (idx_t row_idx = 0; row_idx < chunk.size(); row_idx++) { diff --git a/src/duckdb/src/execution/physical_plan/plan_window.cpp b/src/duckdb/src/execution/physical_plan/plan_window.cpp index 31f8b5d40..ea7874bee 100644 --- a/src/duckdb/src/execution/physical_plan/plan_window.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_window.cpp @@ -50,7 +50,7 @@ bool HasDegenerateFrameCase1(ClientContext &client, BoundWindowExpression &wexpr return false; } const auto start_val = ExpressionExecutor::EvaluateScalar(client, *start_expr); - if (start_val.GetValue()) { + if (start_val.IsNull() || start_val.GetValue()) { return false; } @@ -59,7 +59,7 @@ bool HasDegenerateFrameCase1(ClientContext &client, BoundWindowExpression &wexpr return false; } const auto end_val = ExpressionExecutor::EvaluateScalar(client, *end_expr); - if (end_val.GetValue()) { + if (end_val.IsNull() || end_val.GetValue()) { return false; } @@ -358,7 +358,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { // Chain the new window operator on top of the plan if (i >= special_count) { - auto &window = Make(context, types, std::move(select_list), op.estimated_cardinality); + auto &window = Make(context, types, std::move(select_list), op.estimated_cardinality, + op.partition_limit); window.children.push_back(plan); plan = window; } else if (has_streaming) { @@ -370,7 +371,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { const auto expr_idx = matching[0]; auto &partitions = partitioned_columns[expr_idx]; auto &window = Make(context, types, std::move(select_list), op.estimated_cardinality, - std::move(partitions)); + std::move(partitions), op.partition_limit); window.children.push_back(plan); plan = window; } diff --git a/src/duckdb/src/execution/sample/base_reservoir_sample.cpp b/src/duckdb/src/execution/sample/base_reservoir_sample.cpp index 973796dc4..b6c61b002 100644 --- a/src/duckdb/src/execution/sample/base_reservoir_sample.cpp +++ b/src/duckdb/src/execution/sample/base_reservoir_sample.cpp @@ -26,75 +26,6 @@ unique_ptr BaseReservoirSampling::Copy() { return ret; } -void BaseReservoirSampling::InitializeReservoirWeights(idx_t cur_size, idx_t sample_size) { - //! 1: The first m items of V are inserted into R - //! first we need to check if the reservoir already has "m" elements - //! 2. For each item vi ∈ R: Calculate a key ki = random(0, 1) - //! we then define the threshold to enter the reservoir T_w as the minimum key of R - //! we use a priority queue to extract the minimum key in O(1) time - if (cur_size == sample_size) { - //! 2. For each item vi ∈ R: Calculate a key ki = random(0, 1) - //! we then define the threshold to enter the reservoir T_w as the minimum key of R - //! we use a priority queue to extract the minimum key in O(1) time - for (idx_t i = 0; i < sample_size; i++) { - double k_i = random.NextRandom(); - reservoir_weights.emplace(-k_i, i); - } - SetNextEntry(); - } -} - -void BaseReservoirSampling::SetNextEntry() { - D_ASSERT(!reservoir_weights.empty()); - //! 4. Let r = random(0, 1) and Xw = log(r) / log(T_w) - auto &min_key = reservoir_weights.top(); - double t_w = -min_key.first; - double r = random.NextRandom32(); - double x_w = log(r) / log(t_w); - //! 5. From the current item vc skip items until item vi , such that: - //! 6. wc +wc+1 +···+wi−1 < Xw <= wc +wc+1 +···+wi−1 +wi - //! since all our weights are 1 (uniform sampling), we can just determine the amount of elements to skip - min_weight_threshold = t_w; - min_weighted_entry_index = min_key.second; - if (x_w >= 1.0 && std::isfinite(x_w)) { - next_index_to_sample = idx_t(ceil(x_w)); - } else { - next_index_to_sample = 1; - } - num_entries_to_skip_b4_next_sample = 0; -} - -void BaseReservoirSampling::ReplaceElementWithIndex(idx_t entry_index, double with_weight, bool pop) { - if (pop) { - reservoir_weights.pop(); - } - double r2 = with_weight; - //! now we insert the new weight into the reservoir - reservoir_weights.emplace(-r2, entry_index); - //! we update the min entry with the new min entry in the reservoir - SetNextEntry(); -} - -void BaseReservoirSampling::ReplaceElement(double with_weight) { - //! replace the entry in the reservoir - //! pop the minimum entry - reservoir_weights.pop(); - //! now update the reservoir - //! 8. Let tw = Tw i , r2 = random(tw,1) and vi’s key: ki = (r2)1/wi - //! 9. The new threshold Tw is the new minimum key of R - //! we generate a random number between (min_weight_threshold, 1) - double r2 = random.NextRandom(min_weight_threshold, 1); - - //! if we are merging two reservoir samples use the weight passed - if (with_weight >= 0) { - r2 = with_weight; - } - //! now we insert the new weight into the reservoir - reservoir_weights.emplace(-r2, min_weighted_entry_index); - //! we update the min entry with the new min entry in the reservoir - SetNextEntry(); -} - void BaseReservoirSampling::UpdateMinWeightThreshold() { if (!reservoir_weights.empty()) { min_weight_threshold = -reservoir_weights.top().first; diff --git a/src/duckdb/src/function/builtin_encodings.cpp b/src/duckdb/src/function/builtin_encodings.cpp index e095d4f87..299fda45b 100644 --- a/src/duckdb/src/function/builtin_encodings.cpp +++ b/src/duckdb/src/function/builtin_encodings.cpp @@ -44,14 +44,14 @@ void EncodeUTF8ToLatin1(const char *input, idx_t input_size, char *output, idx_t pos++; continue; } - // a two byte sequence U+0080..U+07FF, valid UTF-8 is guaranteed by VARCHAR + // a two byte sequence U+0080..U+07FF uint32_t code_point = 0; idx_t length = 1; if (lead >= 0xF0) { length = 4; } else if (lead >= 0xE0) { length = 3; - } else { + } else if (pos + 1 < input_size) { length = 2; code_point = ((lead & 0x1F) << 6) | (static_cast(input[pos + 1]) & 0x3F); } @@ -73,23 +73,29 @@ void EncodeUTF8ToUTF16(const char *input, idx_t input_size, char *output, idx_t }; while (pos < input_size) { const auto lead = static_cast(input[pos]); - uint32_t code_point; - idx_t length; + idx_t length = 4; if (lead <= 0x7F) { - code_point = lead; length = 1; } else if (lead < 0xE0) { - code_point = ((lead & 0x1F) << 6) | (static_cast(input[pos + 1]) & 0x3F); length = 2; } else if (lead < 0xF0) { + length = 3; + } + if (pos + length > input_size) { + throw ConversionException("Could not encode the character at byte %llu in utf-16", pos); + } + uint32_t code_point; + if (length == 1) { + code_point = lead; + } else if (length == 2) { + code_point = ((lead & 0x1F) << 6) | (static_cast(input[pos + 1]) & 0x3F); + } else if (length == 3) { code_point = ((lead & 0x0F) << 12) | ((static_cast(input[pos + 1]) & 0x3F) << 6) | (static_cast(input[pos + 2]) & 0x3F); - length = 3; } else { code_point = ((lead & 0x07) << 18) | ((static_cast(input[pos + 1]) & 0x3F) << 12) | ((static_cast(input[pos + 2]) & 0x3F) << 6) | (static_cast(input[pos + 3]) & 0x3F); - length = 4; } if (code_point >= 0x10000) { code_point -= 0x10000; diff --git a/src/duckdb/src/function/cast/cast_statistics.cpp b/src/duckdb/src/function/cast/cast_statistics.cpp index 87ea64ccf..753e5c662 100644 --- a/src/duckdb/src/function/cast/cast_statistics.cpp +++ b/src/duckdb/src/function/cast/cast_statistics.cpp @@ -162,7 +162,8 @@ bool CastStatistics::CanPropagate(const LogicalType &source, const LogicalType & // for time/timestamps/dates - there are various limitations on what we can propagate // Downcasting timestamps to times is not a truncation operation switch (target.id()) { - case LogicalTypeId::TIME: { + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: { switch (source.id()) { case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIMESTAMP_SEC: diff --git a/src/duckdb/src/function/function_list.cpp b/src/duckdb/src/function/function_list.cpp index e066fb216..7ccb70c28 100644 --- a/src/duckdb/src/function/function_list.cpp +++ b/src/duckdb/src/function/function_list.cpp @@ -178,6 +178,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION_SET(FmodFun), DUCKDB_SCALAR_FUNCTION(GetVariableFun), DUCKDB_SCALAR_FUNCTION(HasErrorFun), + DUCKDB_SCALAR_FUNCTION(HashFun), DUCKDB_SCALAR_FUNCTION(HivePartitionComponentFun), DUCKDB_SCALAR_FUNCTION(IlikeEscapeFun), DUCKDB_SCALAR_FUNCTION(InvokeFun), diff --git a/src/duckdb/src/function/scalar/generic/hash.cpp b/src/duckdb/src/function/scalar/generic/hash.cpp new file mode 100644 index 000000000..f9bfa25e5 --- /dev/null +++ b/src/duckdb/src/function/scalar/generic/hash.cpp @@ -0,0 +1,76 @@ +#include "duckdb/function/scalar/generic_functions.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/chunk_hasher.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_hash_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" + +namespace duckdb { + +static void HashFunction(DataChunk &args, ExpressionState &state, Vector &result) { + D_ASSERT(args.ColumnCount() > 0); + VectorOperations::Hash(args.data[0], result, args.size()); + for (idx_t i = 1; i < args.ColumnCount(); i++) { + VectorOperations::CombineHash(result, args.data[i], args.size()); + } +} + +ScalarFunction HashFun::GetFunction() { + auto hash_fun = ScalarFunction({}, LogicalType::HASH, HashFunction); + hash_fun.SetName("hash"); + hash_fun.GetSignature().AddParameter("value", LogicalType::ANY); + hash_fun.GetSignature().AddArgs("args", LogicalType::ANY); + hash_fun.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + // hash the arguments after their combinable collations + hash_fun.SetCollationHandling(FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS); + return hash_fun; +} + +//===--------------------------------------------------------------------===// +// BoundHashExpression +//===--------------------------------------------------------------------===// +unique_ptr BoundHashExpression::CreateOnColumns(ClientContext &context, const vector &types, + const vector &column_ids) { + (void)context; + D_ASSERT(!column_ids.empty()); + vector> children; + for (auto column_id : column_ids) { + children.push_back(make_uniq(types[column_id], column_id)); + } + return make_uniq(BoundScalarFunction(HashFun::GetFunction()), std::move(children), + nullptr); +} + +unique_ptr BoundHashExpression::CreateOnColumns(ClientContext &context, const vector &types) { + vector column_ids; + for (idx_t i = 0; i < types.size(); i++) { + column_ids.push_back(i); + } + return CreateOnColumns(context, types, column_ids); +} + +void BoundHashExpression::Execute(ExpressionExecutor &executor, DataChunk &input, Vector &hashes, idx_t expr_idx) { + executor.SetChunk(input); + executor.ExecuteExpression(expr_idx, hashes); + // the dictionary optimization of the executor can emit a dictionary vector + if (hashes.GetVectorType() == VectorType::DICTIONARY_VECTOR) { + hashes.Flatten(); + } +} + +//===--------------------------------------------------------------------===// +// ChunkHasher +//===--------------------------------------------------------------------===// +ChunkHasher::ChunkHasher(ClientContext &context, const vector &types) + : expression(BoundHashExpression::CreateOnColumns(context, types)), executor(context, *expression) { +} + +ChunkHasher::ChunkHasher(ClientContext &context, const vector &types, const vector &column_ids) + : expression(BoundHashExpression::CreateOnColumns(context, types, column_ids)), executor(context, *expression) { +} + +void ChunkHasher::Hash(DataChunk &input, Vector &hashes) { + BoundHashExpression::Execute(executor, input, hashes); +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 3dde71375..b6d8643d7 100644 --- a/src/duckdb/src/function/table/version/pragma_version.cpp +++ b/src/duckdb/src/function/table/version/pragma_version.cpp @@ -1,5 +1,5 @@ #ifndef DUCKDB_PATCH_VERSION -#define DUCKDB_PATCH_VERSION "0-alpha57049" +#define DUCKDB_PATCH_VERSION "0-alpha57096" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 1 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.1.0-alpha57049" +#define DUCKDB_VERSION "v2.1.0-alpha57096" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "87d96b7773" +#define DUCKDB_SOURCE_ID "e11756ae3a" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/window/window_naive_aggregator.cpp b/src/duckdb/src/function/window/window_naive_aggregator.cpp index f4da1d0d2..c2749ca1f 100644 --- a/src/duckdb/src/function/window/window_naive_aggregator.cpp +++ b/src/duckdb/src/function/window/window_naive_aggregator.cpp @@ -1,6 +1,7 @@ #include "duckdb/function/window/window_naive_aggregator.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_hash_expression.hpp" #include "duckdb/common/sorting/sort.hpp" #include "duckdb/function/window/window_collection.hpp" #include "duckdb/function/window/window_shared_expressions.hpp" @@ -30,6 +31,7 @@ WindowNaiveAggregator::WindowNaiveAggregator(const WindowAggregateExecutor &exec arg_idx, arg_type, arg_types.size() + arg_idx)); } args_equal = BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(arg_equals)); + args_hash = BoundHashExpression::CreateOnColumns(client, arg_types); } } @@ -99,6 +101,7 @@ class WindowNaiveLocalState : public WindowAggregatorLocalState { SubFrames frames; //! The optional hash table used for DISTINCT Vector hashes; + unique_ptr args_hash; //! The state used for comparing the collection across chunk boundaries unique_ptr comparer; //! Whether two rows have the same arguments, over [left arguments..., right arguments...] @@ -158,6 +161,7 @@ void WindowNaiveLocalState::Finalize(ExecutionContext &context, WindowAggregator auto compare_types = aggregator.arg_types; compare_types.insert(compare_types.end(), aggregator.arg_types.begin(), aggregator.arg_types.end()); args_compare.InitializeEmpty(compare_types); + args_hash = make_uniq(context.client.GetContext(), *aggregator.args_hash); } } @@ -214,7 +218,7 @@ size_t WindowNaiveLocalState::Hash(idx_t rid) { auto &scanned = cursor->chunk; SelectionVector sel(&s, 1); leaves.Slice(scanned, sel, 1); - leaves.Hash(hashes); + BoundHashExpression::Execute(*args_hash, leaves, hashes); return *FlatVector::GetData(hashes); } diff --git a/src/duckdb/src/include/duckdb/common/hive_partitioning.hpp b/src/duckdb/src/include/duckdb/common/hive_partitioning.hpp index a5b0d97fc..a341ff31b 100644 --- a/src/duckdb/src/include/duckdb/common/hive_partitioning.hpp +++ b/src/duckdb/src/include/duckdb/common/hive_partitioning.hpp @@ -10,6 +10,7 @@ #include "duckdb/common/identifier.hpp" #include "duckdb/common/types/column/partitioned_column_data.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/common/open_file_info.hpp" #include "duckdb/original/std/sstream.hpp" @@ -116,6 +117,8 @@ class HivePartitionedColumnData : public PartitionedColumnData { hive_partition_map_t local_partition_map; //! The columns that make up the key vector group_by_columns; + //! Hashes the key columns + ChunkHasher hasher; //! Thread-local pre-allocated vector for hashes Vector hashes_v; //! Thread-local pre-allocated HivePartitionKeys diff --git a/src/duckdb/src/include/duckdb/common/random_engine.hpp b/src/duckdb/src/include/duckdb/common/random_engine.hpp index 5386ace3f..0373ff872 100644 --- a/src/duckdb/src/include/duckdb/common/random_engine.hpp +++ b/src/duckdb/src/include/duckdb/common/random_engine.hpp @@ -12,6 +12,7 @@ #include "duckdb/common/limits.hpp" #include "duckdb/common/mutex.hpp" +#include #include namespace duckdb { @@ -45,6 +46,25 @@ class RandomEngine { static RandomEngine &Get(ClientContext &context); + //! The conversions above, for any generator of uint32_t + template + static uint64_t NextRandomInteger64(GENERATOR &generator) { + return (static_cast(generator()) << UINT64_C(32)) | static_cast(generator()); + } + template + static double NextRandom(GENERATOR &generator) { + return std::ldexp(NextRandomInteger64(generator), -64); + } + template + static double NextRandom(GENERATOR &generator, double min, double max) { + D_ASSERT(max >= min); + return min + (NextRandom(generator) * (max - min)); + } + template + static double NextRandom32(GENERATOR &generator) { + return std::ldexp(generator(), -32); + } + mutex lock; private: diff --git a/src/duckdb/src/include/duckdb/common/sorting/full_sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/full_sort.hpp index ac79c0465..17881a752 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/full_sort.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/full_sort.hpp @@ -17,7 +17,7 @@ class FullSort : public SortStrategy { using Orders = vector; FullSort(ClientContext &client, const vector &order_bys, const Types &payload_types, - bool require_payload = false); + bool require_payload = false, optional_idx partition_limit = optional_idx()); public: //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/common/sorting/sort_strategy.hpp b/src/duckdb/src/include/duckdb/common/sorting/sort_strategy.hpp index a9a468e1b..3a6e9ff9f 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/sort_strategy.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/sort_strategy.hpp @@ -25,9 +25,10 @@ class SortStrategy { const vector &order_bys, const Types &payload_types, const vector> &partitions_stats, const OperatorPartitionInfo &partition_info, idx_t estimated_cardinality, - bool require_payload = false); + bool require_payload = false, + optional_idx partition_limit = optional_idx()); - explicit SortStrategy(const Types &input_types); + explicit SortStrategy(const Types &input_types, optional_idx partition_limit = optional_idx()); virtual ~SortStrategy() = default; public: @@ -88,6 +89,8 @@ class SortStrategy { vector scan_ids; //! Key columns in the sorted output. Needed for prefix computations. vector sort_ids; + //! The maximum number of rows in a partition + optional_idx partition_limit; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp b/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp new file mode 100644 index 000000000..ebfc845c3 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp @@ -0,0 +1,192 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/sorting/topn_heap.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/arena_containers/arena_vector.hpp" +#include "duckdb/common/types/selection_vector.hpp" +#include "duckdb/common/types/string_type.hpp" +#include "duckdb/function/create_sort_key.hpp" +#include "duckdb/planner/bound_result_modifier.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// Heaps +//===--------------------------------------------------------------------===// +class TopNHeap; + +struct TopNEntry { + string_t sort_key; + idx_t index; + + bool operator<(const TopNEntry &other) const { + return sort_key < other.sort_key; + } +}; + +struct TopNScanState { + TopNScanState() : pos(0), sel(STANDARD_VECTOR_SIZE) { + } + + idx_t pos; + vector scan_order; + SelectionVector sel; +}; + +struct TopNBoundaryValue { + TopNBoundaryValue(const BoundOrderByNode &order, const shared_ptr &dynamic_filter) + : dynamic_filter(dynamic_filter), boundary_vector(order.expression->GetReturnType()), + boundary_modifiers(order.type, order.null_order) { + } + + const shared_ptr &dynamic_filter; + mutex lock; + string boundary_value; + bool is_set = false; + Vector boundary_vector; + OrderModifiers boundary_modifiers; + + bool TryGetBoundaryValue(string ¤t_boundary) { + unique_lock l(lock, std::try_to_lock); + if (!l.owns_lock() || boundary_value == current_boundary) { + return false; + } + current_boundary = boundary_value; + return true; + } + + void UpdateValue(string_t boundary_val) { + unique_lock l(lock); + if (!is_set || boundary_val < string_t(boundary_value)) { + boundary_value = boundary_val.GetString(); + is_set = true; + if (dynamic_filter) { + CreateSortKeyHelpers::DecodeSortKey(boundary_val, boundary_vector, 0, boundary_modifiers); + auto new_dynamic_value = boundary_vector.GetValue(0); + l.unlock(); + dynamic_filter->SetValue(std::move(new_dynamic_value)); + } + } + } +}; + +struct TopOneFunc { + typedef idx_t (*topone_size_t)(); + typedef optional_idx (*topone_update_t)(data_ptr_t state_p, Vector &sort_key, const idx_t count); + typedef bool (*topone_combine_t)(const_data_ptr_t source_p, data_ptr_t target_p); + + topone_size_t state_size; + topone_update_t update; + topone_combine_t combine; +}; + +class TopNHeap { +public: + static bool CanOptimize(idx_t limit, idx_t cardinality); + + TopNHeap(ClientContext &context, const vector &payload_types, const vector &orders, + const vector> ¬_distinct_from, idx_t limit, idx_t offset); + TopNHeap(ExecutionContext &context, const vector &payload_types, + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset); + TopNHeap(ClientContext &context, Allocator &allocator, const vector &payload_types, + const vector &orders, const vector> ¬_distinct_from, + idx_t limit, idx_t offset); + + Allocator &allocator; + BufferManager &buffer_manager; + ArenaAllocator arena_allocator; + unsafe_arena_vector heap; + const vector &payload_types; + const vector &orders; + vector modifiers; + idx_t limit; + idx_t offset; + idx_t heap_size; + ExpressionExecutor executor; + //! NOT DISTINCT FROM comparison of every sort column + vector> not_distinct_from; + DataChunk sort_chunk; + DataChunk heap_data; + DataChunk sort_keys; + CreateSortKeyState sort_key_state; + StringHeap sort_key_heap; + + SelectionVector matching_sel; + + DataChunk compare_chunk; + //! Cached global boundary value as a set of constant vectors + DataChunk boundary_values; + //! The input of not_distinct_from: [sort columns..., boundary values...] + DataChunk boundary_compare_chunk; + //! Cached global boundary value in sort-key format + string boundary_val; + SelectionVector final_sel; + SelectionVector true_sel; + SelectionVector false_sel; + SelectionVector new_remaining_sel; + + unique_ptr topone; + vector topone_state; + +public: + void Sink(DataChunk &input, optional_ptr boundary_value = nullptr); + void Combine(TopNHeap &other); + void Reduce(); + void Finalize(); + + void InitializeScan(TopNScanState &state, bool exclude_offset); + void Scan(TopNScanState &state, DataChunk &chunk, idx_t &pos); + + bool CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &boundary_val); + void AddSingleHeap(DataChunk &input, optional_ptr global_boundary); + void AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec); + void AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec); + +public: + idx_t ReduceThreshold() const { + return MaxValue(STANDARD_VECTOR_SIZE * 5ULL, 2ULL * heap_size); + } + + idx_t InitialHeapAllocSize() const { + return MinValue(STANDARD_VECTOR_SIZE * 100ULL, ReduceThreshold()) + STANDARD_VECTOR_SIZE; + } + +private: + inline bool EntryShouldBeAdded(const string_t &sort_key) { + if (heap_size == 0) { + // the heap has no capacity (LIMIT 0) - no entry can ever be added + return false; + } + if (heap.size() < heap_size) { + // heap is not full yet - the entry can be added + return true; + } + if (sort_key < heap.front().sort_key) { + // sort key is smaller than current max value + return true; + } + // heap is full and there is no room for the entry + return false; + } + + inline void AddEntryToHeap(const TopNEntry &entry) { + D_ASSERT(heap_size > 0); + if (heap.size() >= heap_size) { + D_ASSERT(!heap.empty()); + std::pop_heap(heap.begin(), heap.end()); + heap.pop_back(); + } + heap.push_back(entry); + std::push_heap(heap.begin(), heap.end()); + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/sorting/topn_sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/topn_sort.hpp new file mode 100644 index 000000000..6bd1ea817 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/sorting/topn_sort.hpp @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/sorting/topn_sort.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/sorting/sort_strategy.hpp" + +namespace duckdb { + +class TopNSort : public SortStrategy { +public: + using Orders = vector; + + static bool CanOptimize(optional_idx limit, idx_t cardinality); + + TopNSort(ClientContext &client, const vector &order_bys, const Types &payload_types, + optional_idx partition_limit); + +public: + //===--------------------------------------------------------------------===// + // Sink Interface + //===--------------------------------------------------------------------===// + unique_ptr GetLocalSinkState(ExecutionContext &context) const override; + unique_ptr GetGlobalSinkState(ClientContext &client) const override; + SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) const override; + SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) const override; + SinkFinalizeType Finalize(ClientContext &client, OperatorSinkFinalizeInput &finalize) const override; + ProgressData GetSinkProgress(ClientContext &context, GlobalSinkState &gstate, + const ProgressData source_progress) const override; + +public: + //===--------------------------------------------------------------------===// + // Source Interface + //===--------------------------------------------------------------------===// + unique_ptr GetGlobalSourceState(ClientContext &context, GlobalSinkState &sink) const override; + +public: + //===--------------------------------------------------------------------===// + // Non-Standard Interface + //===--------------------------------------------------------------------===// + SourceResultType MaterializeColumnData(ExecutionContext &context, idx_t hash_bin, + OperatorSourceInput &source) const override; + HashGroupPtr GetColumnData(idx_t hash_bin, OperatorSourceInput &source) const override; + + SourceResultType MaterializeSortedRun(ExecutionContext &context, idx_t hash_bin, + OperatorSourceInput &source) const override; + SortedRunPtr GetSortedRun(ClientContext &client, idx_t hash_bin, OperatorSourceInput &source) const override; + + const ChunkRows &GetHashGroups(GlobalSourceState &global_state) const override; + +public: + // OVER(...) (sorting) + Orders orders; + // Key columns that must be computed + vector> sort_exprs; + //! NOT DISTINCT FROM comparison of the boundary value for every order column + vector> not_distinct_from; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp index 95a4144d7..d60f21040 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp @@ -163,6 +163,9 @@ class ColumnDataCollection { //! Materializes every row on each call, so read many values through GetRows instead DUCKDB_API Value GetValue(idx_t column, idx_t index) const; + //! Truncates the collection in place. NOP if it is already smaller. + void Truncate(idx_t new_count); + //! Compare two column data collections to another. If they are equal according to result equality rules, //! return true. That means null values are equal, and approx equality is used for floating point values. //! If they are not equal, return false and fill in the error message. diff --git a/src/duckdb/src/include/duckdb/common/types/data_chunk.hpp b/src/duckdb/src/include/duckdb/common/types/data_chunk.hpp index 2b3d581ef..947bd41dc 100644 --- a/src/duckdb/src/include/duckdb/common/types/data_chunk.hpp +++ b/src/duckdb/src/include/duckdb/common/types/data_chunk.hpp @@ -163,11 +163,6 @@ class DataChunk { DUCKDB_API void Serialize(Serializer &serializer, bool compressed_serialization = true) const; DUCKDB_API void Deserialize(Deserializer &source); - //! Hashes the DataChunk to the target vector - DUCKDB_API void Hash(Vector &result); - //! Hashes specific vectors of the DataChunk to the target vector - DUCKDB_API void Hash(vector &column_ids, Vector &result); - //! Returns a list of types of the vectors of this data chunk DUCKDB_API vector GetTypes() const; diff --git a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp index d2a485fc5..75061932b 100644 --- a/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/aggregate_hashtable.hpp @@ -17,6 +17,7 @@ #include "duckdb/common/row_operations/row_operations.hpp" #include "duckdb/common/clustered_aggregate.hpp" #include "duckdb/common/atomic.hpp" +#include "duckdb/execution/expression_executor.hpp" namespace duckdb { @@ -53,6 +54,8 @@ struct AggregateHTProbeState { SelectionVector group_compare_vector; SelectionVector no_match_vector; DataChunk group_chunk; + //! Executes the hash table's hash expression over the groups + unique_ptr hash_executor; optional_ptr owner; bool initialized = false; }; @@ -189,6 +192,10 @@ class GroupedAggregateHashTable : public BaseAggregateHashTable { void ZeroTrailingRegion(Vector &row_locations, idx_t count) const; //! Efficiently matches groups RowMatcher row_matcher; + //! "hash(#0, #1, ...)" over the groups + unique_ptr hash_expression; + //! Hash the groups into hashes, with the executor of the given probe state + void HashGroups(DataChunk &groups, AggregateHTProbeState &probe_state, Vector &hashes) const; struct AggregateDictionaryState { AggregateDictionaryState(); diff --git a/src/duckdb/src/include/duckdb/execution/chunk_hasher.hpp b/src/duckdb/src/include/duckdb/execution/chunk_hasher.hpp new file mode 100644 index 000000000..5057d35e7 --- /dev/null +++ b/src/duckdb/src/include/duckdb/execution/chunk_hasher.hpp @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/execution/chunk_hasher.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/execution/expression_executor.hpp" + +namespace duckdb { + +//! Hashes the columns of a chunk with a "hash(#0, #1, ...)" expression run through an ExpressionExecutor +class ChunkHasher { +public: + //! Hash all columns of chunks of the given types + ChunkHasher(ClientContext &context, const vector &types); + //! Hash the given columns of chunks of the given types + ChunkHasher(ClientContext &context, const vector &types, const vector &column_ids); + +public: + //! Hash all rows of the input into a flat or constant vector + void Hash(DataChunk &input, Vector &hashes); + +private: + unique_ptr expression; + ExpressionExecutor executor; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 049417003..60b076b5f 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -21,6 +21,7 @@ #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" +#include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/ht_entry.hpp" #include "duckdb/execution/perfect_hash_join_table.hpp" #include "duckdb/parallel/sharded_counter.hpp" @@ -299,6 +300,8 @@ class JoinHashTable { Vector hashes; Vector ht_offsets_and_salts_v; Vector hashes_dense_v; + //! Executes the hash table's hash expression over the probe keys + unique_ptr hash_executor; unique_ptr spill_hashes; SelectionVector spill_false_sel; //! Allocated only when the operator gates the compressed-probe paths on; null otherwise @@ -432,6 +435,13 @@ class JoinHashTable { const vector &conditions; //! The types of the keys used in equality comparison vector equality_types; + //! "hash(#0, #1, ...)" over the equality keys + unique_ptr hash_expression; + //! "hash(#i)" for every equality key i, for the per-key-column filters + vector> key_hash_expressions; + //! Executors of the build side, which is thread-local + unique_ptr build_hash_executor; + unique_ptr build_key_hash_executor; //! The types of the keys vector condition_types; //! The types of all conditions @@ -540,7 +550,8 @@ class JoinHashTable { void InitializeScanStructure(ScanStructure &scan_structure, DataChunk &keys, TupleDataChunkState &key_state, optional_ptr ¤t_sel); - void Hash(DataChunk &keys, const SelectionVector &sel, idx_t count, Vector &hashes); + //! Hash all rows of the equality keys, creating the executor if it does not exist yet + void Hash(DataChunk &keys, unique_ptr &executor, Vector &hashes) const; bool TryProbePerfectHashTable(ScanStructure &scan_structure, DataChunk &keys); bool CanUsePerfectDictionaryLookup() const; @@ -826,6 +837,7 @@ class JoinHashTable { explicit KeyFilterBuildScratch(JoinHashTable &ht); DataChunk keys; Vector hashes; + ExpressionExecutor key_hash_executor; }; //! Gathers one key column of a chunk of materialized rows void GatherKeyColumn(TupleDataChunkState &chunk_state, idx_t count, idx_t key_idx, Vector &result); diff --git a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp index ab5ed7564..460d9ec72 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/aggregate/physical_window.hpp @@ -21,10 +21,11 @@ class PhysicalWindow : public PhysicalOperator { public: PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, - vector> select_list, idx_t estimated_cardinality, - vector partitions); + vector> select_list, idx_t estimated_cardinality, vector partitions, + optional_idx partition_limit = optional_idx()); PhysicalWindow(PhysicalPlan &physical_plan, ClientContext &context, vector types, - vector> select_list, idx_t estimated_cardinality); + vector> select_list, idx_t estimated_cardinality, + optional_idx partition_limit = optional_idx()); //! The projection list of the WINDOW statement (may contain aggregates) vector> select_list; @@ -35,6 +36,8 @@ class PhysicalWindow : public PhysicalOperator { bool is_order_dependent; //! The partitions over which this is grouped (if any) OperatorPartitionInfo partition_info; + //! The partition size limit (if any) + optional_idx partition_limit; //! DISTINCT FROM comparison of the partition keys unique_ptr partition_distinct_from; //! DISTINCT FROM comparison of the order keys of every window expression, by the end of its order key prefix diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp index 313ee2190..7c8c162df 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_keyed_state.hpp @@ -201,6 +201,7 @@ class RecursiveCTEKeyedState : public RecursiveCTEState { unique_ptr key_delta; vector payload_aggregate_objects; + unique_ptr preaggregation_hasher; Vector preaggregation_hashes; vector> payload_comparison_executors; }; diff --git a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp index 53fbf4d75..7bc59ff7d 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/set/physical_recursive_cte_state.hpp @@ -5,6 +5,7 @@ #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/types/hyperloglog.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" +#include "duckdb/execution/chunk_hasher.hpp" #include "duckdb/execution/executor.hpp" #include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/parallel/pipeline_schedule.hpp" @@ -80,7 +81,7 @@ class RecursiveCTEPartialKeyIndex { idx_t next; }; - RecursiveCTEPartialKeyIndex(Allocator &allocator, const vector &full_key_types, + RecursiveCTEPartialKeyIndex(ClientContext &context, const vector &full_key_types, vector key_indices); //! Key and address selections can differ when addresses have already been compacted. @@ -98,6 +99,7 @@ class RecursiveCTEPartialKeyIndex { DataChunk partial_keys; DataChunk selected_keys; + unique_ptr hasher; Vector hashes; vector heads; vector entries; diff --git a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp index 92508b77a..51ecccf75 100644 --- a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp +++ b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp @@ -16,6 +16,8 @@ #include "duckdb/common/queue.hpp" +#include + // Originally intended to be the vector size, but in order to run on // vector size = 2, we had to change it. #define FIXED_SAMPLE_SIZE 2048 @@ -46,17 +48,86 @@ class ReservoirRNG : public RandomEngine { }; //! Reservoir sampling is based on the 2005 paper "Weighted Random Sampling" by Efraimidis and Spirakis -class BaseReservoirSampling { +template +class ReservoirSampler { public: - explicit BaseReservoirSampling(int64_t seed); - BaseReservoirSampling(); + void InitializeReservoirWeights(idx_t cur_size, idx_t sample_size) { + //! 1: The first m items of V are inserted into R + //! first we need to check if the reservoir already has "m" elements + //! 2. For each item vi ∈ R: Calculate a key ki = random(0, 1) + //! we then define the threshold to enter the reservoir T_w as the minimum key of R + //! we use a priority queue to extract the minimum key in O(1) time + if (cur_size == sample_size) { + //! 2. For each item vi ∈ R: Calculate a key ki = random(0, 1) + //! we then define the threshold to enter the reservoir T_w as the minimum key of R + //! we use a priority queue to extract the minimum key in O(1) time + for (idx_t i = 0; i < sample_size; i++) { + double k_i = RandomEngine::NextRandom(Sampler().random); + Sampler().PushWeight(-k_i, i); + } + SetNextEntry(); + } + } - void InitializeReservoirWeights(idx_t cur_size, idx_t sample_size); + void SetNextEntry() { + auto &sampler = Sampler(); + //! 4. Let r = random(0, 1) and Xw = log(r) / log(T_w) + auto &min_key = sampler.TopWeight(); + double t_w = -min_key.first; + double r = RandomEngine::NextRandom32(sampler.random); + double x_w = log(r) / log(t_w); + //! 5. From the current item vc skip items until item vi , such that: + //! 6. wc +wc+1 +···+wi−1 < Xw <= wc +wc+1 +···+wi−1 +wi + //! since all our weights are 1 (uniform sampling), we can just determine the amount of elements to skip + sampler.min_weight_threshold = t_w; + sampler.min_weighted_entry_index = min_key.second; + if (x_w >= 1.0 && std::isfinite(x_w)) { + sampler.next_index_to_sample = idx_t(ceil(x_w)); + } else { + sampler.next_index_to_sample = 1; + } + sampler.num_entries_to_skip_b4_next_sample = 0; + } - void SetNextEntry(); + void ReplaceElementWithIndex(idx_t entry_index, double with_weight, bool pop = true) { + if (pop) { + Sampler().PopWeight(); + } + double r2 = with_weight; + //! now we insert the new weight into the reservoir + Sampler().PushWeight(-r2, entry_index); + //! we update the min entry with the new min entry in the reservoir + SetNextEntry(); + } - void ReplaceElementWithIndex(idx_t entry_index, double with_weight, bool pop = true); - void ReplaceElement(double with_weight = -1); + void ReplaceElement(double with_weight = -1) { + //! replace the entry in the reservoir + //! 8. Let tw = Tw i , r2 = random(tw,1) and vi’s key: ki = (r2)1/wi + //! 9. The new threshold Tw is the new minimum key of R + //! we generate a random number between (min_weight_threshold, 1) + auto &sampler = Sampler(); + double r2 = RandomEngine::NextRandom(sampler.random, sampler.min_weight_threshold, 1); + + //! if we are merging two reservoir samples use the weight passed + if (with_weight >= 0) { + r2 = with_weight; + } + //! pop the minimum entry and insert the new weight + ReplaceElementWithIndex(sampler.min_weighted_entry_index, r2); + } + +private: + SAMPLER &Sampler() { + return static_cast(*this); + } +}; + +class BaseReservoirSampling : public ReservoirSampler { + friend class ReservoirSampler; + +public: + explicit BaseReservoirSampling(int64_t seed); + BaseReservoirSampling(); void UpdateMinWeightThreshold(); @@ -93,6 +164,18 @@ class BaseReservoirSampling { // of tuples in the sample. The blocking sample can then easily maintain statistical properties // from the sample point of view. friend class BlockingSample; + +private: + const std::pair &TopWeight() const { + D_ASSERT(!reservoir_weights.empty()); + return reservoir_weights.top(); + } + void PopWeight() { + reservoir_weights.pop(); + } + void PushWeight(double weight, idx_t index) { + reservoir_weights.emplace(weight, index); + } }; class BlockingSample { diff --git a/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp index 7e37dbc59..c843f3859 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/generic_functions.hpp @@ -96,4 +96,14 @@ struct InvokeFun { static ScalarFunction GetFunction(); }; +struct HashFun { + static constexpr const char *Name = "hash"; + static constexpr const char *Parameters = "value"; + static constexpr const char *Description = "Returns a `UBIGINT` with the hash of the `value`. Note that this is not a cryptographic hash."; + static constexpr const char *Example = "hash('🦆')"; + static constexpr const char *Categories = "string"; + + static ScalarFunction GetFunction(); +}; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp b/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp index f53262053..57b4e4846 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_naive_aggregator.hpp @@ -31,6 +31,8 @@ class WindowNaiveAggregator : public WindowAggregator { const WindowAggregateExecutor &executor; //! Whether two rows have the same arguments, over [left arguments..., right arguments...] (can be nullptr) unique_ptr args_equal; + //! "hash(#0, #1, ...)" over the arguments + unique_ptr args_hash; //! The column indices of any ORDER BY argument expressions vector arg_order_idx; }; diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index 1bc467703..f7f556f10 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -258,7 +258,6 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"greatest_common_divisor", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"group_concat", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"hamming", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, - {"hash", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"hex", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"histogram", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, {"histogram_exact", "core_functions", CatalogType::AGGREGATE_FUNCTION_ENTRY}, diff --git a/src/duckdb/src/include/duckdb/main/user_settings.hpp b/src/duckdb/src/include/duckdb/main/user_settings.hpp index f07e39d3d..0fe94e2c5 100644 --- a/src/duckdb/src/include/duckdb/main/user_settings.hpp +++ b/src/duckdb/src/include/duckdb/main/user_settings.hpp @@ -27,7 +27,8 @@ struct GenericSetting { struct UserSettingsMap { public: - void SetUserSetting(idx_t setting_index, Value target_value); + //! Returns whether the setting was updated. + bool SetUserSetting(idx_t setting_index, Value target_value); void ClearSetting(idx_t setting_index); bool IsSet(idx_t setting_index) const; bool TryGetSetting(idx_t setting_index, Value &result_value) const; diff --git a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp index 9be3a56ca..9efb63ac4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp @@ -48,7 +48,7 @@ class TopNWindowElimination : public LogicalOperatorVisitor { // Returns the <= index for TopN, if any // Note that it can return 0 if the filter removes all rows! - static optional_idx CanOptimize(LogicalOperator &op); + static optional_idx CanOptimize(LogicalOperator &op, ClientContext &client); private: unique_ptr OptimizeInternal(unique_ptr op, ColumnBindingReplacer &replacer); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_hash_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_hash_expression.hpp new file mode 100644 index 000000000..ff1faee2a --- /dev/null +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_hash_expression.hpp @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/planner/expression/bound_hash_expression.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/expression.hpp" + +namespace duckdb { +class ClientContext; +class DataChunk; +class ExpressionExecutor; +class Vector; + +//! Helper methods to hash the columns of a chunk through an ExpressionExecutor +struct BoundHashExpression { + //! Create "hash(#column_ids[0], #column_ids[1], ...)" over input columns of the given types, without collations + static unique_ptr CreateOnColumns(ClientContext &context, const vector &types, + const vector &column_ids); + //! Create "hash(#0, #1, ...)" over all input columns of the given types + static unique_ptr CreateOnColumns(ClientContext &context, const vector &types); + //! Execute the hash expression expr_idx of the executor over the input into a flat or constant vector + static void Execute(ExpressionExecutor &executor, DataChunk &input, Vector &hashes, idx_t expr_idx = 0); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp index 3a14dcccf..f6aa07258 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_window.hpp @@ -39,6 +39,7 @@ class LogicalWindow : public LogicalOperator { static unique_ptr Deserialize(Deserializer &deserializer); vector GetTableIndex() const override; string GetName() const override; + InsertionOrderPreservingMap ParamsToString() const override; protected: void ResolveTypes() override; diff --git a/src/duckdb/src/main/http/http_client_httplib.cpp b/src/duckdb/src/main/http/http_client_httplib.cpp index 55f69bf18..c33a66018 100644 --- a/src/duckdb/src/main/http/http_client_httplib.cpp +++ b/src/duckdb/src/main/http/http_client_httplib.cpp @@ -35,6 +35,7 @@ class HTTPLibClient : public HTTPClient { client->set_read_timeout(sec, usec); client->set_connection_timeout(sec, usec); client->set_decompress(false); + client->set_payload_max_length(idx_t(2) * 1024 * 1024 * 1024); if (!http_params.http_proxy.empty()) { client->set_proxy(http_params.http_proxy, static_cast(http_params.http_proxy_port)); diff --git a/src/duckdb/src/main/user_settings.cpp b/src/duckdb/src/main/user_settings.cpp index bff02eca9..45f7beb08 100644 --- a/src/duckdb/src/main/user_settings.cpp +++ b/src/duckdb/src/main/user_settings.cpp @@ -1,20 +1,97 @@ #include "duckdb/main/user_settings.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/string.hpp" +#include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/uuid.hpp" + +#include #ifdef __MVS__ #include #endif namespace duckdb { -void UserSettingsMap::SetUserSetting(idx_t setting_index, Value target_value) { +static bool HasUserSettingExtensionType(const LogicalType &type) { + if (!type.IsNested()) { + return type.HasExtensionInfo(); + } + return TypeVisitor::Contains(type, [](const LogicalType &child) { return child.HasExtensionInfo(); }); +} + +static bool UserSettingValuesEqual(const Value &left, const Value &right); + +static bool UserSettingChildrenEqual(const vector &left, const vector &right) { + if (left.size() != right.size()) { + return false; + } + for (idx_t i = 0; i < left.size(); i++) { + if (!UserSettingValuesEqual(left[i], right[i])) { + return false; + } + } + return true; +} + +static bool UserSettingValuesEqual(const Value &left, const Value &right) { + // A no-op must preserve the type; NotDistinctFrom can cast values or equate differently typed NULLs. + if (left.type() != right.type()) { + return false; + } + // Ordinary type equality ignores collations, including those on nested child types. + if ((left.type().IsNested() || left.type().id() == LogicalTypeId::VARCHAR) && + !left.type().EqualsIncludingCollation(right.type())) { + return false; + } + if (left.IsNull() || right.IsNull()) { + return Value::NotDistinctFrom(left, right); + } + switch (left.type().InternalType()) { + // NotDistinctFrom equates signed zeros and NaNs; preserve the sign and allow NaNs to miss the no-op. + case PhysicalType::FLOAT: { + const auto lvalue = left.GetValueUnsafe(); + const auto rvalue = right.GetValueUnsafe(); + return lvalue == rvalue && std::signbit(lvalue) == std::signbit(rvalue); + } + case PhysicalType::DOUBLE: { + const auto lvalue = left.GetValueUnsafe(); + const auto rvalue = right.GetValueUnsafe(); + return lvalue == rvalue && std::signbit(lvalue) == std::signbit(rvalue); + } + // NotDistinctFrom equates 1 month with 30 days, but date arithmetic distinguishes them. + case PhysicalType::INTERVAL: + return left.GetValueUnsafe().SameFields(right.GetValueUnsafe()); + // SQL nested equality applies those same normalizations to children; recurse with these stricter rules. + case PhysicalType::STRUCT: + return UserSettingChildrenEqual(StructValue::GetChildren(left), StructValue::GetChildren(right)); + case PhysicalType::LIST: + return UserSettingChildrenEqual(ListValue::GetChildren(left), ListValue::GetChildren(right)); + case PhysicalType::ARRAY: + return UserSettingChildrenEqual(ArrayValue::GetChildren(left), ArrayValue::GetChildren(right)); + // NotDistinctFrom does not implement comparisons for these internal types. + case PhysicalType::INVALID: + case PhysicalType::UNKNOWN: + case PhysicalType::BIT: + return false; + default: + return Value::NotDistinctFrom(left, right); + } +} + +bool UserSettingsMap::SetUserSetting(idx_t setting_index, Value target_value) { if (setting_index >= settings.size()) { settings.resize(setting_index + 1); } auto &generic_setting = settings[setting_index]; + // Extension type equality can ignore missing modifiers and properties. + if (generic_setting.is_set && !HasUserSettingExtensionType(generic_setting.value.type()) && + !HasUserSettingExtensionType(target_value.type()) && + UserSettingValuesEqual(generic_setting.value, target_value)) { + return false; + } generic_setting.is_set = true; generic_setting.value = std::move(target_value); + return true; } void UserSettingsMap::ClearSetting(idx_t setting_index) { @@ -68,8 +145,9 @@ GlobalUserSettings &GlobalUserSettings::operator=(const GlobalUserSettings &othe void GlobalUserSettings::SetUserSetting(idx_t setting_index, Value target_value) { lock_guard guard(lock); - settings_map.SetUserSetting(setting_index, std::move(target_value)); - ++settings_version; + if (settings_map.SetUserSetting(setting_index, std::move(target_value))) { + ++settings_version; + } } void GlobalUserSettings::ClearSetting(idx_t setting_index) { diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index 9001df91e..10fe09bc6 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -515,12 +515,6 @@ void Optimizer::RunBuiltInOptimizers() { }); } - // rewrite unique ranking window function + filter on row_number to fused operator - RunOptimizer(OptimizerType::WINDOW_FUSION, [&]() { - WindowFusion window_fusion(context, &statistics_map); - plan = window_fusion.Optimize(std::move(plan)); - }); - // rewrite row_number window function + filter on row_number to aggregate bool topn_used_late_materialization = false; RunOptimizer(OptimizerType::TOP_N_WINDOW_ELIMINATION, [&]() { @@ -529,6 +523,12 @@ void Optimizer::RunBuiltInOptimizers() { topn_used_late_materialization = topn_window_elimination.UsedLateMaterialization(); }); + // rewrite unique ranking window function + filters to a fused operator + RunOptimizer(OptimizerType::WINDOW_FUSION, [&]() { + WindowFusion window_fusion(context, &statistics_map); + plan = window_fusion.Optimize(std::move(plan)); + }); + // remove duplicate aggregates RunOptimizer(OptimizerType::COMMON_AGGREGATE, [&]() { CommonAggregateOptimizer common_aggregate; diff --git a/src/duckdb/src/optimizer/rule/regex_optimizations.cpp b/src/duckdb/src/optimizer/rule/regex_optimizations.cpp index e3fa9578f..ed0907545 100644 --- a/src/duckdb/src/optimizer/rule/regex_optimizations.cpp +++ b/src/duckdb/src/optimizer/rule/regex_optimizations.cpp @@ -104,15 +104,16 @@ static LikeString LikeMatchFromRegex(duckdb_re2::RE2 &pattern) { ret.like_string += "%"; } break; - case duckdb_re2::kRegexpStar: - // .* is a Star operator is a anyChar operator as a child. - // any other child operator would represent a pattern LIKE cannot match. - if (subs[cur_sub_index]->nsub() == 1 && subs[cur_sub_index]->sub()[0]->op() == duckdb_re2::kRegexpAnyChar) { + case duckdb_re2::kRegexpStar: { + // a star at either edge can match the empty string; elsewhere only .* (with 's') maps to % + bool at_edge = cur_sub_index == 0 || cur_sub_index + 1 == num_subs; + if (at_edge || subs[cur_sub_index]->sub()[0]->op() == duckdb_re2::kRegexpAnyChar) { ret.like_string += "%"; break; } ret.exists = false; return ret; + } case duckdb_re2::kRegexpLiteralString: case duckdb_re2::kRegexpLiteral: { // if this is the only matching op, we should have directly called diff --git a/src/duckdb/src/optimizer/topn_optimizer.cpp b/src/duckdb/src/optimizer/topn_optimizer.cpp index a2c9f805b..bf8608355 100644 --- a/src/duckdb/src/optimizer/topn_optimizer.cpp +++ b/src/duckdb/src/optimizer/topn_optimizer.cpp @@ -13,6 +13,7 @@ #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/sorting/topn_heap.hpp" namespace duckdb { @@ -40,15 +41,11 @@ bool TopN::CanOptimize(LogicalOperator &op, optional_ptr context) if (child_op->has_estimated_cardinality) { // only check if we should switch to full sorting if we have estimated cardinality - auto constant_limit = static_cast(limit.limit_val.GetConstantValue()); + auto constant_limit = limit.limit_val.GetConstantValue(); if (limit.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) { - constant_limit += static_cast(limit.offset_val.GetConstantValue()); + constant_limit += limit.offset_val.GetConstantValue(); } - auto child_card = static_cast(child_op->estimated_cardinality); - - // if the limit is > 0.7% of the child cardinality, sorting the whole table is faster - bool limit_is_large = constant_limit > 5000; - if (constant_limit > child_card * 0.007 && limit_is_large) { + if (!TopNHeap::CanOptimize(constant_limit, child_op->estimated_cardinality)) { return false; } } diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 7b39fe4bf..6fc1730f7 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -234,7 +234,7 @@ unique_ptr TopNWindowElimination::Optimize(unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptr op, ColumnBindingReplacer &replacer) { - const auto limit = CanOptimize(*op); + const auto limit = CanOptimize(*op, context); if (!limit.IsValid()) { // Traverse through query plan to find grouped top-n pattern if (op->children.size() > 1) { @@ -544,7 +544,7 @@ TopNWindowElimination::CreateProjectionOperator(unique_ptr op, return unique_ptr(std::move(logical_projection)); } -optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { +optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op, ClientContext &client) { const optional_idx cant_optimize; if (op.type != LogicalOperatorType::LOGICAL_FILTER) { return cant_optimize; @@ -650,11 +650,7 @@ optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { if (child.get().type != LogicalOperatorType::LOGICAL_WINDOW) { return cant_optimize; } - const auto &window = child.get().Cast(); - // Give up if window fusion has already taking this. - if (window.partition_limit.IsValid()) { - return cant_optimize; - } + auto &window = child.get().Cast(); if (window.window_index != filter_col_idx) { return cant_optimize; } @@ -682,11 +678,39 @@ optional_idx TopNWindowElimination::CanOptimize(LogicalOperator &op) { if (window_expr.OrderBy().size() != 1) { return cant_optimize; } - if (window_expr.OrderBy()[0].type != OrderType::DESCENDING && - window_expr.OrderBy()[0].type != OrderType::ASCENDING) { + + const auto &order = window_expr.OrderBy()[0]; + if (order.type != OrderType::DESCENDING && order.type != OrderType::ASCENDING) { + return cant_optimize; + } + if (order.null_order != OrderByNullType::NULLS_LAST) { + return cant_optimize; + } + + // Window fusion works better than TopN for certain cases + + // Fusion does not yet support partitioning + if (!window_expr.Partitions().empty()) { + return can_optimize; + } + + // Fusion is better for non-numeric keys + if (!TypeIsNumeric(order.expression->GetReturnType().InternalType())) { + return cant_optimize; + } + + // Fusion is better for large ranges + if (can_optimize.GetIndex() > 5000) { return cant_optimize; } - if (window_expr.OrderBy()[0].null_order != OrderByNullType::NULLS_LAST) { + + // TopN is better for k == 1 + if (can_optimize.GetIndex() == 1) { + return can_optimize; + } + + // TopN is better for small cardinalities + if (op.EstimateCardinality(client) > 400000) { return cant_optimize; } diff --git a/src/duckdb/src/optimizer/window_fusion.cpp b/src/duckdb/src/optimizer/window_fusion.cpp index 581b388c1..b225bf991 100644 --- a/src/duckdb/src/optimizer/window_fusion.cpp +++ b/src/duckdb/src/optimizer/window_fusion.cpp @@ -5,6 +5,7 @@ #include "duckdb/main/database.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_window.hpp" @@ -98,12 +99,11 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { D_ASSERT(current_column_ref.table_index == projection.table_index); // The filter has to name the window column itself. An expression that only mentions it, such as // row_number + 10, is a different predicate, and following the inner reference would drop that expression. - auto &proj_expr = *projection.expressions[current_column_ref.column_index]; - if (proj_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + auto &proj_expr = projection.expressions[current_column_ref.column_index]; + if (proj_expr->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return cant_optimize; } - column_references = - ColumnReferenceExtractor::GetReferences(&projection.expressions[current_column_ref.column_index]); + column_references = ColumnReferenceExtractor::GetReferences(&proj_expr); child = *child.get().children[0]; } @@ -111,32 +111,26 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { if (column_references.size() != 1) { return cant_optimize; } - const auto filter_col_idx = column_references.begin()->first.table_index; + const auto &filter_ref = column_references.begin()->first; if (child.get().type != LogicalOperatorType::LOGICAL_WINDOW) { return cant_optimize; } const auto &window = child.get().Cast(); - if (window.window_index != filter_col_idx) { + if (window.window_index != filter_ref.table_index) { return cant_optimize; } - const auto &first_window_expr = window.expressions[0]->Cast(); - for (auto &partition : first_window_expr.Partitions()) { - if (partition->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return cant_optimize; - } + auto &window_expr = window.expressions[0]->Cast(); + if (window_expr.GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { + return cant_optimize; } if (window.expressions.size() != 1) { for (idx_t i = 1; i < window.expressions.size(); ++i) { - if (!window.expressions[i]->Equals(first_window_expr)) { + if (!window.expressions[i]->Equals(window_expr)) { return cant_optimize; } } } - if (window.expressions[0]->GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { - return cant_optimize; - } - auto &window_expr = window.expressions[0]->Cast(); if (!window_expr.ArgOrders().empty()) { return cant_optimize; @@ -157,6 +151,10 @@ unique_ptr WindowFusion::OptimizeInternal(unique_ptr(std::move(op)); + } + // Remove the Filter D_ASSERT(op->children.size() == 1); auto &filter = op->Cast(); @@ -171,7 +169,7 @@ unique_ptr WindowFusion::OptimizeInternal(unique_ptrCast(); // Restrict to implemented cases - if (!PhysicalStreamingWindow::IsStreamingFunction(client, wexpr)) { + if (!wexpr.Partitions().empty()) { return op; } diff --git a/src/duckdb/src/planner/operator/logical_window.cpp b/src/duckdb/src/planner/operator/logical_window.cpp index bba35b825..57604e405 100644 --- a/src/duckdb/src/planner/operator/logical_window.cpp +++ b/src/duckdb/src/planner/operator/logical_window.cpp @@ -33,4 +33,14 @@ string LogicalWindow::GetName() const { return LogicalOperator::GetName(); } +InsertionOrderPreservingMap LogicalWindow::ParamsToString() const { + auto result = LogicalOperator::ParamsToString(); + + if (partition_limit.IsValid()) { + result["Limit"] = to_string(partition_limit.GetIndex()); + } + + return result; +} + } // namespace duckdb diff --git a/src/duckdb/src/storage/compression/dict_fsst.cpp b/src/duckdb/src/storage/compression/dict_fsst.cpp index 697fbce9b..22dd2dc21 100644 --- a/src/duckdb/src/storage/compression/dict_fsst.cpp +++ b/src/duckdb/src/storage/compression/dict_fsst.cpp @@ -151,11 +151,22 @@ void DictFSSTCompressionStorage::StringScan(ColumnSegment &segment, ColumnScanSt //===--------------------------------------------------------------------===// // Select //===--------------------------------------------------------------------===// +static bool PreferSparseDictionary(const ColumnSegment &segment, const CompressedStringScanState &scan_state, + idx_t vector_count, idx_t sel_count) { + return scan_state.layout.mode == DictFSSTMode::DICT_FSST && scan_state.layout.dict_count >= 512 && + idx_t(scan_state.layout.dict_count) * 8 >= segment.count.load() && sel_count <= vector_count / 64; +} + void DictFSSTSelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, Vector &result, const SelectionVector &sel, idx_t sel_count, idx_t result_offset, ScanVectorType scan_type) { D_ASSERT(sel_count <= vector_count); D_ASSERT(sel_count == 0 || sel.get_index(sel_count - 1) < vector_count); auto &scan_state = state.scan_state->Cast(); + if (!scan_state.dictionary && PreferSparseDictionary(segment, scan_state, vector_count, sel_count)) { + scan_state.Select(result, result_offset, state.GetPositionInSegment(), sel, sel_count, + StringScanType::COPY_STRINGS); + return; + } if (scan_state.layout.mode != DictFSSTMode::FSST_ONLY && scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR) { if (sel_count <= vector_count / 64) { scan_state.SelectToDictionaryVector(result, state.GetPositionInSegment(), vector_count, sel, sel_count); @@ -177,6 +188,49 @@ static void DictFSSTFilter(ColumnSegment &segment, ColumnScanState &state, idx_t D_ASSERT(sel_count <= vector_count); auto &scan_state = state.scan_state->Cast(); auto start = state.GetPositionInSegment(); + const bool sparse_dictionary = PreferSparseDictionary(segment, scan_state, vector_count, sel_count) && + (!scan_state.filter_cache || !scan_state.filter_cache->IsValidFor(filter_state)); + if (sparse_dictionary || (scan_state.layout.mode == DictFSSTMode::FSST_ONLY && sel_count <= vector_count / 2)) { + SelectionVector input_rows(sel_count); + SelectionVector compact_sel(sel_count); + for (idx_t i = 0; i < sel_count; i++) { + input_rows.set_index(i, sel.get_index(i)); + compact_sel.set_index(i, i); + } + Vector decoded(result.GetType()); + scan_state.Select(decoded, 0, start, input_rows, sel_count, + sparse_dictionary && !scan_state.dictionary ? StringScanType::COPY_STRINGS + : state.string_scan_type); + const auto decoded_count = sel_count; + ColumnSegment::FilterSelection(compact_sel, decoded, filter_state, decoded_count, sel_count); + if (sel_count == 0) { + return; + } + + // Restore the original row positions expected by the scan. + StringVector::AddHeapReference(result, decoded); + if (scan_state.dictionary) { + StringVector::AddHeapReference(result, scan_state.dictionary->data); + } + auto values = decoded.Values(); + auto writer = FlatVector::Writer(result, vector_count); + idx_t survivor = 0; + for (idx_t row = 0; row < vector_count; row++) { + if (survivor == sel_count || input_rows.get_index(compact_sel.get_index(survivor)) != row) { + writer.WriteNull(); + continue; + } + auto value = values[compact_sel.get_index(survivor)]; + if (value.IsValid()) { + writer.WriteStringRef(value.GetValue()); + } else { + writer.WriteNull(); + } + sel.set_index(survivor++, row); + } + D_ASSERT(survivor == sel_count); + return; + } if (scan_state.AllowDictionaryScan(vector_count)) { if (!scan_state.filter_cache || !scan_state.filter_cache->IsValidFor(filter_state)) { scan_state.filter_cache = diff --git a/src/duckdb/src/storage/table/struct_column_data.cpp b/src/duckdb/src/storage/table/struct_column_data.cpp index 3e47b3bb7..70d380cb3 100644 --- a/src/duckdb/src/storage/table/struct_column_data.cpp +++ b/src/duckdb/src/storage/table/struct_column_data.cpp @@ -177,7 +177,13 @@ idx_t StructColumnData::Scan(TransactionData transaction, idx_t vector_index, Co if (!ConstantVector::IsNull(result)) { throw InternalException("StructColumnData::Scan returned a constant but not NULL vector "); } - // constant NULL struct - we don't need to scan any children, everything is already NULL + // constant NULL struct - skip the children instead of scanning them, everything is already NULL + auto struct_children = GetStructChildren(state); + for (auto &child : struct_children) { + if (child.should_scan) { + child.col.Skip(child.state, scan_count); + } + } return scan_count; } } diff --git a/src/duckdb/ub_extension_core_functions_scalar_generic.cpp b/src/duckdb/ub_extension_core_functions_scalar_generic.cpp index eca94e2e4..904df26c1 100644 --- a/src/duckdb/ub_extension_core_functions_scalar_generic.cpp +++ b/src/duckdb/ub_extension_core_functions_scalar_generic.cpp @@ -8,8 +8,6 @@ #include "extension/core_functions/scalar/generic/current_setting.cpp" -#include "extension/core_functions/scalar/generic/hash.cpp" - #include "extension/core_functions/scalar/generic/least.cpp" #include "extension/core_functions/scalar/generic/replace_type.cpp" diff --git a/src/duckdb/ub_src_common_sort.cpp b/src/duckdb/ub_src_common_sort.cpp index 667112484..bb93c57b2 100644 --- a/src/duckdb/ub_src_common_sort.cpp +++ b/src/duckdb/ub_src_common_sort.cpp @@ -16,3 +16,7 @@ #include "src/common/sort/sorted_run_merger.cpp" +#include "src/common/sort/topn_heap.cpp" + +#include "src/common/sort/topn_sort.cpp" + diff --git a/src/duckdb/ub_src_function_scalar_generic.cpp b/src/duckdb/ub_src_function_scalar_generic.cpp index 0e13c7e74..beff95699 100644 --- a/src/duckdb/ub_src_function_scalar_generic.cpp +++ b/src/duckdb/ub_src_function_scalar_generic.cpp @@ -8,6 +8,8 @@ #include "src/function/scalar/generic/has_error.cpp" +#include "src/function/scalar/generic/hash.cpp" + #include "src/function/scalar/generic/invoke.cpp" #include "src/function/scalar/generic/try_rethrow.cpp"