Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
171 changes: 163 additions & 8 deletions src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ struct KahanAvgState {
void Combine(const KahanAvgState &other) {
this->count += other.count;
KahanAddInternal(other.value, this->value, this->err);
KahanAddInternal(-other.err, this->value, this->err);
this->err += other.err;
}
};

Expand Down Expand Up @@ -229,6 +229,92 @@ struct TimestampAverageOperation : public DiscreteAverageOperation {
}
};

//! The average of timestamps in nanosecond resolution - mirrors TimestampAverageOperation, but
//! interprets the state value as a nanosecond timestamp so infinity is the ns infinity
template <class NS_TIMESTAMP>
struct TimestampNSAverageOperation : public DiscreteAverageOperation {
static constexpr uint64_t INFINITE_COUNT = NumericLimits<uint64_t>::Maximum();
static constexpr uint64_t POSITIVE_INFINITY = 1;
static constexpr uint64_t NEGATIVE_INFINITY = 2;
static constexpr uint64_t BOTH_INFINITIES = POSITIVE_INFINITY | NEGATIVE_INFINITY;

template <class STATE>
static void AddInfinities(STATE &state, uint64_t infinities) {
if (state.count != INFINITE_COUNT) {
state.count = INFINITE_COUNT;
state.value = hugeint_t(0);
}
state.value.lower |= infinities;
}

static uint64_t GetInfinity(int64_t input) {
return input > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
}

template <class STATE, class OP>
static void Combine(const STATE &source, STATE &target, AggregateInputData &) {
if (source.count == INFINITE_COUNT) {
AddInfinities(target, source.value.lower);
} else if (source.count != 0 && target.count != INFINITE_COUNT) {
if (target.count == 0) {
// an empty target holds no sum
target.value = hugeint_t(0);
}
if (!TryAddOperator::Operation(target.count, source.count, target.count) ||
target.count == INFINITE_COUNT) {
throw OutOfRangeException("Overflow in aggregate state combine");
}
CombineSumStateValue(target.value, source.value);
}
}

template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) {
if (source.count == INFINITE_COUNT) {
if (count > 0) {
AddInfinities(target, source.value.lower);
}
} else if (target.count != INFINITE_COUNT) {
DiscreteAverageOperation::RepeatedCombine<STATE, OP>(source, target, input, count);
if (target.count == INFINITE_COUNT) {
throw OutOfRangeException("Overflow in repeated aggregate state combine");
}
}
}

template <class INPUT_TYPE, class STATE, class OP>
static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) {
if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) {
AddInfinities(state, GetInfinity(input));
} else if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::Operation<INPUT_TYPE, STATE, OP>(state, input, unary_input);
}
}

template <class INPUT_TYPE, class STATE, class OP>
static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input,
idx_t count) {
if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) {
AddInfinities(state, GetInfinity(input));
} else if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::ConstantOperation<INPUT_TYPE, STATE, OP>(state, input, unary_input, count);
}
}

template <class T, class STATE>
static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) {
if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::Finalize<T, STATE>(state, target, finalize_data);
} else if (state.value == hugeint_t(POSITIVE_INFINITY)) {
target = NS_TIMESTAMP::infinity().value;
} else if (state.value == hugeint_t(NEGATIVE_INFINITY)) {
target = NS_TIMESTAMP::ninfinity().value;
} else {
finalize_data.ReturnNull();
}
}
};

//! A state with the maximum count holds only infinities, reject imported ones that hold other values
void ValidateTimestampAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) {
for (idx_t i = 0; i < count; i++) {
Expand Down Expand Up @@ -271,6 +357,27 @@ AggregateStateLayout TimeAverageStateLayout(AggregateLayoutInput &input) {
return layout;
}

//! The average of TIME_NS values is within a day - reject imported states that average outside of it
void ValidateTimeNSAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) {
for (idx_t i = 0; i < count; i++) {
const auto state = Load<AvgState<hugeint_t>>(states + i * stride);
if (state.count == 0) {
continue;
}
const auto max_value = hugeint_t(0, state.count) * hugeint_t(Interval::NANOS_PER_DAY);
if (state.value < 0 || state.value > max_value) {
throw InvalidInputException("Invalid avg state - the average of %s over %llu values is not a valid time",
state.value.ToString(), state.count);
}
}
}

AggregateStateLayout TimeNSAverageStateLayout(AggregateLayoutInput &input) {
auto layout = AggregateFunction::StructStateLayout<AvgState<hugeint_t>>(input);
layout.validate_state = ValidateTimeNSAverageStates;
return layout;
}

struct HugeintAverageOperation : public BaseSumOperation<AverageSetOperation, HugeintAdd> {
template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) {
Expand Down Expand Up @@ -310,7 +417,7 @@ struct KahanAverageOperation : public BaseSumOperation<AverageSetOperation, Kaha
if (state.count == 0) {
finalize_data.ReturnNull();
} else {
target = (state.value / state.count) - (state.err / state.count);
target = KahanFinalize(state.value, state.err) / static_cast<double>(state.count);
}
}
};
Expand Down Expand Up @@ -441,6 +548,35 @@ unique_ptr<FunctionData> BindDecimalAvg(BindAggregateFunctionInput &input) {
Hugeint::Cast<double>(Hugeint::POWERS_OF_TEN[DecimalType::GetScale(decimal_type)]));
}

