Skip to content

Commit 5a0dc91

Browse files
committed
Answer sum, avg and sumCount from per-part statistics
1 parent 3ade111 commit 5a0dc91

57 files changed

Lines changed: 616 additions & 119 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,7 @@ std::unordered_map<String, CHSetting> performanceSettings
639639
{"use_statistics", trueOrFalseSetting},
640640
{"use_statistics_for_min_max_aggregation", trueOrFalseSetting},
641641
{"use_statistics_for_part_pruning", trueOrFalseSetting},
642+
{"use_statistics_for_sum_avg_aggregation", trueOrFalseSetting},
642643
{"use_streaming_marks_compression", trueOrFalseSetting},
643644
{"use_top_k_dynamic_filtering", trueOrFalseSetting},
644645
{"use_top_k_dynamic_filtering_for_variable_length_types", trueOrFalseSetting}};

‎src/Core/Settings.cpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2193,13 +2193,27 @@ Answer `min`, `max` and `count` aggregations from per-part column statistics ins
21932193
When enabled, a query of the form `SELECT min(column), max(column), count() FROM table` without `GROUP BY` and filters
21942194
is answered from column statistics (e.g. MinMax statistics, see the `auto_statistics_types` MergeTree setting)
21952195
for the data parts that have them materialized, and only the remaining parts are read.
2196+
`count()` is also answered together with the aggregations of `use_statistics_for_sum_avg_aggregation`.
21962197

21972198
Possible values:
21982199

21992200
- 0 — Disabled.
22002201
- 1 — Enabled.
22012202
)", 0, \
22022203
{"26.9", false, true, "New setting to answer `min`, `max` and `count` aggregations without `GROUP BY` and filters from per-part column statistics for parts that have them materialized, reading only the remaining parts. previous_value=false so `compatibility` with versions before 26.9 keeps the optimization disabled and restores the pre-existing plan."}) \
2204+
DECLARE(Bool, use_statistics_for_sum_avg_aggregation, true, R"(
2205+
Answer `sum`, `avg` and `sumCount` aggregations over integer and `Decimal` columns that are not `Nullable` or
2206+
`LowCardinality`, without `GROUP BY` and filters, from per-part column statistics (the `basic` statistics type, see the
2207+
`auto_statistics_types` `MergeTree` setting) for the data parts that have them materialized, and read only the remaining
2208+
parts. `count(column)` of a column that is not `Nullable` or `LowCardinality` is answered there from the number of rows.
2209+
The result is exactly the same as when reading the data.
2210+
2211+
Possible values:
2212+
2213+
- 0 — Disabled.
2214+
- 1 — Enabled.
2215+
)", 0, \
2216+
{"26.10", false, true, "New setting to answer `sum`, `avg`, `sumCount` and `count(column)` aggregations without `GROUP BY` and filters from per-part column statistics. previous_value=false so `compatibility` with versions before 26.10 keeps the optimization disabled and restores the pre-existing plan."}) \
22032217
DECLARE(Bool, use_top_k_dynamic_filtering, true, R"(
22042218
Enable dynamic filtering optimization when executing a `ORDER BY <column> LIMIT n` query.
22052219

‎src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp‎

Lines changed: 141 additions & 51 deletions
Large diffs are not rendered by default.

‎src/Storages/MergeTree/IMergeTreeDataPart.cpp‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1453,26 +1453,45 @@ ColumnsStatistics IMergeTreeDataPart::loadStatistics(const Names & required_colu
14531453
return loadStatisticsWide(required_columns_set);
14541454
}
14551455

1456+
void IMergeTreeDataPart::cacheEstimates(const ColumnsStatistics & statistics, const Names & looked_up_columns) const
1457+
{
1458+
/// The callers load the transient raw statistics in the default arena; only the cache is long-lived
1459+
/// (kept on the part until reload), so build it in the dedicated arena, like the part's metadata.
1460+
ScopedJemallocThreadArena mergetree_arena_scope(JemallocMergeTreeArena::getArenaIndex());
1461+
for (const auto & [column_name, stats] : statistics)
1462+
estimates.try_emplace(column_name, stats->getEstimate());
1463+
estimates_loaded_columns.insert(looked_up_columns.begin(), looked_up_columns.end());
1464+
}
1465+
14561466
Estimates IMergeTreeDataPart::getEstimates() const
14571467
{
14581468
std::lock_guard lock(estimates_mutex);
14591469

1460-
if (estimates.has_value())
1461-
return *estimates;
1462-
1463-
/// The raw statistics are transient, so load them in the default arena; only the cached
1464-
/// estimates map is long-lived (kept on the part until reload), so build it in the dedicated
1465-
/// arena, like the rest of the part's metadata.
1466-
auto statistics = loadStatistics();
1467-
1470+
if (!all_estimates_loaded)
14681471
{
1469-
ScopedJemallocThreadArena mergetree_arena_scope(JemallocMergeTreeArena::getArenaIndex());
1470-
Estimates new_estimates;
1471-
for (const auto & [column_name, stats] : statistics)
1472-
new_estimates.emplace(column_name, stats->getEstimate());
1473-
estimates = std::move(new_estimates);
1472+
cacheEstimates(loadStatistics(), {});
1473+
all_estimates_loaded = true;
14741474
}
1475-
return *estimates;
1475+
return estimates;
1476+
}
1477+
1478+
Estimates IMergeTreeDataPart::getEstimates(const Names & columns) const
1479+
{
1480+
std::lock_guard lock(estimates_mutex);
1481+
1482+
Names columns_to_load;
1483+
for (const auto & column : columns)
1484+
if (!all_estimates_loaded && !estimates_loaded_columns.contains(column))
1485+
columns_to_load.push_back(column);
1486+
1487+
if (!columns_to_load.empty())
1488+
cacheEstimates(loadStatistics(columns_to_load), columns_to_load);
1489+
1490+
Estimates result;
1491+
for (const auto & column : columns)
1492+
if (auto it = estimates.find(column); it != estimates.end())
1493+
result.emplace(*it);
1494+
return result;
14761495
}
14771496

14781497
void IMergeTreeDataPart::setEstimates(const Estimates & new_estimates)
@@ -1489,6 +1508,7 @@ void IMergeTreeDataPart::setEstimates(const Estimates & new_estimates)
14891508

14901509
std::lock_guard lock(estimates_mutex);
14911510
estimates = std::move(stored_estimates);
1511+
all_estimates_loaded = true;
14921512
}
14931513

