github-actions[bot] commented on code in PR #71004:
URL: https://github.com/apache/doris/pull/71004#discussion_r4690691157
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/DropStatsCommand.java:
##########
@@ -127,16 +134,38 @@ public void validate(ConnectContext ctx) throws
UserException {
throw new UserException("Can't delete more that " +
MAX_IN_ELEMENT_TO_DELETE + " columns at one time.");
}
isAllColumns = false;
+ boolean escapeVariantDots = table instanceof OlapTable olap &&
olap.getVariantEscapeDotsInKeys();
+ LinkedHashSet<String> resolved = new LinkedHashSet<>();
for (String cName : columnNames) {
- if (table.getColumn(cName) == null) {
+ Column col = table.getColumn(cName);
+ if (col != null) {
+ if (StatisticsUtil.isUnsupportedType(col.getType())) {
+ List<SubcolumnStatisticsUtil.SubcolumnDescriptor>
subcolumns =
+ SubcolumnStatisticsUtil.discoverForColumn(col,
escapeVariantDots);
Review Comment:
[P2] Filter physical-name collisions when expanding a complex root
With `s STRUCT<age:INT>` and an independent physical column named `s.age`,
collection deliberately suppresses the synthetic leaf and stores `s.age`
statistics for the physical column. `discoverForColumn` uses an empty
physical-name set, so `DROP STATS t(s)` expands to that same ID and deletes the
unrelated physical column's persisted and cached statistics. `SHOW COLUMN STATS
t(s)` has the same selection error. Expand roots using the collision-filtered
table/index descriptors used by ANALYZE.
##########
fe/fe-core/src/main/java/org/apache/doris/statistics/util/SubcolumnStatisticsUtil.java:
##########
@@ -0,0 +1,378 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.statistics.util;
+
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.MaterializedIndexMeta;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PatternType;
+import org.apache.doris.catalog.StructField;
+import org.apache.doris.catalog.StructType;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.catalog.VariantField;
+import org.apache.doris.catalog.VariantType;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.util.PropertyAnalyzer;
+import org.apache.doris.common.util.SqlUtils;
+
+import com.google.common.base.Preconditions;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+/**
+ * Discovers and resolves scalar leaf subcolumns declared on {@link
VariantType} (exact predefined
+ * fields) and {@link StructType} columns for statistics collection,
persistence, and CBO lookup.
+ */
+public final class SubcolumnStatisticsUtil {
+
+ public static final int MAX_STRUCT_NESTING_DEPTH = 4;
+ public static final int MAX_SUBCOLUMNS_PER_ROOT = 64;
+
+ public record SubcolumnDescriptor(
+ String colId,
+ Column rootColumn,
+ List<String> subPath,
+ Type leafType,
+ Column syntheticColumn,
+ String sqlExpr) {
+ }
+
+ private SubcolumnStatisticsUtil() {
+ }
+
+ /**
+ * Formats the canonical statistics {@code col_id} for a subcolumn path
under {@code rootColumnName}.
+ * Uses {@link PropertyAnalyzer#encodeVariantPathComponent(String)} so
literal {@code '.'} and {@code '%'}
+ * inside path segments never collide with path separators and never
introduce SQL quotes or backslashes.
+ */
+ public static String formatSubcolumnId(String rootColumnName, List<String>
subPath) {
+ Preconditions.checkArgument(rootColumnName != null &&
!rootColumnName.isEmpty(),
+ "rootColumnName must not be empty");
+ Preconditions.checkArgument(subPath != null && !subPath.isEmpty(),
+ "subPath must not be empty");
+ return rootColumnName + "." + subPath.stream()
Review Comment:
[P2] Disambiguate dotted root names in canonical subcolumn IDs
Doris permits dots in physical column names, so a table can contain both a
column named `a.b` of type `STRUCT<c:INT>` and `a STRUCT<b:STRUCT<c:INT>>`.
This returns `a.b.c` for both leaves because only the path components are
escaped. `discoverFromColumns` then drops one descriptor via `putIfAbsent`, and
`StatsCalculator.statsColumnKey` makes both accesses request the same
NDV/bounds. Encode or otherwise delimit the root component consistently in
discovery and lookup, and cover two complex roots whose IDs would collide.
##########
fe/fe-core/src/main/java/org/apache/doris/statistics/analysis/BaseAnalysisTask.java:
##########
@@ -258,7 +247,9 @@ public enum AnalyzeSampleAlgorithm {
+ "'${colId}' AS `col_id`, "
+ "NULL AS `part_id`, "
+ "SUM(count) AS `row_count`, "
- + "HLL_CARDINALITY(HLL_UNION(ndv)) AS `ndv`, "
+ + "IF(IFNULL(SUM(unseen_ndv), 0) = 0,
HLL_CARDINALITY(HLL_UNION(ndv)), "
+ + "LEAST(GREATEST(0, IFNULL(SUM(count) - SUM(null_count), 0)), "
+ + "HLL_CARDINALITY(HLL_UNION(ndv)) + IFNULL(SUM(unseen_ndv), 0)))
AS `ndv`, "
Review Comment:
[P2] Account for overlap when merging unseen partition NDV
Consider a DUP table with 100 partitions, each containing the same 10,000
distinct values of an ordinary column. With partition analysis enabled, a first
ANALYZE with a 100,000-row total sample budget samples roughly 1,000 rows per
partition. Each all-singleton sample estimates 10,000 NDV and stores about
9,000 unseen values. This merge deduplicates only the observed HLLs, then adds
about 900,000 unseen values even though the global domain is just 10,000;
clamping to the million non-null rows does not help. Use a merge estimator that
handles cross-partition overlap, and update `PartitionColumnStatisticBuilder`'s
parallel sum as well.
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/stats/ExpressionEstimation.java:
##########
@@ -305,6 +332,97 @@ public ColumnStatistic visitSlotReference(SlotReference
slotReference, Statistic
return columnStatistic;
}
+ @Override
+ public ColumnStatistic visitElementAt(ElementAt elementAt, Statistics
context) {
+ ColumnStatistic direct = context.findColumnStatistics(elementAt);
+ if (direct != null) {
+ return direct;
+ }
+ List<String> reversedSegments = new ArrayList<>();
+ Expression cur = elementAt;
+ while (cur instanceof ElementAt elem) {
+ Expression container = elem.child(0);
+ Expression selector = elem.child(1);
+ DataType containerType = container.getDataType();
+ if (containerType instanceof StructType structType) {
+ if (selector instanceof StringLikeLiteral strLit) {
+ StructField field =
structType.getField(strLit.getStringValue());
+ if (field == null) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ reversedSegments.add(field.getName());
+ } else if (selector instanceof IntegerLikeLiteral intLit) {
+ StructField field =
structType.getFieldByOrdinal(intLit.getBigDecimalValue());
+ if (field == null) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ reversedSegments.add(field.getName());
+ } else {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ } else if (containerType instanceof VariantType && selector
instanceof StringLikeLiteral strLit) {
+ String seg = strLit.getStringValue();
+ if (seg.isEmpty()) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ reversedSegments.add(seg);
+ } else {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ cur = container;
+ }
+ if (!(cur instanceof SlotReference baseSlot) ||
reversedSegments.isEmpty()) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ Collections.reverse(reversedSegments);
+ List<String> fullPath = new ArrayList<>(baseSlot.getSubPath().size() +
reversedSegments.size());
+ fullPath.addAll(baseSlot.getSubPath());
+ fullPath.addAll(reversedSegments);
+
+ for (Map.Entry<Expression, ColumnStatistic> entry :
context.columnStatistics().entrySet()) {
+ if (entry.getKey() instanceof SlotReference candidate
+ && candidate.getSubPath().equals(fullPath)
+ && Objects.equals(candidate.getOriginalTable(),
baseSlot.getOriginalTable())
+ && Objects.equals(candidate.getOriginalColumn(),
baseSlot.getOriginalColumn())) {
+ return entry.getValue();
+ }
+ }
+ if (baseSlot.getOriginalTable().isEmpty()) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ ConnectContext ctx = ConnectContext.get();
+ if (ctx != null && (ctx.getState().isPlanWithUnKnownColumnStats()
+ || !ctx.getSessionVariable().enableStats)) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ TableIf table = baseSlot.getOriginalTable().get();
+ if (StatisticConstants.isSystemTable(table) || table.getDatabase() ==
null
+ || table.getDatabase().getCatalog() == null) {
+ return
ColumnStatistic.createUnknownByDataType(elementAt.getDataType());
+ }
+ String rootName =
baseSlot.getOriginalColumn().map(Column::getName).orElse(baseSlot.getName());
+ String candidateColId =
SubcolumnStatisticsUtil.formatSubcolumnId(rootName, fullPath);
+ String colId = SubcolumnStatisticsUtil.resolveAnyIndex(table,
candidateColId)
+ .map(SubcolumnStatisticsUtil.SubcolumnDescriptor::colId)
+ .orElse(candidateColId);
Review Comment:
[P2] Keep colliding physical-column statistics out of subcolumn lookup
For a legal schema with `s STRUCT<age:INT>` and physical `s.age BIGINT`, the
reduced plan is:
```text
Filter(element_at(s, 'age') = 10)
Scan(t: s, `s.age`)
```
`resolveAnyIndex` intentionally returns empty because the physical column
wins, but this fallback still fetches its `s.age` statistics. Physical bounds
1000..2000 can therefore make the STRUCT predicate estimate zero despite leaf
values 10..20. Require a valid subcolumn descriptor before consuming the cache
entry, and apply the same protection to `StatsCalculator.statsColumnKey` for
pruned VARIANT slots.
##########
fe/fe-core/src/main/java/org/apache/doris/catalog/InternalSchemaInitializer.java:
##########
@@ -114,9 +114,15 @@ public void run() {
}
public void modifyColumnStatsTblSchema() {
+ modifyStatsTblSchema(StatisticConstants.TABLE_STATISTIC_TBL_NAME);
+ modifyStatsTblSchema(StatisticConstants.PARTITION_STATISTIC_TBL_NAME);
Review Comment:
[P2] Gate the partition schema migration for mixed FE versions
During a rolling FE upgrade, an upgraded master now adds `unseen_ndv` as the
fifteenth visible column. If an older FE subsequently becomes master, its
`BaseAnalysisTask.doPartitionTable` still emits a bare `INSERT INTO
partition_statistics SELECT ...` with fourteen outputs. The old `BindSink`
binds every visible target column when no column list is supplied, then rejects
this width mismatch, so partition ANALYZE stops working. A nullable trailing
column does not fix positional INSERT binding. Preserve compatibility until
older FEs can no longer become master, or stage the column-list compatibility
change before this migration.
##########
fe/fe-core/src/main/java/org/apache/doris/statistics/sampling/HierarchicalFixedBudgetTabletSamplingMethod.java:
##########
@@ -0,0 +1,323 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.statistics.sampling;
+
+import org.apache.doris.analysis.FixedBlockSampleSpec;
+import org.apache.doris.statistics.analysis.AnalyzeSkipException;
+import
org.apache.doris.statistics.sampling.TabletSampleSpec.EqualProbabilitySamplingSemantics;
+import
org.apache.doris.statistics.sampling.TabletSampleSpec.FixedBlockScanClause;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Three-stage sample with a common unconditional inclusion probability for
every physical block. */
+public final class HierarchicalFixedBudgetTabletSamplingMethod implements
TabletSamplingMethod {
+ private final FixedBlockSampleSpec.Mode mode;
+ private final boolean crossTabletDuplicates;
+
+ public HierarchicalFixedBudgetTabletSamplingMethod() {
+ this(FixedBlockSampleSpec.Mode.FIXED_BLOCK, false);
+ }
+
+ public
HierarchicalFixedBudgetTabletSamplingMethod(FixedBlockSampleSpec.Mode mode) {
+ this(mode, false);
+ }
+
+ public
HierarchicalFixedBudgetTabletSamplingMethod(FixedBlockSampleSpec.Mode mode,
+ boolean crossTabletDuplicates) {
+ this.mode = mode;
+ this.crossTabletDuplicates = crossTabletDuplicates;
+ }
+
+ private static final long PARTITION = 0x706172746974696fL;
+ private static final long ROUNDING = 0x726f756e64696e67L;
+ private static final long TABLET = 0x7461626c6574L;
+
+ @Override
+ public TabletSampleSpec build(TabletSamplingRequest request) {
+ SamplingBudget budget = request.budget();
+ List<PartitionSampleMeta> partitions = request.scope().partitions();
+ long k = 1 + (budget.targetRows() - 1) / budget.unitRows();
+ Population population = Population.of(partitions, budget.unitRows());
+ if (population.isCensus(budget.targetRows(), budget.unitRows())) {
+ return TabletSampleSpec.fullScan();
+ }
+ long min = population.min();
+ long max = population.max();
+ int tiers = max <= 4.0 * min ? 1 : Math.min(3,
budget.maxSampleGroups());
+ double step = Math.pow((double) max / min, 1.0 / tiers);
+ double[] boundaries = new double[tiers - 1];
+ for (int h = 0; h < boundaries.length; h++) {
+ boundaries[h] = min * Math.pow(step, h + 1);
+ }
+ int[] counts = new int[tiers];
+ double[] weights = new double[tiers];
+ long[] largest = new long[tiers];
+ long[] largestRows = new long[tiers];
+ List<Cell[]> cells = new ArrayList<>();
+ for (PartitionSampleMeta part : partitions) {
+ Cell[] strata = new Cell[tiers];
+ Arrays.setAll(strata, i -> new Cell());
+ for (TabletSampleMeta t : part.tablets()) {
+ long b = t.blocks(budget.unitRows());
+ int h = 0;
+ while (h < boundaries.length && b >= boundaries[h]) {
+ h++;
+ }
+ strata[h].ids.add(t.id());
+ counts[h]++;
+ weights[h] += b;
+ largest[h] = Math.max(largest[h], b);
+ largestRows[h] = Math.max(largestRows[h], t.estimatedRows());
+ }
+ cells.add(strata);
+ }
+ int cap = Math.min(budget.maxSelectedTablets(),
+
SampledScanSqlRenderer.tabletCapacity(budget.maxInternalSqlBytes(), tiers,
mode));
+ if (cap < 1) {
+ throw new AnalyzeSkipException("Fixed-block SQL budget cannot fit
one tablet");
+ }
+ long tabletCount = Arrays.stream(counts).asLongStream().sum();
+ int divisor = request.layout().key() || request.layout().partition()
|| request.layout().distribution()
+ ? 16 : 32;
+ long minSeats = crossTabletDuplicates ? Math.min(8L, tabletCount) : 1L;
+ int seats = (int) Math.min(cap, Math.max(minSeats, k / divisor));
+ int m = Math.min(partitions.size(), seats);
+ double alpha = (double) m / partitions.size();
+ // Even if every selected tablet reads all its blocks, equal marginals
need at least
+ // q * tabletCount seats. Reduce q before water-filling if the nominal
target is infeasible.
+ double q = Math.min(Math.min(alpha, k / population.blocks()), (double)
seats / tabletCount);
+ double[] beta = allocate(counts, weights, seats / alpha, q / alpha);
+
+ // Any common offset u < 1 gives floor(worst + u) <= cap when worst <=
cap.
+ // Evaluate the bound in the same exact units used to draw, before
consulting the seed.
+ BigInteger[] rates =
Arrays.stream(beta).mapToObj(SystematicRounding::units).toArray(BigInteger[]::new);
+ BigInteger limit =
SystematicRounding.units(1.0).multiply(BigInteger.valueOf(cap));
+ BigInteger worst = worstCost(cells, m, rates);
+ if (worst.compareTo(limit) > 0) {
+ q = SystematicRounding.scaleDown(SystematicRounding.units(q),
limit, worst);
+ for (int h = 0; h < tiers; h++) {
+ beta[h] = SystematicRounding.scaleDown(rates[h], limit, worst);
+ rates[h] = SystematicRounding.units(beta[h]);
+ }
+ }
+ // Division when computing the water-filling floor can round down,
even without budget scaling.
+ for (int h = 0; h < tiers; h++) {
+ if (counts[h] > 0) {
+ q = Math.min(q, alpha * beta[h]);
+ }
+ }
+ return draw(request, partitions, cells, m, alpha, beta, weights,
rates, q, largest, largestRows,
+ population.rows());
+ }
+
+ public record Population(long min, long max, double rows, double blocks,
boolean imputed) {
+ public static Population of(List<PartitionSampleMeta> partitions, long
unitRows) {
+ long min = Long.MAX_VALUE;
+ long max = 0;
+ double blocks = 0;
+ double rows = 0;
+ boolean imputed = false;
+ for (PartitionSampleMeta part : partitions) {
+ for (TabletSampleMeta t : part.tablets()) {
+ long b = t.blocks(unitRows);
+ min = Math.min(min, b);
+ max = Math.max(max, b);
+ blocks += b;
+ rows += t.estimatedRows();
+ imputed |= t.imputed();
+ }
+ }
+ return new Population(min, max, rows, blocks, imputed);
+ }
+
+ public boolean isCensus(long targetRows, long unitRows) {
+ return !imputed && (rows <= targetRows || 1 + (targetRows - 1) /
unitRows >= blocks);
+ }
+ }
+
+ private static BigInteger worstCost(List<Cell[]> cells, int m,
BigInteger[] rates) {
+ return cells.stream().map(strata -> {
+ BigInteger cost = BigInteger.ZERO;
+ for (int h = 0; h < strata.length; h++) {
+ cost =
cost.add(rates[h].multiply(BigInteger.valueOf(strata[h].ids.size())));
+ }
+ return cost;
+ }).sorted(Comparator.reverseOrder()).limit(m).reduce(BigInteger.ZERO,
BigInteger::add);
+ }
+
+ // Allocate in proportion to block mass, capping saturated cohorts and
redistributing their surplus.
+ // The lower bound makes the subsequent conditional block probability
realizable.
+ private static double[] allocate(int[] counts, double[] weights, double
seats, double floor) {
+ double[] rates = new double[counts.length];
+ double hi = 0;
+ for (int h = 0; h < counts.length; h++) {
+ if (counts[h] > 0) {
+ hi = Math.max(hi, counts[h] / weights[h]);
+ }
+ }
+ double lo = 0;
+ for (int i = 0; i < 64; i++) {
+ double lambda = (lo + hi) / 2;
+ double total = 0;
+ for (int h = 0; h < counts.length; h++) {
+ rates[h] = counts[h] == 0 ? 0 : Math.max(floor, Math.min(1,
lambda * weights[h] / counts[h]));
+ total += counts[h] * rates[h];
+ }
+ if (total > seats) {
+ hi = lambda;
+ } else {
+ lo = lambda;
+ }
+ }
+ return rates;
+ }
+
+ private TabletSampleSpec draw(TabletSamplingRequest request,
List<PartitionSampleMeta> partitions,
+ List<Cell[]> cells, int m, double alpha, double[] beta, double[]
weights, BigInteger[] rates,
+ double q, long[] largest, long[] largestRows, double
populationRows) {
+ long seed = request.seed();
+ List<Integer> order = new ArrayList<>();
+ for (int j = 0; j < partitions.size(); j++) {
+ order.add(j);
+ }
+ order.sort(Comparator.comparingLong(j -> hash(seed, PARTITION,
partitions.get(j).id())));
+ order = order.subList(0, m);
+ order.sort(Comparator.comparingLong(j -> partitions.get(j).id()));
+ List<List<Long>> selected = new ArrayList<>();
+ for (int h = 0; h < beta.length; h++) {
+ selected.add(new ArrayList<>());
+ }
+ SystematicRounding rounding = new SystematicRounding(hash(seed,
ROUNDING, 0));
+ for (int j : order) {
+ for (int h = 0; h < beta.length; h++) {
+ List<Long> ids = cells.get(j)[h].ids;
+ int take = rounding.take(ids.size(), rates[h]);
+ if (take > 0) {
+ ids.sort(Comparator.comparingLong(id -> hash(seed, TABLET,
id)));
+ selected.get(h).addAll(ids.subList(0, take));
+ }
+ }
+ }
+ int selectedTablets = selected.stream().mapToInt(List::size).sum();
+ long effectiveUnitRows = request.budget().unitRows();
+ if (mode == FixedBlockSampleSpec.Mode.KEY_RANGE_BLOCK &&
selectedTablets > 0) {
+ // Coalesce narrow key units into at most ~32 stratified
contiguous spans per selected
+ // tablet so overlapping segments do not decompress separate 64 KB
pages for hundreds of cuts.
+ double expectedRowsPerTablet = (q * populationRows) /
selectedTablets;
+ long minUnitByTarget = Math.max(1L, (long)
Math.ceil(expectedRowsPerTablet / 32.0));
+ effectiveUnitRows = Math.max(effectiveUnitRows, minUnitByTarget);
+ }
+ Map<GroupRates, List<Long>> combined = new LinkedHashMap<>();
+ for (int h = 0; h < beta.length; h++) {
+ if (!selected.get(h).isEmpty()) {
+ double pi = alpha * beta[h];
+ double p = q / pi;
+ long maxBlocks = effectiveUnitRows ==
request.budget().unitRows()
+ ? largest[h]
+ : (1L + (Math.max(1L, largestRows[h]) - 1L) /
effectiveUnitRows);
+ // BE rounds per segment. Allow for segment tails and delayed
tablet reports.
+ long safetyCap = (long) Math.ceil(2 * p * maxBlocks + 64);
Review Comment:
[P2] Account for per-segment tails in the sampling cap
This bounds `ceil(tabletRows / unitRows)`, but `FixedRowIdBlockSampler`
counts `sum(ceil(segmentRows / unitRows))`. One accurately reported 10,000-row
DUP tablet containing 1,000 uncompacted ten-row segments, sampled with `WITH
SAMPLE ROWS 100` and the default unit size 1,024, produces about `p=0.1` and a
cap of 66 here. BE instead has 1,000 units and selects about 100, so it returns
`INVALID_ARGUMENT` and ANALYZE fails; batch fallback repeats the same failure.
The fixed 64-unit allowance cannot bound normal segment tails. Use a cap/design
that accounts for the actual unit population, including the analogous RANDOM
sampling caps.
##########
be/src/storage/sampling/key_range_block_sampler.cpp:
##########
@@ -0,0 +1,533 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "storage/sampling/key_range_block_sampler.h"
+
+#include <algorithm>
+#include <map>
+#include <numeric>
+#include <optional>
+#include <queue>
+#include <random>
+
+#include "common/check.h"
+#include "common/status.h"
+#include "storage/index/short_key_index.h"
+#include "storage/sampling/dependent_rounding.h"
+#include "storage/sampling/tablet_sample_plan.h"
+#include "storage/segment/segment_key_seeker.h"
+
+namespace doris {
+namespace {
+constexpr size_t kMaxSubdivisionHeads = 16;
+constexpr size_t kMaxTotalSubdivisionProbes = 16384;
+
+struct BlockHead {
+ const SampleSegment* segment;
+ size_t seg_idx;
+ uint32_t block;
+ uint32_t start;
+ uint32_t end;
+ bool advance_next_block;
+ std::optional<std::string> custom_prefix;
+
+ const ShortKeyIndexDecoder& index() const { return segment->keys->index();
}
+ Slice prefix() const {
+ return custom_prefix.has_value() ? Slice(*custom_prefix)
+ : segment->keys->index_prefix(block);
+ }
+ uint32_t weight() const { return end - start; }
+};
+
+using CutKey = std::pair<std::string, std::vector<std::string>>;
+
+struct SubdivisionState {
+ uint64_t unit_rows = 0;
+ uint64_t remaining_rows = 0;
+ size_t probes_left = kMaxTotalSubdivisionProbes;
+ size_t bytes_left = 8 * 1024 * 1024;
+ uint64_t accumulated = 0;
+ std::vector<KeyRangeBound>* cuts = nullptr;
+};
+
+uint64_t carry_residual(uint64_t accumulated, uint64_t unit_rows) {
+ return accumulated < 2 * unit_rows ? accumulated - unit_rows : 0;
+}
+
+// Coalesce sequential blocks of the same segment that share `prefix` into one
contiguous span
+// so stride probing covers that segment's entire prefix range rather than
only its first block.
+std::vector<BlockHead> merge_same_segment_heads(std::vector<BlockHead> probes)
{
+ std::ranges::sort(probes, [](const BlockHead& lhs, const BlockHead& rhs) {
+ if (lhs.seg_idx != rhs.seg_idx) {
+ return lhs.seg_idx < rhs.seg_idx;
+ }
+ return lhs.start < rhs.start;
+ });
+ std::vector<BlockHead> merged;
+ merged.reserve(probes.size());
+ for (auto& head : probes) {
+ if (!merged.empty() && merged.back().seg_idx == head.seg_idx &&
+ merged.back().end == head.start) {
+ merged.back().end = head.end;
+ merged.back().block = std::max(merged.back().block, head.block);
+ } else {
+ merged.push_back(std::move(head));
+ }
+ }
+ return merged;
+}
+
+// Cumulative-weight midpoint selection picks up to kMaxSubdivisionHeads spans
proportionally to
+// row weight while spanning sequential equal-sized segments across the entire
key range.
+std::vector<size_t> select_active_heads(const std::vector<BlockHead>& spans,
+ uint64_t total_weight) {
+ if (spans.size() <= kMaxSubdivisionHeads || total_weight == 0) {
+ std::vector<size_t> all(spans.size());
+ std::iota(all.begin(), all.end(), 0);
+ return all;
+ }
+ std::vector<uint64_t> cum_end(spans.size());
+ uint64_t running = 0;
+ for (size_t i = 0; i < spans.size(); ++i) {
+ running += spans[i].weight();
+ cum_end[i] = running;
+ }
+ std::vector<size_t> selected;
+ selected.reserve(kMaxSubdivisionHeads);
+ for (size_t j = 0; j < kMaxSubdivisionHeads; ++j) {
+ const auto target =
+ static_cast<uint64_t>((static_cast<unsigned __int128>(2 * j +
1) * total_weight) /
+ (2 * kMaxSubdivisionHeads));
+ auto it = std::ranges::upper_bound(cum_end, target);
+ const size_t idx =
+ it == cum_end.end() ? spans.size() - 1 :
static_cast<size_t>(it - cum_end.begin());
+ if (selected.empty() || selected.back() != idx) {
+ selected.push_back(idx);
+ }
+ }
+ return selected;
+}
+
+Status probe_selected_spans(const std::vector<BlockHead>& spans,
+ const std::vector<size_t>& selected_indices,
+ uint64_t sampled_head_weight, uint64_t
desired_probes,
+ size_t run_probe_budget, const
std::optional<std::string>& upper_prefix,
+ SubdivisionState* state, std::map<CutKey,
uint64_t>* tuples,
+ uint64_t* in_range_sampled_rows, uint64_t*
deferred_sampled_rows,
+ size_t* used_probes, size_t* used_bytes, bool*
budget_exceeded,
+ std::vector<BlockHead>* continuations) {
+ for (size_t sel_pos = 0; sel_pos < selected_indices.size(); ++sel_pos) {
+ const auto& head = spans[selected_indices[sel_pos]];
+ const uint64_t w = head.weight();
+ const uint64_t span_probes = std::max<uint64_t>(
+ 1, (desired_probes * w + sampled_head_weight - 1) /
sampled_head_weight);
+ const uint32_t step =
+ std::max<uint32_t>(1, static_cast<uint32_t>((w + span_probes -
1) / span_probes));
+ const auto phase =
static_cast<uint32_t>((static_cast<uint64_t>(sel_pos) * step) /
+ selected_indices.size());
+ bool first_slice = phase > 0;
+ for (uint32_t row = head.start; row < head.end;) {
+ if (*used_probes >= run_probe_budget) {
+ *budget_exceeded = true;
+ return Status::OK();
+ }
+ std::string row_prefix;
+ std::vector<std::string> key;
+ size_t bytes = 0;
+ RETURN_IF_ERROR(head.segment->keys->read_key(row, &row_prefix,
&key, &bytes));
+ ++(*used_probes);
+ bytes += row_prefix.size();
+ if (*used_bytes + bytes > state->bytes_left) {
+ *budget_exceeded = true;
+ return Status::OK();
+ }
+ *used_bytes += bytes;
+ if (upper_prefix.has_value() && row_prefix >= *upper_prefix) {
+ *deferred_sampled_rows += head.end - row;
+ continuations->push_back({head.segment, head.seg_idx,
head.block, row, head.end,
+ false, std::move(row_prefix)});
+ break;
+ }
+ const uint32_t target_step = first_slice ? phase : step;
+ first_slice = false;
+ const uint32_t slice_rows = std::min(target_step, head.end - row);
+ *in_range_sampled_rows += slice_rows;
+ (*tuples)[{std::move(row_prefix), std::move(key)}] += slice_rows;
+ row += slice_rows;
+ }
+ }
+ return Status::OK();
+}
+
+Status subdivide_prefix_run(const std::vector<BlockHead>& spans, uint64_t
weight, uint64_t splits,
+ const std::optional<std::string>& upper_prefix,
SubdivisionState* state,
+ std::vector<BlockHead>* continuations) {
+ const std::vector<size_t> selected_indices = select_active_heads(spans,
weight);
+ const auto fair_share =
+ static_cast<size_t>((static_cast<unsigned
__int128>(state->probes_left) * weight) /
+ std::max<uint64_t>(weight,
state->remaining_rows));
+ const size_t run_probe_budget =
+ std::min(state->probes_left, std::max(selected_indices.size() * 2,
fair_share));
+ if (run_probe_budget < selected_indices.size()) {
+ state->accumulated += weight;
+ state->remaining_rows -= std::min(state->remaining_rows, weight);
+ return Status::OK();
+ }
+ uint64_t sampled_head_weight = 0;
+ for (size_t idx : selected_indices) {
+ sampled_head_weight += spans[idx].weight();
+ }
+ const uint64_t unprobed_weight = weight - sampled_head_weight;
+ const uint64_t usable_probes = run_probe_budget > selected_indices.size()
* 2
+ ? run_probe_budget -
selected_indices.size() * 2
+ : 1;
+ const uint64_t desired_probes = std::min<uint64_t>(
+ usable_probes, std::max<uint64_t>(splits * 2,
selected_indices.size() * 8));
+ std::map<CutKey, uint64_t> tuples;
+ uint64_t in_range_sampled_rows = 0;
+ uint64_t deferred_sampled_rows = 0;
+ size_t used_probes = 0;
+ size_t used_bytes = 0;
+ bool budget_exceeded = false;
+ RETURN_IF_ERROR(probe_selected_spans(
+ spans, selected_indices, sampled_head_weight, desired_probes,
run_probe_budget,
+ upper_prefix, state, &tuples, &in_range_sampled_rows,
&deferred_sampled_rows,
+ &used_probes, &used_bytes, &budget_exceeded, continuations));
+ state->probes_left -= std::min(state->probes_left, used_probes);
+ if (budget_exceeded || tuples.empty()) {
+ if (budget_exceeded && used_bytes >= state->bytes_left) {
+ state->bytes_left = 0;
+ }
+ continuations->clear();
+ state->accumulated += weight;
+ state->remaining_rows -= std::min(state->remaining_rows, weight);
+ return Status::OK();
+ }
+ state->bytes_left -= used_bytes;
+ const uint64_t target_in_range_weight = weight - deferred_sampled_rows;
+ state->remaining_rows -= std::min(state->remaining_rows,
target_in_range_weight);
+ uint64_t seen_raw = 0;
+ uint64_t prev_scaled = 0;
+ for (const auto& [cut_key, raw_rows] : tuples) {
+ seen_raw += raw_rows;
+ const uint64_t next_scaled =
+ unprobed_weight == 0
+ ? seen_raw
+ : static_cast<uint64_t>((static_cast<unsigned
__int128>(seen_raw) *
+ target_in_range_weight) /
+ in_range_sampled_rows);
+ const uint64_t scaled_rows = next_scaled - prev_scaled;
+ prev_scaled = next_scaled;
+ if (state->accumulated >= state->unit_rows) {
+ state->cuts->push_back({cut_key.first, cut_key.second});
+ state->accumulated = carry_residual(state->accumulated,
state->unit_rows);
+ }
+ state->accumulated += scaled_rows;
+ }
+ return Status::OK();
+}
+
+// Sparse block heads charge each physical row once. When a prefix run spans
multiple
+// unit_rows (either from overlapping rowsets, shared VARCHAR prefixes, or
unit_rows
+// smaller than the short-key block size), intra-block stride probes subdivide
it along
+// full sort-key boundaries while deferring any suffix >= the next queued
block head.
+Status build_boundaries(std::span<const SampleSegment> segments, uint64_t
unit_rows,
+ std::vector<KeyRangeBound>* cuts, uint64_t*
population) {
+ auto later = [](const BlockHead& a, const BlockHead& b) {
+ const int cmp = a.prefix().compare(b.prefix());
+ if (cmp != 0) {
+ return cmp > 0;
+ }
+ return a.seg_idx > b.seg_idx;
+ };
+ std::priority_queue<BlockHead, std::vector<BlockHead>, decltype(later)>
heads(later);
+ uint32_t max_segment_blocks = 0;
+ uint64_t total_rows = 0;
+ for (size_t seg_idx = 0; seg_idx < segments.size(); ++seg_idx) {
+ const auto& seg = segments[seg_idx];
+ if (seg.rows) {
+ total_rows += seg.rows;
+ const uint32_t stride = seg.keys->index().num_rows_per_block();
+ max_segment_blocks = std::max(max_segment_blocks,
seg.keys->index().num_items());
+ heads.push({&seg, seg_idx, 0, 0, std::min(seg.rows, stride), true,
std::nullopt});
+ }
+ }
+ if (heads.empty()) {
+ *population = 0;
+ return Status::OK();
+ }
+ SubdivisionState state {
+ .unit_rows = unit_rows,
+ .remaining_rows = total_rows,
+ .cuts = cuts,
+ };
+ while (!heads.empty()) {
+ const std::string prefix = heads.top().prefix().to_string();
+ if (state.accumulated >= unit_rows) {
+ cuts->push_back({prefix, {}});
+ state.accumulated = carry_residual(state.accumulated, unit_rows);
+ }
+ std::vector<BlockHead> raw_probes;
+ uint64_t weight = 0;
+ bool coarse_block = false;
+ bool same_segment_run = false;
+ do {
+ auto head = heads.top();
+ heads.pop();
+ weight += head.weight();
+ coarse_block |= head.weight() > unit_rows;
+ same_segment_run |= std::ranges::any_of(raw_probes, [&](const
BlockHead& prev) {
Review Comment:
[P2] Short-circuit the repeated-segment search once it succeeds
Boolean `|=` still evaluates `any_of` after `same_segment_run` becomes true.
For a supported AGG/MOR key `(region VARCHAR, k INT)` with one short-key column
and a constant region, equal-prefix heads are gathered in segment order and
every head rescans all earlier segments. With 1,000 uncompacted segments and
196 blocks each, this entails about 19 billion comparisons before the
subdivision probe budget is checked. Short-circuit after the first repeated
segment or track seen segment IDs to keep sampled ANALYZE from spending
quadratic CPU gathering a single prefix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]