AggregateFunction GetTimestampAverage() {
auto timestamp_avg =
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t, TimestampAverageOperation>(
LogicalType::TIMESTAMP, LogicalType::TIMESTAMP);
timestamp_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_avg.SetStructStateExport(TimestampAverageStateLayout);
return timestamp_avg;
}

//! Averages the argument as a TIMESTAMP, whose range holds every ordinary date of the lower precisions
unique_ptr<FunctionData> BindWidenedTimestampAvg(BindAggregateFunctionInput &input) {
auto &function = input.GetBoundFunction();
function.ReplaceImplementation(GetTimestampAverage());
function.SetName("avg");
function.GetArguments()[0] = LogicalType::TIMESTAMP;
function.SetReturnType(LogicalType::TIMESTAMP);
return nullptr;
}

//! Without an overload of their own, TIMESTAMP_S, TIMESTAMP_MS and DATE would widen to TIMESTAMP_NS, the cheapest
//! implicit cast, whose range is far smaller than theirs
AggregateFunction GetWidenedTimestampAverage(const LogicalType &type) {
// stub function, the bind sets the TIMESTAMP implementation and the argument type it casts to
AggregateFunction fun({}, LogicalType::TIMESTAMP, nullptr, nullptr, nullptr, nullptr, nullptr,
FunctionNullHandling::DEFAULT_NULL_HANDLING, nullptr, BindWidenedTimestampAvg);
fun.GetSignature().AddParameter("x", type);
return fun;
}

} // namespace