14941514
void IMergeTreeDataPart::loadColumnsChecksumsIndexes(bool require_columns_checksums, bool check_consistency, bool load_metadata_version)

‎src/Storages/MergeTree/IMergeTreeDataPart.h‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,8 @@ class IMergeTreeDataPart : public std::enable_shared_from_this<IMergeTreeDataPar
246246
ColumnsStatistics loadStatistics() const;
247247
ColumnsStatistics loadStatistics(const Names & required_columns) const;
248248
Estimates getEstimates() const;
249+
/// Loads the statistics only of those `columns` that were not looked up yet.
250+
Estimates getEstimates(const Names & columns) const;
249251
void setEstimates(const Estimates & new_estimates);
250252

251253
/// Initialize columns (from columns.txt if exists, or create from column files if not).
@@ -932,7 +934,11 @@ class IMergeTreeDataPart : public std::enable_shared_from_this<IMergeTreeDataPar
932934
/// Small state of finalized statistics for suitable statistics types.
933935
/// Lazily initialized on a first access.
934936
mutable std::mutex estimates_mutex;
935-
mutable std::optional<Estimates> estimates TSA_GUARDED_BY(estimates_mutex);
937+
mutable Estimates estimates TSA_GUARDED_BY(estimates_mutex);
938+
mutable bool all_estimates_loaded TSA_GUARDED_BY(estimates_mutex) = false;
939+
/// Also the columns without statistics, so that they are not looked up again.
940+
mutable NameSet estimates_loaded_columns TSA_GUARDED_BY(estimates_mutex);
941+
void cacheEstimates(const ColumnsStatistics & statistics, const Names & looked_up_columns) const TSA_REQUIRES(estimates_mutex);
936942