AggregateFunctionSet AvgFun::GetFunctions() {
Expand All @@ -461,12 +597,10 @@ AggregateFunctionSet AvgFun::GetFunctions() {
numeric_avg.GetSignature().GetParameter(0).SetName("x");
avg.AddFunction(numeric_avg);

auto timestamp_avg =
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t, TimestampAverageOperation>(
LogicalType::TIMESTAMP, LogicalType::TIMESTAMP);
timestamp_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_avg.SetStructStateExport(TimestampAverageStateLayout);
avg.AddFunction(timestamp_avg);
avg.AddFunction(GetTimestampAverage());
for (auto &type : {LogicalType::TIMESTAMP_S, LogicalType::TIMESTAMP_MS, LogicalType::DATE}) {
avg.AddFunction(GetWidenedTimestampAverage(type));
}

auto timestamp_tz_avg =
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t, TimestampAverageOperation>(
Expand All @@ -488,6 +622,27 @@ AggregateFunctionSet AvgFun::GetFunctions() {
time_tz_avg.SetStructStateExport(TimeAverageStateLayout);
avg.AddFunction(time_tz_avg);

auto timestamp_ns_avg = AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t,
TimestampNSAverageOperation<timestamp_ns_t>>(
LogicalType::TIMESTAMP_NS, LogicalType::TIMESTAMP_NS);
timestamp_ns_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_ns_avg.SetStructStateExport(TimestampAverageStateLayout);
avg.AddFunction(timestamp_ns_avg);

auto timestamp_tz_ns_avg = AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t,
TimestampNSAverageOperation<timestamp_tz_ns_t>>(
LogicalType::TIMESTAMP_TZ_NS, LogicalType::TIMESTAMP_TZ_NS);
timestamp_tz_ns_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_tz_ns_avg.SetStructStateExport(TimestampAverageStateLayout);
avg.AddFunction(timestamp_tz_ns_avg);

auto time_ns_avg =
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t, DiscreteAverageOperation>(
LogicalType::TIME_NS, LogicalType::TIME_NS);
time_ns_avg.GetSignature().GetParameter(0).SetName("x");
time_ns_avg.SetStructStateExport(TimeNSAverageStateLayout);
avg.AddFunction(time_ns_avg);

return avg;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ struct KahanSumOperation : public BaseSumOperation<KahanSumSetOperation, KahanAd
if (!state.is_set) {
finalize_data.ReturnNull();
} else {
target = state.value;
target = KahanFinalize(state.value, state.err);
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ struct ApproxTopKOperation {
return;
}
source.Verify();
auto min_source = source.values.back().get().count;
auto min_source = source.values.size() < source.capacity ? 0 : source.values.back().get().count;
idx_t min_target;
if (target.values.empty()) {
min_target = 0;
Expand All @@ -249,7 +249,7 @@ struct ApproxTopKOperation {
throw NotImplementedException("Approx Top K - cannot combine approx_top_K with different k values. "
"K values must be the same for all entries within the same group");
}
min_target = target.values.back().get().count;
min_target = target.values.size() < target.capacity ? 0 : target.values.back().get().count;
}
// for all entries in target
// check if they are tracked in source
Expand Down Expand Up @@ -559,6 +559,10 @@ void ApproxTopKImportState(AggregateImportInputData &input) {
throw InvalidInputException("Invalid approx_top_k state - the filter values cannot be NULL");
}
target.filter[filter_idx] = filter_data[filter_entry_idx];
if (target.filter[filter_idx] != 0 && target.values.size() < target.capacity) {
throw InvalidInputException(
"Invalid approx_top_k state - the filter must be empty unless the state holds 3 * k values");
}
}
target.Verify();
state.state = internal_state.release();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,9 @@ AggregateFunction GetApproximateQuantileAggregateFunction(const LogicalType &typ
return AggregateFunction::UnaryAggregate<ApproxQuantileState, dtime_t, dtime_t, ApproxQuantileScalarOperation>(
type, type);
}
if (type.id() == LogicalTypeId::TIMESTAMP || type.id() == LogicalTypeId::TIMESTAMP_TZ) {
if (type.id() == LogicalTypeId::TIMESTAMP || type.id() == LogicalTypeId::TIMESTAMP_TZ ||
type.id() == LogicalTypeId::TIMESTAMP_NS || type.id() == LogicalTypeId::TIMESTAMP_TZ_NS) {
// every timestamp precision stores an int64 with the same two infinities, which the coding keeps infinite
return AggregateFunction::UnaryAggregate<ApproxQuantileState, timestamp_t, timestamp_t,
ApproxQuantileScalarOperation>(type, type);
}
Expand Down Expand Up @@ -466,10 +468,10 @@ AggregateFunction ApproxQuantileDecimalFunction(const LogicalType &type) {
return function;
}

//! Specialises the (stub) DECIMAL function to the implementation over the DECIMAL's physical type. The implementation
//! only declares the input argument, so the quantile argument that BindApproxQuantile folded into the bind data is
//! restored afterwards.
void ReplaceApproxQuantileDecimal(BoundAggregateFunction &function, const AggregateFunction &implementation) {
//! Specialises a stub function, the DECIMAL ones to the implementation over the DECIMAL's physical type and the
//! TIMESTAMP_S and TIMESTAMP_MS ones to the TIMESTAMP implementation. The implementation only declares the input
//! argument, so the quantile argument that BindApproxQuantile folded into the bind data is restored afterwards.
void ReplaceApproxQuantileImplementation(BoundAggregateFunction &function, const AggregateFunction &implementation) {
auto declared_arguments = function.GetArguments();
function.ReplaceImplementation(implementation);
for (idx_t i = function.GetArguments().size(); i < declared_arguments.size(); i++) {
Expand All @@ -482,7 +484,7 @@ unique_ptr<FunctionData> BindApproxQuantileDecimal(BindAggregateFunctionInput &i
auto &arguments = input.GetArguments();
auto decimal_type = arguments[0]->GetReturnType();
auto bind_data = BindApproxQuantile(input);
ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalFunction(decimal_type));
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(decimal_type));
return bind_data;
}

Expand Down Expand Up @@ -609,7 +611,7 @@ unique_ptr<FunctionData> BindApproxQuantileDecimalList(BindAggregateFunctionInpu
auto &arguments = input.GetArguments();
auto decimal_type = arguments[0]->GetReturnType();
auto bind_data = BindApproxQuantile(input);
ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalListFunction(decimal_type));
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(decimal_type));
return bind_data;
}

Expand All @@ -631,9 +633,9 @@ unique_ptr<FunctionData> ApproxQuantileDecimalDeserialize(Deserializer &deserial
auto bind_data = ApproximateQuantileBindData::Deserialize(deserializer, function);
auto &return_type = deserializer.Get<const LogicalType &>();
if (return_type.id() == LogicalTypeId::LIST) {
ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalListFunction(function.GetArguments()[0]));
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(function.GetArguments()[0]));
} else {
ReplaceApproxQuantileDecimal(function, ApproxQuantileDecimalFunction(function.GetArguments()[0]));
ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(function.GetArguments()[0]));
}
return bind_data;
}
Expand All @@ -648,6 +650,37 @@ AggregateFunction GetApproxQuantileDecimal() {
return fun;
}

//! The TIMESTAMP implementation, which TIMESTAMP_S and TIMESTAMP_MS arguments are widened to
AggregateFunction ApproxQuantileTimestampFunction() {
auto function = GetApproximateQuantileAggregateFunction(LogicalType::TIMESTAMP);
function.SetName("approx_quantile");
function.SetSerializeCallback(ApproximateQuantileBindData::Serialize);
function.SetDeserializeCallback(ApproximateQuantileBindData::Deserialize);
function.SetStateExportCallbacks(ApproxQuantileGetStateType, ApproxQuantileExportState, ApproxQuantileImportState);
return function;
}

unique_ptr<FunctionData> BindApproxQuantileWidenedTimestamp(BindAggregateFunctionInput &input) {
auto &function = input.GetBoundFunction();
auto bind_data = BindApproxQuantile(input);
ReplaceApproxQuantileImplementation(function, ApproxQuantileTimestampFunction());
function.GetArguments()[0] = LogicalType::TIMESTAMP;
function.SetReturnType(LogicalType::TIMESTAMP);
return bind_data;
}

//! Without an overload of their own, TIMESTAMP_S and TIMESTAMP_MS would widen to TIMESTAMP_NS, the cheapest implicit
//! cast, whose range is far smaller than theirs
AggregateFunction GetApproxQuantileWidenedTimestamp(const LogicalType &type) {
// stub function, the bind sets the TIMESTAMP implementation and the argument type it casts to
AggregateFunction fun({}, LogicalType::TIMESTAMP, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
BindApproxQuantileWidenedTimestamp);
fun.GetSignature().AddParameter("x", type).AddParameter("pos", LogicalType::FLOAT);
fun.SetSerializeCallback(ApproximateQuantileBindData::Serialize);
fun.SetDeserializeCallback(ApproximateQuantileBindData::Deserialize);
return fun;
}

AggregateFunction GetApproxQuantileDecimalList() {
// stub function - the actual function is set during bind or deserialize
AggregateFunction fun({}, LogicalType::LIST(LogicalTypeId::DECIMAL), nullptr, nullptr, nullptr, nullptr, nullptr,
Expand All @@ -673,9 +706,14 @@ AggregateFunctionSet ApproxQuantileFun::GetFunctions() {

approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::DATE));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_NS));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_TZ));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_NS));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ_NS));
approx_quantile.AddFunction(GetApproxQuantileWidenedTimestamp(LogicalType::TIMESTAMP_S));
approx_quantile.AddFunction(GetApproxQuantileWidenedTimestamp(LogicalType::TIMESTAMP_MS));