937943
/// Reads part unique identifier (if exists) from uuid.txt
938944
void loadUUID();

‎src/Storages/MergeTree/MergeTask.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -998,7 +998,8 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const
998998
{
999999
auto it = part_statistics.find(column_name);
10001000

1001-
if (it == part_statistics.end() || !column_stats->structureEquals(*it->second))
1001+
if (it == part_statistics.end() || !column_stats->structureEquals(*it->second)
1002+
|| (column_stats->hasSum() && !it->second->hasSum()))
10021003
global_ctx->statistics_to_build_by_part[part->name].emplace(column_name, column_stats->cloneEmpty());
10031004
else
10041005
column_stats->merge(it->second);

‎src/Storages/MergeTree/registerStorageMergeTree.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2582,7 +2582,8 @@ EXPLAIN indexes = 1 SELECT count() FROM test_stats WHERE value > 5000;
25822582
A compact bundle of single-value summaries derived from a column. Depending on the column type, the following pieces are populated:
25832583
- for any column: the number of rows equal to the type's default value (`0` for integers and floats, `''` for `String`, `[]` for `Array`, `NULL` for `Nullable`, etc.), which lets the optimizer estimate `col = <default>` predicates and `IS NULL` filters;
25842584
- for any column whose values are represented by a number (integers, floats, `Decimal*`, `Date*`, `DateTime*`, `Enum*`, `IPv4`, ...): the minimum and maximum value, which allow to estimate the selectivity of range filters and enable part pruning;
2585-
- for `String` and `FixedString` columns: the total byte length of non-`NULL` values (from which the average string length can be derived).
2585+
- for `String` and `FixedString` columns: the total byte length of non-`NULL` values (from which the average string length can be derived);
2586+
- for integer and `Decimal` columns that are not `Nullable` or `LowCardinality`: the exact sum of values, from which `sum`, `avg` and `sumCount` without `GROUP BY` and filters are answered (see the `use_statistics_for_sum_avg_aggregation` setting).
25862587
25872588
A single `basic` statistic can populate several of these at once — for example on a `Nullable(UInt32)` column it tracks both numeric min/max and the `NULL` count. Because a default-value count is defined for every column type, `basic` can be declared on any column, including composite types such as `Array`, `Tuple`, and `Map`.
25882589

‎src/Storages/Statistics/Statistics.cpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,12 @@ bool ColumnStatistics::hasMinMax() const
420420
return false;
421421
}
422422

423+
bool ColumnStatistics::hasSum() const
424+
{
425+
auto it = stats.find(StatisticsType::Basic);
426+
return it != stats.end() && assert_cast<const StatisticsBasic &>(*it->second).hasSum();
427+
}
428+
423429
UInt64 ColumnStatistics::getNullCount() const
424430
{
425431
if (auto it = stats.find(StatisticsType::Basic); it != stats.end())
@@ -495,6 +501,8 @@ Estimate ColumnStatistics::getEstimate() const
495501
info.estimated_null_count = basic_stats.getNullCount();
496502
if (basic_stats.hasDefaultCount())
497503
info.estimated_default_count = basic_stats.getDefaultCount();
504+
if (basic_stats.hasSum())
505+
info.estimated_sum = basic_stats.getSum();
498506
}
499507
else if (auto minmax_it = stats.find(StatisticsType::MinMax); minmax_it != stats.end())
500508
{
@@ -988,4 +996,9 @@ bool canStatisticsTrackMinMax(const DataTypePtr & data_type)
988996
return removeLowCardinalityAndNullable(removeNullable(data_type))->isValueRepresentedByNumber();
989997
}
990998

999+
bool canStatisticsTrackSum(const DataTypePtr & data_type)
1000+
{
1001+
return WhichDataType(data_type).isIntegerOrDecimal();
1002+
}
1003+
9911004
}

‎src/Storages/Statistics/Statistics.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ struct Estimate
119119
std::optional<Field> estimated_max;
120120
std::optional<UInt64> estimated_null_count;
121121
std::optional<UInt64> estimated_default_count;
122+
std::optional<Field> estimated_sum;
122123
};
123124

124125
using Estimates = std::unordered_map<String, Estimate>;
@@ -147,6 +148,7 @@ class ColumnStatistics
147148
/// True iff loaded statistics include a source of numeric min/max values
148149
/// (`MinMax`, or `Basic` on a numeric/temporal column).
149150
bool hasMinMax() const;
151+
bool hasSum() const;
150152
/// True iff `estimateCardinality` is backed by a uniq sketch. When it is not, that method returns a
151153
/// fixed fraction of the row count, which callers dividing by the cardinality must not mistake for
152154
/// a measurement.
@@ -246,5 +248,8 @@ void addImplicitStatistics(ColumnsDescription & columns, const String & statisti
246248
/// (`StatisticsBasic::hasNumericMinMax`).
247249
bool canStatisticsTrackMinMax(const DataTypePtr & data_type);
248250

251+
/// Whether `basic` statistics record the sum of a column of this type (integers and `Decimal`, exact in any order).
252+
bool canStatisticsTrackSum(const DataTypePtr & data_type);
253+
249254

250255
}

‎src/Storages/Statistics/StatisticsBasic.cpp‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
#include <Storages/Statistics/StatisticsBasic.h>
22

3+
#include <Columns/ColumnDecimal.h>
34
#include <Columns/ColumnFixedString.h>
45
#include <Columns/ColumnNullable.h>
6+
#include <Columns/ColumnSparse.h>
57
#include <Columns/ColumnString.h>
8+
#include <Columns/ColumnsNumber.h>
9+
#include <Core/callOnTypeIndex.h>
610
#include <DataTypes/DataTypeFactory.h>
711
#include <DataTypes/DataTypeLowCardinality.h>
812
#include <DataTypes/DataTypeNullable.h>
13+
#include <DataTypes/DataTypesDecimal.h>
14+
#include <DataTypes/DataTypesNumber.h>
915
#include <DataTypes/IDataType.h>
1016
#include <Interpreters/convertFieldToType.h>
1117
#include <IO/ReadHelpers.h>
1218
#include <IO/WriteHelpers.h>
19+
#include <Common/FieldVisitorSum.h>
1320
#include <Common/FieldVisitorToString.h>
1421

1522

@@ -32,6 +39,7 @@ enum BasicFeatureMask : UInt8
3239
NumericMinMax = 1u << 0,
3340
StringLengthSum = 1u << 1,
3441
DefaultCount = 1u << 2,
42+
ExactSum = 1u << 3,
3543
};
3644

3745
const NullMap * tryGetNullMap(const IColumn & column)
@@ -71,6 +79,40 @@ UInt64 sumNonNullStringBytes(const ColumnPtr & column)
7179
return 0;
7280
}
7381

82+
/// Sums like the `sum` aggregate function: in its accumulator type and with its wraparound, which
83+
/// unsigned and `wide::integer` arithmetic give without undefined behavior.
84+
Field sumValues(const IColumn & column, const IDataType & type)
85+
{
86+
Field result;
87+
callOnIndexAndDataType<void>(type.getTypeId(), [&](const auto & types)
88+
{
89+
using DataType = typename std::decay_t<decltype(types)>::LeftType;
90+
if constexpr (IsDataTypeDecimal<DataType>)
91+
{
92+
using T = typename DataType::FieldType;
93+
using Accumulator = std::conditional_t<std::is_same_v<T, Decimal256>, Decimal256, Decimal128>;
94+
typename Accumulator::NativeType accumulated = 0;
95+
for (const auto & value : assert_cast<const ColumnDecimal<T> &>(column).getData())
96+
accumulated += value.value;
97+
result = DecimalField<Accumulator>(accumulated, getDecimalScale(type));
98+
}
99+
else if constexpr (IsDataTypeNumber<DataType>)
100+
{
101+
using T = typename DataType::FieldType;
102+
if constexpr (is_integer<T>)
103+
{
104+
using Accumulator = std::conditional_t<sizeof(T) <= sizeof(UInt64), UInt64, T>;
105+
Accumulator accumulated = 0;
106+
for (const auto value : assert_cast<const ColumnVector<T> &>(column).getData())
107+
accumulated += static_cast<Accumulator>(value);
108+
result = static_cast<NearestFieldType<T>>(accumulated);
109+
}
110+
}
111+
return true;
112+
});
113+
return result;
114+
}
115+
74116
}
75117