// List variants
approx_quantile.AddFunction(GetApproxQuantileDecimalList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -547,16 +547,19 @@ AggregateFunction GetContinuousQuantileTemplated(const LogicalType &type) {
}
case LogicalTypeId::DATE: {
auto fun = OP::template GetFunction<date_t, timestamp_t>(type, LogicalType::TIMESTAMP);
fun.SetFallible(); // interpolation casts to TIMESTAMP, which throws for dates outside of the timestamp range
fun.SetFallible(); // the TIMESTAMP cast throws for out-of-range dates, interpolation for the infinities
return fun;
}
case LogicalTypeId::TIMESTAMP:
case LogicalTypeId::TIMESTAMP_TZ:
case LogicalTypeId::TIMESTAMP_TZ_NS:
case LogicalTypeId::TIMESTAMP_SEC:
case LogicalTypeId::TIMESTAMP_MS:
case LogicalTypeId::TIMESTAMP_NS:
return OP::template GetFunction<timestamp_t, timestamp_t>(type, type);
case LogicalTypeId::TIMESTAMP_NS: {
auto fun = OP::template GetFunction<timestamp_t, timestamp_t>(type, type);
fun.SetFallible(); // interpolation throws for the infinities
return fun;
}
case LogicalTypeId::TIME:
return OP::template GetFunction<dtime_t, dtime_t>(type, type);
case LogicalTypeId::TIME_TZ:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ double CheckReservoirQuantile(const Value &quantile_val) {
unique_ptr<FunctionData> BindReservoirQuantile(BindAggregateFunctionInput &input) {
Value quantile_val = input.GetConstant(1);
vector<double> quantiles;
if (quantile_val.type().id() != LogicalTypeId::LIST) {
// a NULL list is rejected like a NULL quantile
if (quantile_val.IsNull() || quantile_val.type().id() != LogicalTypeId::LIST) {
quantiles.push_back(CheckReservoirQuantile(quantile_val));
} else {
for (const auto &element_val : ListValue::GetChildren(quantile_val)) {
Expand Down
Loading
Loading