76118

@@ -88,6 +130,10 @@ StatisticsBasic::StatisticsBasic(const SingleStatisticsDescription & description
88130
column_default_field = (*default_col)[0];
89131

90132
is_nullable = isNullableOrLowCardinalityNullable(data_type_) || column_default_field.isNull();
133+
134+
has_sum = canStatisticsTrackSum(data_type_);
135+
if (has_sum)
136+
sum = sumValues(*data_type->createColumn(), *data_type);
91137
}
92138

93139
void StatisticsBasic::build(const ColumnPtr & column)
@@ -114,6 +160,15 @@ void StatisticsBasic::build(const ColumnPtr & column)
114160
if (tracks_string)
115161
string_total_bytes += sumNonNullStringBytes(column);
116162

163+
if (has_sum)
164+
{
165+
auto values = column->convertToFullColumnIfConst();
166+
/// A sparse column omits only zeros from its values.
167+
if (const auto * sparse = typeid_cast<const ColumnSparse *>(values.get()))
168+
values = sparse->getValuesPtr();
169+
applyVisitor(FieldVisitorSum(sumValues(*values, *data_type)), sum);
170+
}
171+
117172
row_count += column_size;
118173
}
119174

@@ -136,6 +191,11 @@ void StatisticsBasic::merge(const StatisticsPtr & other_stats)
136191
default_count += other->default_count;
137192
}
138193

194+
if (has_sum && other->has_sum)
195+
applyVisitor(FieldVisitorSum(other->sum), sum);
196+
else
197+
has_sum = false;
198+
139199
row_count += other->row_count;
140200
}
141201

@@ -150,6 +210,9 @@ void StatisticsBasic::serialize(WriteBuffer & buf)
150210
mask |= BasicFeatureMask::StringLengthSum;
151211

152212
mask |= BasicFeatureMask::DefaultCount;
213+
/// Not written for a sum that a loaded blob lacks, so that a mutation re-serializing it does not invent one.
214+
if (has_sum)
215+
mask |= BasicFeatureMask::ExactSum;
153216
writeIntBinary(mask, buf);
154217

155218
if (tracks_numeric)
@@ -161,6 +224,9 @@ void StatisticsBasic::serialize(WriteBuffer & buf)
161224
writeIntBinary(string_total_bytes, buf);
162225

163226
writeIntBinary(default_count, buf);
227+
228+
if (has_sum)
229+
writeFieldBinary(sum, buf);
164230
}
165231

166232
void StatisticsBasic::deserialize(ReadBuffer & buf, StatisticsFileVersion /*version*/)
@@ -184,6 +250,14 @@ void StatisticsBasic::deserialize(ReadBuffer & buf, StatisticsFileVersion /*vers
184250
has_default_count = (mask & BasicFeatureMask::DefaultCount) != 0;
185251
if (has_default_count)
186252
readIntBinary(default_count, buf);
253+
254+
Field stored_sum;
255+
if (mask & BasicFeatureMask::ExactSum)
256+
stored_sum = readFieldBinary(buf);
257+
/// A missing sum, or one of an unexpected type, is not used, and the next merge of the part rebuilds it.
258+
has_sum = has_sum && stored_sum.getType() == sum.getType();
259+
if (has_sum)
260+
sum = stored_sum;
187261
}
188262

189263
std::optional<Float64> StatisticsBasic::estimateLess(const Field & val) const

0 commit comments

Comments
 (0)