This is an automated email from the ASF dual-hosted git repository.
yujun777 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new cae574ee153 [improvement](stream) Estimate stream and snapshot column
statistics (#70564)
cae574ee153 is described below
commit cae574ee153d4c8ac0ca989c2b5588d9f1714765
Author: yujun <[email protected]>
AuthorDate: Tue Nov 24 15:55:38 2026 +0800
[improvement](stream) Estimate stream and snapshot column statistics
(#70564)
### Background
Incremental streams and historical snapshots are lowered into OLAP
scans, filters, projections and unions. The optimizer needs column NDV
and NULL counts for join estimates and runtime-filter selectivity, in
addition to each scan's row estimate.
### What problem does this PR solve?
Issue Number: None
Related PR: #69850 (stream row-count estimates), #69896 (changelog
row-count collection), #69817 (IS NULL estimation)
PR Type: Enhancement
Problem Summary:
Stream and historical scans currently reuse distributions for a
different population, or look up statistics under the stream identity.
This change maps business columns to their source OLAP statistics and
derives a new distribution for each scan, preserving the source NULL
fraction and capping NDV at its estimated non-NULL rows. Most of the
diff tests population conversion and propagation; the production change
also copies partition HLLs before merging to avoid mutating cached
statistics.
### Details
- **Change map:** 459 changed production lines, 706 changed test lines
and 41 generated expectation lines. The scan calculator shares row count
setup, partition lookups and virtual column estimation, with separate
methods for ordinary and stream column distributions. A
source-table/index adapter resolves cache lookups for named streams and
their historical snapshots. The changelog wrapper records whether
normalization produced the scan from a named stream. Tests cover
conversion, mapping, cache isolation and propagation, followed by a SQL
plan/result regression.
- **Before and after:** A source column with count=1000, NULLs=900 and
NDV=100, read by a scan estimated at 100 rows, now has count=100,
NULLs=90 and NDV=10. Low NDVs are retained instead of proportionally
scaled. Source count and NULL count always come from the same table or
merged-partition population, even when the source statistics predate
current table growth. BEFORE/AFTER columns use the original business
column, while internal columns stay unknown. The average width is
retained and the total size and original statistic are rebuilt. Source
ranges and hot values are omitted because they describe a different
population. The NDV cap accounts for floating-point rounding so
fractional NULL counts survive validity checks. Join-reorder validation
consumes the same adjusted statistics.
- **Configs and defaults:** No new configuration. Stream scans only
resolve partition names when `enable_partition_analyze` is enabled.
Manually injected source statistics take priority, and a missing
selected partition falls back to the full table-level population.
- **Impact on existing users:** Ordinary OLAP, direct base-table
incremental reads, stream resets, and IVM post-snapshot reads use the
ordinary distribution rules. Named stream snapshots are estimated at
their consumption offset. Stream and historical scan estimates can
change join/RF cost decisions. Stream and historical scans use the
upstream row-count estimator as the output population. Explicit
estimates already cover the selected partitions, including fallback for
missing partition counts. Predicate estimates for a stream scan use its
scoped population. Statistics derivation records unknown key statistics
after early NDV validation. The source NULL fraction remains an
approximation. Without offset-specific min/max statistics, an equality
predicate uses the scoped NDV even for values outside the source range.
---
.../doris/catalog/OlapChangelogTableWrapper.java | 21 +-
.../rewrite/NormalizeOlapTableStreamScan.java | 2 +-
.../doris/nereids/stats/ExpressionEstimation.java | 11 +-
.../doris/nereids/stats/StatsCalculator.java | 396 +++++++++-----
.../doris/statistics/cache/StatisticsCache.java | 11 +-
.../doris/nereids/stats/StatsCalculatorTest.java | 6 +-
.../nereids/stats/StreamColumnStatisticsTest.java | 604 +++++++++++++++++++++
.../trees/plans/ExplainTableStreamPlanTest.java | 3 +
.../test_stream_column_statistics.out | 41 ++
.../test_stream_column_statistics.groovy | 93 ++++
10 files changed, 1046 insertions(+), 142 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapChangelogTableWrapper.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapChangelogTableWrapper.java
index d5b8b3653d3..e5dd5f60a18 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapChangelogTableWrapper.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/catalog/OlapChangelogTableWrapper.java
@@ -39,19 +39,36 @@ import java.util.stream.Collectors;
public class OlapChangelogTableWrapper extends OlapTableWrapper {
private final MaterializedIndexMeta changelogIndexMeta;
+ private final boolean streamScan;
public OlapChangelogTableWrapper(OlapTable originTable) {
this(originTable, Collections.emptyMap());
}
public OlapChangelogTableWrapper(OlapTable originTable, Map<Long,
PartitionScanState> partitionScanStates) {
+ this(originTable, partitionScanStates, false);
+ }
+
+ /** Build the changelog branch of a stream read or its snapshot
reconstruction. */
+ public static OlapChangelogTableWrapper forStream(OlapTable originTable,
+ Map<Long, PartitionScanState> partitionScanStates) {
+ return new OlapChangelogTableWrapper(originTable, partitionScanStates,
true);
+ }
+
+ private OlapChangelogTableWrapper(OlapTable originTable, Map<Long,
PartitionScanState> partitionScanStates,
+ boolean streamScan) {
super(originTable, originTable.getName(),
originTable.getChangelogIndexMeta().getSchema(), KeysType.DUP_KEYS,
partitionScanStates);
this.changelogIndexMeta = originTable.getChangelogIndexMeta();
+ this.streamScan = streamScan;
Preconditions.checkNotNull(changelogIndexMeta, "changelog meta is
null, table=%s", originTable.getName());
this.setBaseIndexId(changelogIndexMeta.getIndexId());
}
+ public boolean isStreamScan() {
+ return streamScan;
+ }
+
@Override
public long getBaseIndexId() {
return changelogIndexMeta.getIndexId();
@@ -103,11 +120,11 @@ public class OlapChangelogTableWrapper extends
OlapTableWrapper {
return false;
}
OlapChangelogTableWrapper other = (OlapChangelogTableWrapper) obj;
- return changelogIndexMeta.equals(other.changelogIndexMeta);
+ return streamScan == other.streamScan &&
changelogIndexMeta.equals(other.changelogIndexMeta);
}
@Override
public int hashCode() {
- return Objects.hash(super.hashCode(),
changelogIndexMeta.getChangelogIndexId());
+ return Objects.hash(super.hashCode(),
changelogIndexMeta.getChangelogIndexId(), streamScan);
}
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeOlapTableStreamScan.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeOlapTableStreamScan.java
index 00ab234384f..c45cbd286dc 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeOlapTableStreamScan.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/NormalizeOlapTableStreamScan.java
@@ -181,7 +181,7 @@ public class NormalizeOlapTableStreamScan extends
OneRewriteRuleFactory {
Map<Long, Long> rowCountEstimates =
streamWrapper.estimateChangelogRead(
selectedPartitionIds, offsetMap, streamScanType);
OlapChangelogTableWrapper table =
- new OlapChangelogTableWrapper(baseTable,
makePartitionScanStates(
+ OlapChangelogTableWrapper.forStream(baseTable,
makePartitionScanStates(
streamWrapper, selectedPartitionIds, offsetMap,
rowCountEstimates));
Map<String, String> scanParams = new HashMap<>();
scanParams.put(OlapScanNode.OLAP_INCREMENT_TYPE,
streamScanType.toString());
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/ExpressionEstimation.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/ExpressionEstimation.java
index 380fa421218..0dca9e698ac 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/ExpressionEstimation.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/ExpressionEstimation.java
@@ -342,8 +342,15 @@ public class ExpressionEstimation extends
ExpressionVisitor<ColumnStatistic, Sta
.setMaxValue(leftMax - rightMin).setMinExpr(null)
.setMaxExpr(null).build();
}
+ boolean isMultiply = binaryArithmetic instanceof Multiply;
+ boolean isDivide = binaryArithmetic instanceof Divide ||
binaryArithmetic instanceof IntegralDivide;
+ if ((isMultiply || isDivide) && (leftColStats.isMinMaxInvalid() ||
rightColStats.isMinMaxInvalid())) {
+ // Unavailable endpoints can produce NaN or a spurious zero range
in multiplication and division.
+ return new
ColumnStatisticBuilder().setNdv(ndv).setAvgSizeByte(leftColStats.avgSizeByte)
+ .setNumNulls(numNulls).setDataSize(isDivide ?
exprResultTypeWidth : dataSize).build();
+ }
// TODO: stat for multiply and divide produced by below algorithm may
have huge deviation with reality.
- if (binaryArithmetic instanceof Multiply) {
+ if (isMultiply) {
double min = Math.min(
Math.min(
Math.min(leftMin * rightMin, leftMin * rightMax),
@@ -358,7 +365,7 @@ public class ExpressionEstimation extends
ExpressionVisitor<ColumnStatistic, Sta
.setNumNulls(numNulls).setDataSize(dataSize).setMinValue(min).setMaxValue(max)
.setMaxExpr(null).setMinExpr(null).build();
}
- if (binaryArithmetic instanceof Divide || binaryArithmetic instanceof
IntegralDivide) {
+ if (isDivide) {
double min = Math.min(
Math.min(
Math.min(leftMin / noneZeroDivisor(rightMin),
leftMin / noneZeroDivisor(rightMax)),
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
index 44becf747b5..d10d0a4b12b 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
@@ -24,6 +24,7 @@ import org.apache.doris.catalog.DatabaseIf;
import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.ListPartitionItem;
import org.apache.doris.catalog.MTMV;
+import org.apache.doris.catalog.OlapChangelogTableWrapper;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.OlapTableWrapper;
import org.apache.doris.catalog.PartitionItem;
@@ -31,6 +32,7 @@ import org.apache.doris.catalog.PartitionKey;
import org.apache.doris.catalog.PartitionType;
import org.apache.doris.catalog.RangePartitionItem;
import org.apache.doris.catalog.TableIf;
+import org.apache.doris.catalog.stream.OlapTableStreamWrapper;
import org.apache.doris.common.FeConstants;
import org.apache.doris.common.Pair;
import org.apache.doris.nereids.CascadesContext;
@@ -149,6 +151,7 @@ import
org.apache.doris.statistics.model.PartitionColumnStatisticBuilder;
import org.apache.doris.statistics.model.StatisticRange;
import org.apache.doris.statistics.model.Statistics;
import org.apache.doris.statistics.model.StatisticsBuilder;
+import org.apache.doris.statistics.util.Hll128;
import org.apache.doris.statistics.util.StatisticsUtil;
import com.google.common.annotations.VisibleForTesting;
@@ -475,12 +478,12 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
}
private boolean isRegisteredRowCount(OlapScan olapScan) {
- return !hasScanRowCountEstimates(olapScan) &&
hasUserInjectedStats(olapScan);
+ return !hasScanRowCountEstimates(olapScan) &&
hasUserInjectedStats(olapScan.getTable());
}
- private boolean hasUserInjectedStats(OlapScan olapScan) {
+ private boolean hasUserInjectedStats(OlapTable table) {
AnalysisManager analysisManager =
Env.getCurrentEnv().getAnalysisManager();
- TableStatsMeta tableMeta =
analysisManager.findTableStatsStatus(olapScan.getTable().getId());
+ TableStatsMeta tableMeta =
analysisManager.findTableStatsStatus(table.getId());
return tableMeta != null && tableMeta.userInjected;
}
@@ -516,15 +519,20 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
// check validation of ndv.
private Optional<String> checkNdvValidation(OlapScan olapScan, double
rowCount) {
- OlapTableStatistics olapTableStats =
Env.getCurrentEnv().getStatisticsCache().getOlapTableStats(olapScan);
+ // Validation can run before the statistics cache finishes loading.
+ Statistics streamStats = needsStreamColumnStatistics(olapScan) ?
computeOlapScan(olapScan, false) : null;
+ OlapTableStatistics olapTableStats = streamStats == null ?
getOlapScanSourceStatistics(olapScan) : null;
boolean explicitScanEstimate = hasScanRowCountEstimates(olapScan);
for (Slot slot : ((Plan) olapScan).getOutput()) {
if (isVisibleSlotReference(slot)) {
- ColumnStatistic cache =
olapTableStats.getColumnStatistics(slot.getName(), connectContext);
+ ColumnStatistic cache = streamStats == null
+ ? olapTableStats.getColumnStatistics(slot.getName(),
connectContext)
+ : streamStats.findColumnStatistics(slot);
if (!cache.isUnKnown) {
- // Stream scan estimates cover a window or selected
partitions. Cached column stats
- // still describe the underlying index, so use the
population stored with the NDV.
- double columnPopulation = explicitScanEstimate ?
cache.count : rowCount;
+ // Validate an adjusted stream statistic against its scan
population. A cached
+ // source statistic still describes its original
population.
+ double columnPopulation = streamStats != null ?
streamStats.getRowCount()
+ : (explicitScanEstimate ? cache.count : rowCount);
if ((cache.ndv == 0 && (cache.minExpr != null ||
cache.maxExpr != null))
|| cache.ndv > columnPopulation * 10) {
return Optional.of("slot " + slot.getName() + " has
invalid column stats: " + cache);
@@ -535,142 +543,255 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
return Optional.empty();
}
- /**
- * computeOlapScan
- */
- public Statistics computeOlapScan(OlapScan olapScan) {
- OlapTable olapTable = olapScan.getTable();
- double tableRowCount = Math.max(1, getOlapTableRowCount(olapScan));
-
- OlapTableStatistics olapTableStats =
Env.getCurrentEnv().getStatisticsCache().getOlapTableStats(olapScan);
-
- if (!hasScanRowCountEstimates(olapScan)
- && (olapScan.getSelectedIndexId() !=
olapScan.getTable().getBaseIndexId()
- || olapTable instanceof MTMV)) {
- // mv is selected, return its estimated stats
- Optional<Statistics> optStats =
ConnectContext.get().getStatementContext()
- .getStatistics(((Relation) olapScan).getRelationId());
- LOG.info("computeOlapScan optStats isPresent {}, tableRowCount is
{}, table name is {}",
- optStats.isPresent(), tableRowCount,
olapTable.getQualifiedName());
- if (optStats.isPresent()) {
- double selectedPartitionsRowCount =
getSelectedPartitionRowCount(olapScan, () -> tableRowCount);
- if (isRegisteredRowCount(olapScan)) {
- // If a row count is injected for the materialized view,
use it to fix the issue where
- // the materialized view cannot be selected by cbo stable
due to selectedPartitionsRowCount being 0,
- // which is caused by delayed statistics reporting.
- selectedPartitionsRowCount = tableRowCount;
- }
- LOG.info("computeOlapScan optStats is {},
selectedPartitionsRowCount is {}", optStats.get(),
- selectedPartitionsRowCount);
- // if estimated mv rowCount is more than actual row count,
fall back to base table stats
- if (selectedPartitionsRowCount >=
optStats.get().getRowCount()) {
- Statistics derivedStats = optStats.get();
- double derivedRowCount = derivedStats.getRowCount();
- for (Slot slot : ((Relation) olapScan).getOutput()) {
- if (derivedStats.findColumnStatistics(slot) == null) {
- derivedStats.addColumnStats(slot,
- new
ColumnStatisticBuilder(ColumnStatistic.UNKNOWN, derivedRowCount).build());
- }
- }
- return derivedStats;
- }
+ /** Compute statistics for an OLAP scan or a stream read lowered to an
OLAP scan. */
+ public Statistics computeOlapScan(OlapScan scan) {
+ return computeOlapScan(scan, true);
+ }
+
+ private Statistics computeOlapScan(OlapScan scan, boolean
reportUnknownStats) {
+ double scanRowCount = getOlapTableRowCount(scan);
+ double tableRowCount = Math.max(1, scanRowCount);
+ boolean streamRead = needsStreamColumnStatistics(scan);
+ boolean explicitScanEstimate = hasScanRowCountEstimates(scan);
+ if (!streamRead && !explicitScanEstimate) {
+ Optional<Statistics> mvStats = getDerivedMvScanStatistics(scan,
tableRowCount);
+ if (mvStats.isPresent()) {
+ return mvStats.get();
}
}
+ Optional<Statistics> unknownStats = getUnknownOlapScanStatistics(scan,
tableRowCount);
+ if (unknownStats.isPresent()) {
+ if (reportUnknownStats) {
+ setHasUnknownColStatsInStatementContext();
+ }
+ return unknownStats.get();
+ }
+
+ boolean useSelectedPartitions = !hasUserInjectedStats(scan.getTable())
+ && scan.getSelectedPartitionIds().size() <
scan.getTable().getPartitionNum();
+ // Wrapper estimates already cover the selected partitions.
+ boolean estimatePartitionRows = useSelectedPartitions &&
!explicitScanEstimate;
+ double rowCount = estimatePartitionRows
+ ? getSelectedPartitionRowCount(scan, () -> tableRowCount) :
tableRowCount;
+ StatisticsBuilder builder = new
StatisticsBuilder().setRowCount(rowCount);
+ OlapTableStatistics sourceStats = getOlapScanSourceStatistics(scan);
+ if (streamRead) {
+ // Keep an unavailable estimate out of the column-distribution
calculation.
+ double columnRowCount = !estimatePartitionRows && scanRowCount < 0
? scanRowCount : rowCount;
+ computeOlapStreamScan(scan, columnRowCount, sourceStats, builder);
+ } else {
+ // Table-wide changes since ANALYZE can fall outside a stream
scan's offset range.
+ builder.setDeltaRowCount(computeDeltaRowCount(scan));
+ computeNormalOlapScan(scan, tableRowCount, rowCount,
useSelectedPartitions, sourceStats, builder);
+ }
+ if (reportUnknownStats) {
+ checkIfUnknownStatsUsedAsKey(builder);
+ }
+ return computeVirtualColumnStats(scan, builder.build());
+ }
- StatisticsBuilder builder = new StatisticsBuilder();
+ private Optional<Statistics> getDerivedMvScanStatistics(OlapScan scan,
double tableRowCount) {
+ OlapTable table = scan.getTable();
+ if (scan.getSelectedIndexId() == table.getBaseIndexId() && !(table
instanceof MTMV)) {
+ return Optional.empty();
+ }
+ Optional<Statistics> optStats =
ConnectContext.get().getStatementContext()
+ .getStatistics(((Relation) scan).getRelationId());
+ LOG.info("computeOlapScan optStats isPresent {}, tableRowCount is {},
table name is {}",
+ optStats.isPresent(), tableRowCount, table.getQualifiedName());
+ if (!optStats.isPresent()) {
+ return Optional.empty();
+ }
+ // An injected row count takes precedence over delayed partition
reports.
+ double selectedPartitionsRowCount = isRegisteredRowCount(scan)
+ ? tableRowCount : getSelectedPartitionRowCount(scan, () ->
tableRowCount);
+ LOG.info("computeOlapScan optStats is {}, selectedPartitionsRowCount
is {}",
+ optStats.get(), selectedPartitionsRowCount);
+ Statistics derivedStats = optStats.get();
+ if (selectedPartitionsRowCount >= derivedStats.getRowCount()) {
+ for (Slot slot : ((Relation) scan).getOutput()) {
+ if (derivedStats.findColumnStatistics(slot) == null) {
+ derivedStats.addColumnStats(slot,
+ new
ColumnStatisticBuilder(ColumnStatistic.UNKNOWN,
derivedStats.getRowCount()).build());
+ }
+ }
+ return optStats;
+ }
+ return Optional.empty();
+ }
- // query for system table or FeUt or analysis, use
ColumnStatistic.UNKNOWN
+ private Optional<Statistics> getUnknownOlapScanStatistics(OlapScan scan,
double rowCount) {
+ ConnectContext context = ConnectContext.get();
+ ColumnStatistic unknown;
+ if (StatisticConstants.isSystemTable(scan.getTable()) ||
!FeConstants.enableInternalSchemaDb
+ || context == null ||
context.getState().isPlanWithUnKnownColumnStats()) {
+ unknown = ColumnStatistic.UNKNOWN;
+ } else if (!context.getSessionVariable().enableStats) {
+ // Keep the scan row count on the unknown statistic used by shape
tests.
+ unknown = new ColumnStatisticBuilder(ColumnStatistic.UNKNOWN,
rowCount).build();
+ } else {
+ return Optional.empty();
+ }
+ StatisticsBuilder builder = new
StatisticsBuilder().setRowCount(rowCount);
+ for (Slot slot : ((Plan) scan).getOutput()) {
+ builder.putColumnStatistics(slot, unknown);
+ }
+ return Optional.of(builder.build());
+ }
- if (StatisticConstants.isSystemTable(olapTable) ||
!FeConstants.enableInternalSchemaDb
- || ConnectContext.get() == null
- ||
ConnectContext.get().getState().isPlanWithUnKnownColumnStats()) {
- for (Slot slot : ((Plan) olapScan).getOutput()) {
+ private void computeNormalOlapScan(OlapScan scan, double tableRowCount,
double rowCount,
+ boolean useSelectedPartitions, OlapTableStatistics sourceStats,
StatisticsBuilder builder) {
+ OlapTable table = scan.getTable();
+ List<String> partitionNames = useSelectedPartitions
+ ? getSelectedPartitionNames(scan, table) :
Collections.emptyList();
+ for (Slot slot : ((Plan) scan).getOutput()) {
+ if (!isVisibleSlotReference(slot)) {
builder.putColumnStatistics(slot, ColumnStatistic.UNKNOWN);
+ continue;
}
- setHasUnknownColStatsInStatementContext();
- builder.setRowCount(tableRowCount);
- return builder.build();
+ ColumnStatistic source = getPartitionColumnStatistic(sourceStats,
slot.getName(), partitionNames);
+ boolean useTableStats = source == null;
+ if (useTableStats) {
+ source = sourceStats.getColumnStatistics(slot.getName(),
connectContext);
+ }
+ SlotReference slotReference = (SlotReference) slot;
+ if (useSelectedPartitions) {
+ source = updateMinMaxForPartitionKey(table, partitionNames,
slotReference, source);
+ }
+ ColumnStatisticBuilder columnBuilder = new
ColumnStatisticBuilder(source, rowCount);
+ columnBuilder.normalizeAvgSizeByte(slot.getDataType());
+ if (useSelectedPartitions && useTableStats) {
+ // Table-level NULLs cover the whole table. Partition-level
NULLs already match the scan scope.
+ columnBuilder.setNumNulls(columnBuilder.getNumNulls() *
(rowCount / tableRowCount));
+ }
+ builder.putColumnStatistics(slot, columnBuilder.build());
}
+ }
- // for regression shape test
- if (ConnectContext.get() == null ||
!ConnectContext.get().getSessionVariable().enableStats) {
- // get row count from any visible slotReference's colStats
- for (Slot slot : ((Plan) olapScan).getOutput()) {
- builder.putColumnStatistics(slot,
- new ColumnStatisticBuilder(ColumnStatistic.UNKNOWN,
tableRowCount).build());
- }
- setHasUnknownColStatsInStatementContext();
- return builder.setRowCount(tableRowCount).build();
+ private List<String> getSelectedPartitionNames(OlapScan scan, OlapTable
table) {
+ List<String> names = new
ArrayList<>(scan.getSelectedPartitionIds().size());
+ for (long id : scan.getSelectedPartitionIds()) {
+ names.add(table.getPartition(id).getName());
+ }
+ return names;
+ }
+
+ private boolean needsStreamColumnStatistics(OlapScan scan) {
+ OlapTable table = scan.getTable();
+ if (table instanceof OlapTableStreamWrapper) {
+ return !((LogicalOlapTableStreamScan) scan).isReset();
+ }
+ if (table instanceof OlapChangelogTableWrapper) {
+ return ((OlapChangelogTableWrapper) table).isStreamScan();
}
+ if (table instanceof OlapTableWrapper) {
+ OlapTableWrapper wrapper = (OlapTableWrapper) table;
+ // Fixed visible versions also wrap current/reset reads in cloud
mode. Only an offset
+ // range makes a base scan historical and requires a new
column-statistics population.
+ return scan.getSelectedPartitionIds().stream().anyMatch(id ->
wrapper.getPartitionOffset(id) != null);
+ }
+ return false;
+ }
- // build Stats for olapScan
- double deltaRowCount = computeDeltaRowCount(olapScan);
- builder.setDeltaRowCount(deltaRowCount);
- // if slot is invisible, use UNKNOWN
- List<SlotReference> visibleOutputSlots = new ArrayList<>();
- for (Slot slot : ((Plan) olapScan).getOutput()) {
- if (isVisibleSlotReference(slot)) {
- visibleOutputSlots.add((SlotReference) slot);
- } else {
- builder.putColumnStatistics(slot, ColumnStatistic.UNKNOWN);
- }
+ private OlapTable getOlapScanSourceTable(OlapTable table) {
+ if (table instanceof OlapTableStreamWrapper) {
+ return ((OlapTableStreamWrapper) table).getBaseTable();
}
+ if (table instanceof OlapChangelogTableWrapper &&
!((OlapChangelogTableWrapper) table).isStreamScan()) {
+ return table;
+ }
+ if (table instanceof OlapTableWrapper) {
+ return ((OlapTableWrapper) table).getOriginTable();
+ }
+ return table;
+ }
- if (!hasUserInjectedStats(olapScan)
- && olapScan.getSelectedPartitionIds().size() <
olapScan.getTable().getPartitionNum()) {
- // partition pruned
- // try to use selected partition stats, if failed, fall back to
table stats
- double selectedPartitionsRowCount =
hasScanRowCountEstimates(olapScan)
- ? tableRowCount :
getSelectedPartitionRowCount(olapScan, () -> tableRowCount);
- List<String> selectedPartitionNames = new
ArrayList<>(olapScan.getSelectedPartitionIds().size());
- olapScan.getSelectedPartitionIds().forEach(id -> {
-
selectedPartitionNames.add(olapScan.getTable().getPartition(id).getName());
- });
- boolean enablePartitionStatics = connectContext != null
- &&
connectContext.getSessionVariable().enablePartitionAnalyze;
- for (SlotReference slot : visibleOutputSlots) {
- ColumnStatistic cache;
- // numNulls of the table level statistics covers the whole
table, so it has to be scaled
- // to the selected partitions. numNulls of the partition level
statistics is already
- // scoped to them and must not be scaled again.
- boolean scaleNumNulls;
- if (enablePartitionStatics) {
- cache = getPartitionColumnStatistic(olapTableStats,
slot.getName(), selectedPartitionNames);
- scaleNumNulls = cache == null;
- if (scaleNumNulls) {
- // partition level statistics are unavailable, fall
back to table level statistics
- cache =
olapTableStats.getColumnStatistics(slot.getName(), connectContext);
- }
- } else {
- cache = olapTableStats.getColumnStatistics(slot.getName(),
connectContext);
- scaleNumNulls = true;
- }
- if (slot.getOriginalColumn().isPresent()) {
- cache = updateMinMaxForPartitionKey(olapTable,
selectedPartitionNames, slot, cache);
+ private long getOlapScanSourceIndexId(OlapScan scan, OlapTable
sourceTable) {
+ return scan.getTable() instanceof OlapChangelogTableWrapper
+ ? sourceTable.getBaseIndexId() : scan.getSelectedIndexId();
+ }
+
+ private OlapTableStatistics getOlapScanSourceStatistics(OlapScan scan) {
+ OlapTable table = scan.getTable();
+ OlapTable sourceTable = getOlapScanSourceTable(table);
+ if (sourceTable == table) {
+ return
Env.getCurrentEnv().getStatisticsCache().getOlapTableStats(scan);
+ }
+ return Env.getCurrentEnv().getStatisticsCache().getOlapTableStats(
+ sourceTable, getOlapScanSourceIndexId(scan, sourceTable));
+ }
+
+ private void computeOlapStreamScan(OlapScan scan, double columnRowCount,
+ OlapTableStatistics sourceStats, StatisticsBuilder builder) {
+ OlapTable table = scan.getTable();
+ OlapTable sourceTable = getOlapScanSourceTable(table);
+ // ALTER TABLE ... SET STATS overrides previously collected partition
statistics.
+ List<String> partitionNames = isPartitionAnalyzeEnabled() &&
!hasUserInjectedStats(sourceTable)
+ ? getSelectedPartitionNames(scan, sourceTable) :
Collections.emptyList();
+ for (Slot slot : ((Plan) scan).getOutput()) {
+ String columnName = slot.getName();
+ boolean beforeColumn = table instanceof OlapChangelogTableWrapper
+ && Column.isChangelogBeforeColumn(columnName);
+ if (beforeColumn) {
+ // Generated by Column.generateBeforeColName; the scan may
hide this storage
+ // slot while still using it to reconstruct a business
column's before image.
+ columnName =
columnName.substring(Column.CHANGELOG_BEFORE_PREFIX.length(),
columnName.length() - 2);
+ }
+ Column sourceColumn = sourceTable.getColumn(columnName);
+ ColumnStatistic columnStats = ColumnStatistic.UNKNOWN;
+ // Internal op/TSO/LSN and stream virtual columns have no visible
source column.
+ if ((isVisibleSlotReference(slot) || beforeColumn) && sourceColumn
!= null && sourceColumn.isVisible()) {
+ ColumnStatistic source =
getPartitionColumnStatistic(sourceStats, sourceColumn.getName(),
+ partitionNames);
+ boolean usedPartitionStatistics = source != null;
+ if (source == null) {
+ source =
sourceStats.getColumnStatistics(sourceColumn.getName(), connectContext);
}
- ColumnStatisticBuilder colStatsBuilder = new
ColumnStatisticBuilder(cache,
- selectedPartitionsRowCount);
- colStatsBuilder.normalizeAvgSizeByte(slot.getDataType());
- if (scaleNumNulls) {
- double scale = tableRowCount == 0 ? 1 :
selectedPartitionsRowCount / tableRowCount;
- colStatsBuilder.setNumNulls(colStatsBuilder.getNumNulls()
* scale);
+ columnStats = estimateStreamColumnStatistics(source,
columnRowCount, slot.getDataType());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Stream column stats: table={}, index={},
partitions={}, partitionStats={}, column={}, "
+ + "source count/nulls/ndv={}/{}/{}, target
rows={}, result={}",
+ sourceTable.getId(),
getOlapScanSourceIndexId(scan, sourceTable), partitionNames,
+ usedPartitionStatistics,
+ sourceColumn.getName(),
+ source.count, source.numNulls, source.ndv,
columnRowCount, columnStats);
}
- builder.putColumnStatistics(slot, colStatsBuilder.build());
- }
- checkIfUnknownStatsUsedAsKey(builder);
- builder.setRowCount(selectedPartitionsRowCount);
- } else {
- // get table level stats
- for (SlotReference slot : visibleOutputSlots) {
- ColumnStatistic cache =
olapTableStats.getColumnStatistics(slot.getName(), connectContext);
- ColumnStatisticBuilder colStatsBuilder = new
ColumnStatisticBuilder(cache, tableRowCount);
- colStatsBuilder.normalizeAvgSizeByte(slot.getDataType());
- builder.putColumnStatistics(slot, colStatsBuilder.build());
}
- checkIfUnknownStatsUsedAsKey(builder);
- builder.setRowCount(tableRowCount);
+ builder.putColumnStatistics(slot, columnStats);
}
- return computeVirtualColumnStats(olapScan, builder.build());
+ }
+
+ /**
+ * Estimate a stream/historical scan from one unmodified source
population. Its NULL fraction
+ * is an approximation, including for DELETE/UPDATE_BEFORE.
+ */
+ @VisibleForTesting
+ static ColumnStatistic estimateStreamColumnStatistics(ColumnStatistic
source, double rowCount, DataType dataType) {
+ if (rowCount == 0) {
+ return new
ColumnStatisticBuilder().setNdv(0).setNumNulls(0).setAvgSizeByte(0).build();
+ }
+ if (rowCount < 0 || source.isUnKnown || source.count <= 0) {
+ return ColumnStatistic.UNKNOWN;
+ }
+ double numNulls = Math.min(rowCount, Math.max(0, rowCount *
(source.numNulls / source.count)));
+ double ndv = Math.min(source.ndv, rowCount - numNulls);
+ if (numNulls > rowCount - ndv) {
+ // Match enforceValid's subtraction order so rounding cannot
inflate fractional NULL counts.
+ ndv = Math.nextDown(ndv);
+ }
+ ColumnStatisticBuilder builder = new ColumnStatisticBuilder(source,
rowCount)
+ .setNumNulls(numNulls)
+ .setNdv(ndv)
+ // The source bounds may exclude values visible at the scan's
offset.
+ .setMinValue(Double.NEGATIVE_INFINITY)
+ .setMaxValue(Double.POSITIVE_INFINITY)
+ .setMinExpr(null)
+ .setMaxExpr(null)
+ .setDataSize(0)
+ .setOriginal(null)
+ .setHotValues(null);
+ builder.normalizeAvgSizeByte(dataType);
+ return builder.build();
}
private Statistics computeVirtualColumnStats(OlapScan relation, Statistics
stats) {
@@ -1258,21 +1379,25 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
return columnStatistics;
}
+ private boolean isPartitionAnalyzeEnabled() {
+ return connectContext != null &&
connectContext.getSessionVariable().enablePartitionAnalyze;
+ }
+
/**
* Merge the column statistics of the given partitions.
*
* <p>The returned statistic is scoped to the given partitions, i.e. its
count and numNulls only
- * cover them. Returns null if the statistics of any partition is unknown,
so that the caller can
- * decide whether to fall back to the table level column statistics.
+ * cover them. Returns null when partition statistics are disabled, no
partitions are selected,
+ * or any selected partition is missing stats, allowing callers to fall
back to table-level stats.
*/
private ColumnStatistic getPartitionColumnStatistic(
OlapTableStatistics olapTableStatistics, String colName,
List<String> partitionNames) {
- if (connectContext != null &&
connectContext.getState().isPlanWithUnKnownColumnStats()) {
- return ColumnStatistic.UNKNOWN;
- }
- if (partitionNames.isEmpty()) {
+ if (partitionNames.isEmpty() || !isPartitionAnalyzeEnabled()) {
return null;
}
+ if (connectContext.getState().isPlanWithUnKnownColumnStats()) {
+ return ColumnStatistic.UNKNOWN;
+ }
PartitionColumnStatisticBuilder builder = new
PartitionColumnStatisticBuilder();
boolean hasUnknown = false;
// check if there is any unknown stats to avoid unnecessary partition
column stats merge.
@@ -1293,7 +1418,10 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
// try to merge partition column stats
for (PartitionColumnStatistic pcolStats : pColStatsLists) {
if (isFirst) {
- builder = new PartitionColumnStatisticBuilder(pcolStats);
+ // merge() mutates its HLL; never merge into the shared cache
object's sketch.
+ Hll128 ndv = new Hll128();
+ ndv.merge(pcolStats.ndv);
+ builder = new
PartitionColumnStatisticBuilder(pcolStats).setNdv(ndv);
isFirst = false;
} else {
builder.merge(pcolStats);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/statistics/cache/StatisticsCache.java
b/fe/fe-core/src/main/java/org/apache/doris/statistics/cache/StatisticsCache.java
index 423bb4ce0a8..18a77eb5e9e 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/statistics/cache/StatisticsCache.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/statistics/cache/StatisticsCache.java
@@ -143,6 +143,10 @@ public class StatisticsCache {
return new OlapTableStatistics(olapScan);
}
+ public OlapTableStatistics getOlapTableStats(OlapTable table, long
selectedIndexId) {
+ return new OlapTableStatistics(table, selectedIndexId);
+ }
+
private ColumnStatistic doGetColumnStatistics(
long catalogId, long dbId, long tblId, long idxId, String colName,
ConnectContext ctx) {
StatisticsCacheKey k = new StatisticsCacheKey(catalogId, dbId, tblId,
idxId, colName);
@@ -444,8 +448,11 @@ public class StatisticsCache {
public final long tableId;
public OlapTableStatistics(OlapScan logicalOlapScan) {
- this.olapTable = logicalOlapScan.getTable();
- long selectedIndexId = logicalOlapScan.getSelectedIndexId();
+ this(logicalOlapScan.getTable(),
logicalOlapScan.getSelectedIndexId());
+ }
+
+ public OlapTableStatistics(OlapTable olapTable, long selectedIndexId) {
+ this.olapTable = olapTable;
DatabaseIf database = olapTable.getDatabase();
CatalogIf catalog = database == null ? null :
database.getCatalog();
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java
index 725993df012..2ee312fd7c5 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java
@@ -365,7 +365,6 @@ public class StatsCalculatorTest {
Mockito.when(env.getAnalysisManager()).thenReturn(analysisManager);
Mockito.when(env.getStatisticsCache()).thenReturn(statisticsCache);
-
Mockito.when(statisticsCache.getOlapTableStats(scan)).thenReturn(olapTableStatistics);
Mockito.when(olapTableStatistics.getColumnStatistics("val",
connectContext)).thenReturn(tableStatistic);
if (partitionStatistic != null) {
Mockito.when(olapTableStatistics.getPartitionColumnStatistics("p1", "val",
connectContext))
@@ -380,7 +379,12 @@ public class StatsCalculatorTest {
Mockito.when(table.getRowCountForIndex(baseIndexId,
true)).thenReturn(12L);
Mockito.when(table.getRowCountForPartitionIndex(selectedPartitionId,
baseIndexId, true)).thenReturn(4L);
if (explicitScanEstimate) {
+ OlapTable origin = Mockito.mock(OlapTable.class);
+ Mockito.when(((OlapTableWrapper)
table).getOriginTable()).thenReturn(origin);
Mockito.when(((OlapTableWrapper)
table).hasRowCountEstimates(baseIndexId)).thenReturn(true);
+ Mockito.when(statisticsCache.getOlapTableStats(origin,
baseIndexId)).thenReturn(olapTableStatistics);
+ } else {
+
Mockito.when(statisticsCache.getOlapTableStats(scan)).thenReturn(olapTableStatistics);
}
if (userInjected) {
TableStatsMeta tableStats = Mockito.mock(TableStatsMeta.class);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StreamColumnStatisticsTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StreamColumnStatisticsTest.java
new file mode 100644
index 00000000000..be9ae6ad311
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StreamColumnStatisticsTest.java
@@ -0,0 +1,604 @@
+// 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.nereids.stats;
+
+import org.apache.doris.analysis.IntLiteral;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.OlapChangelogTableWrapper;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.OlapTableWrapper;
+import org.apache.doris.catalog.Partition;
+import org.apache.doris.catalog.PrimitiveType;
+import org.apache.doris.catalog.stream.OlapTableStreamWrapper;
+import org.apache.doris.common.FeConstants;
+import org.apache.doris.common.Pair;
+import org.apache.doris.nereids.CascadesContext;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Divide;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.ExprId;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.Multiply;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.plans.algebra.SetOperation.Qualifier;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapTableStreamScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalUnion;
+import org.apache.doris.nereids.types.DoubleType;
+import org.apache.doris.nereids.types.IntegerType;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.statistics.analysis.AnalysisManager;
+import org.apache.doris.statistics.analysis.TableStatsMeta;
+import org.apache.doris.statistics.cache.StatisticsCache;
+import org.apache.doris.statistics.model.ColumnStatistic;
+import org.apache.doris.statistics.model.ColumnStatisticBuilder;
+import org.apache.doris.statistics.model.PartitionColumnStatistic;
+import org.apache.doris.statistics.model.PartitionColumnStatisticBuilder;
+import org.apache.doris.statistics.model.Statistics;
+import org.apache.doris.statistics.util.Hll128;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.util.BitSet;
+
+class StreamColumnStatisticsTest {
+ @Test
+ void testLowAndHighNdv() {
+ ColumnStatistic low = statistic(10_000_000, 24, 1_000_000);
+ ColumnStatistic high = statistic(10_000_000, 9_000_000, 1_000_000);
+ ColumnStatistic lowResult = estimate(low, 1_000_000);
+ ColumnStatistic highResult = estimate(high, 1_000_000);
+ Assertions.assertEquals(24, lowResult.ndv);
+ Assertions.assertEquals(900_000, highResult.ndv);
+ Assertions.assertEquals(100_000, lowResult.numNulls);
+ Assertions.assertEquals(1_000_000, highResult.count);
+ Assertions.assertEquals(3_600_004, highResult.dataSize);
+ Assertions.assertEquals(highResult.ndv, highResult.original.ndv);
+ }
+
+ @Test
+ void testNullsMissingStatisticsAndEmptyPopulation() {
+ ColumnStatistic allNull = estimate(statistic(100, 0, 100), 20);
+ Assertions.assertEquals(20, allNull.numNulls);
+ Assertions.assertEquals(0, allNull.ndv);
+ Assertions.assertSame(ColumnStatistic.UNKNOWN,
estimate(ColumnStatistic.UNKNOWN, 20));
+ Assertions.assertSame(ColumnStatistic.UNKNOWN, estimate(statistic(0,
0, 0), 20));
+ Assertions.assertSame(ColumnStatistic.UNKNOWN, estimate(statistic(-1,
10, 0), 20));
+ Assertions.assertSame(ColumnStatistic.UNKNOWN, estimate(statistic(100,
10, 0), -1));
+ ColumnStatistic empty = estimate(ColumnStatistic.UNKNOWN, 0);
+ Assertions.assertFalse(empty.isUnKnown);
+ Assertions.assertEquals(0, empty.count);
+ Assertions.assertEquals(0, empty.ndv);
+ Assertions.assertEquals(0, empty.numNulls);
+ Assertions.assertNull(empty.minExpr);
+ }
+
+ @Test
+ void testSourcePopulationAndCacheArePreserved() {
+ ColumnStatistic source = new ColumnStatisticBuilder(statistic(1000,
100, 900))
+ .setMinValue(1).setMinExpr(new IntLiteral(1))
+ .setMaxValue(100).setMaxExpr(new IntLiteral(100))
+ .setUpdatedTime("2026-11-01 00:00:00")
+ .setHotValues(ImmutableMap.of(new IntegerLiteral(1),
10f)).build();
+ ColumnStatistic small = estimate(source, 10);
+ ColumnStatistic large = estimate(source, 100);
+ Assertions.assertEquals(9, small.numNulls);
+ Assertions.assertEquals(1, small.ndv);
+ Assertions.assertEquals(90, large.numNulls);
+ Assertions.assertEquals(10, large.ndv);
+ Assertions.assertEquals(1000, source.count);
+ Assertions.assertEquals(900, source.numNulls);
+ Assertions.assertEquals(100, source.ndv);
+ Assertions.assertEquals(100, source.original.ndv);
+ Assertions.assertEquals(1, source.hotValues.size());
+ Assertions.assertNull(small.hotValues);
+ Assertions.assertEquals(source.updatedTime, small.updatedTime);
+ Assertions.assertEquals(1, source.minValue);
+ Assertions.assertEquals(100, source.maxValue);
+ Assertions.assertNull(small.minExpr);
+ Assertions.assertNull(small.maxExpr);
+ Assertions.assertEquals(Double.NEGATIVE_INFINITY, small.minValue);
+ Assertions.assertEquals(Double.POSITIVE_INFINITY, small.maxValue);
+ Assertions.assertEquals(small.ndv, small.original.ndv);
+ Assertions.assertNotSame(source.original, small.original);
+ }
+
+ @Test
+ void testAverageWidthFallback() {
+ ColumnStatistic source = new ColumnStatisticBuilder(statistic(100, 10,
0)).setAvgSizeByte(0).build();
+ Assertions.assertEquals(4, estimate(source, 20).avgSizeByte);
+ }
+
+ @Test
+ void testChangelogMapsToBaseColumnAndChecksAdjustedNdv() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ // The current table has grown since ANALYZE. Use the source
count=1000, not
+ // the current row count=10000, as the denominator for its 900
NULLs.
+ Mockito.when(fixture.source.getRowCount()).thenReturn(10_000L);
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ Statistics stats = fixture.compute();
+ ColumnStatistic column = stats.findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(90, column.numNulls);
+ Assertions.assertEquals(10, column.ndv);
+ Assertions.assertEquals(100, column.count);
+
Assertions.assertTrue(stats.findColumnStatistics(fixture.internalSlot).isUnKnown);
+ Mockito.verify(fixture.cache).getOlapTableStats(fixture.source,
10L);
+
+ CascadesContext context = Mockito.mock(CascadesContext.class);
+
Mockito.when(context.getConnectContext()).thenReturn(fixture.context);
+
Assertions.assertFalse(StatsCalculator.disableJoinReorderIfStatsInvalid(
+ ImmutableList.of(fixture.scan), context).isPresent());
+
Assertions.assertFalse(fixture.context.getSessionVariable().isDisableJoinReorder());
+ }
+ }
+
+ @Test
+ void testJoinReorderValidatesAdjustedNdv() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ // Raw NDV=10000 exceeds 10 * scan rows. The valid source
population has
+ // 10000 non-NULL rows; the scan distribution caps its NDV at 10
instead.
+ fixture.tableStatistic(statistic(100_000, 10_000, 90_000));
+ CascadesContext context = Mockito.mock(CascadesContext.class);
+
Mockito.when(context.getConnectContext()).thenReturn(fixture.context);
+
Assertions.assertFalse(StatsCalculator.disableJoinReorderIfStatsInvalid(
+ ImmutableList.of(fixture.scan), context).isPresent());
+
Assertions.assertFalse(fixture.context.getSessionVariable().isDisableJoinReorder());
+ }
+ }
+
+ @Test
+ void testNdvValidationLeavesStatementUnknownStatsToDerivation() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ StatementContext statement = new StatementContext(0);
+ fixture.context.setStatementContext(statement);
+ statement.addKeySlot(fixture.slot);
+ fixture.tableStatistic(ColumnStatistic.UNKNOWN);
+
+ CascadesContext context = Mockito.mock(CascadesContext.class);
+
Mockito.when(context.getConnectContext()).thenReturn(fixture.context);
+
Assertions.assertTrue(StatsCalculator.disableJoinReorderIfStatsInvalid(
+ ImmutableList.of(fixture.scan), context).isEmpty());
+ Assertions.assertFalse(statement.isHasUnknownColStats());
+
+ fixture.compute();
+ Assertions.assertTrue(statement.isHasUnknownColStats());
+ }
+ }
+
+ @Test
+ void testHiddenBeforeColumnMapsToOriginalBusinessColumn() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ Column before = Column.generateBeforeValueColumn(new Column("val",
PrimitiveType.INT));
+ before.setIsVisible(false);
+ SlotReference beforeSlot = SlotReference.fromColumn(new ExprId(3),
fixture.table, before,
+ ImmutableList.of("test", "tbl"));
+
Mockito.when(fixture.scan.getOutput()).thenReturn(ImmutableList.of(fixture.slot,
beforeSlot));
+ ColumnStatistic result =
fixture.compute().findColumnStatistics(beforeSlot);
+ Assertions.assertEquals(90, result.numNulls);
+ Assertions.assertEquals(10, result.ndv);
+ }
+ }
+
+ @Test
+ void testStreamAndHistoricalScansUseSourceStatistics() {
+ for (Class<? extends OlapTable> type :
ImmutableList.of(OlapTableStreamWrapper.class, OlapTableWrapper.class)) {
+ try (ScanFixture fixture = new ScanFixture(type, 100)) {
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ ColumnStatistic column =
fixture.compute().findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(90, column.numNulls);
+ Assertions.assertEquals(10, column.ndv);
+
Mockito.verify(fixture.cache).getOlapTableStats(fixture.source, 10L);
+ Mockito.verify(fixture.source,
Mockito.never()).getPartition(Mockito.anyLong());
+ }
+ }
+ }
+
+ @Test
+ void testDirectChangelogScanKeepsOrdinaryColumnStatistics() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ Mockito.when(((OlapChangelogTableWrapper)
fixture.table).isStreamScan()).thenReturn(false);
+ fixture.tableStatistic(statistic(1000, 100, 900));
+
+ Statistics result = fixture.compute();
+ ColumnStatistic column = result.findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(100, result.getRowCount());
+ Assertions.assertEquals(900, column.numNulls);
+ Assertions.assertEquals(100, column.ndv);
+ Mockito.verify(fixture.cache).getOlapTableStats(fixture.scan);
+ }
+ }
+
+ @Test
+ void testHistoricalScanPrefersInjectedTableStatistics() {
+ try (ScanFixture fixture = new ScanFixture(OlapTableWrapper.class,
100)) {
+ fixture.context.getSessionVariable().enablePartitionAnalyze = true;
+ Mockito.when(((OlapTableWrapper)
fixture.table).hasRowCountEstimates(10L)).thenReturn(true);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(1L, 10L,
true)).thenReturn(50L);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(2L, 10L,
true)).thenReturn(50L);
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ fixture.partitionStatistics(partitionStatistic(50, 0, 1),
partitionStatistic(50, 0, 2));
+ TableStatsMeta tableStats = Mockito.mock(TableStatsMeta.class);
+ tableStats.userInjected = true;
+
Mockito.when(fixture.analysisManager.findTableStatsStatus(fixture.source.getId())).thenReturn(tableStats);
+
+ Statistics result = fixture.compute();
+ ColumnStatistic column = result.findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(100, result.getRowCount());
+ Assertions.assertEquals(90, column.numNulls);
+ Assertions.assertEquals(10, column.ndv);
+ }
+ }
+
+ @Test
+ void testResetStreamUsesOrdinarySourceDistribution() {
+ try (ScanFixture fixture = new
ScanFixture(OlapTableStreamWrapper.class, 100)) {
+ Mockito.when(((LogicalOlapTableStreamScan)
fixture.scan).isReset()).thenReturn(true);
+ fixture.tableStatistic(statistic(1000, 24, 10));
+ ColumnStatistic result =
fixture.compute().findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(24, result.ndv);
+ Assertions.assertEquals(10, result.numNulls);
+ }
+ }
+
+ @Test
+ void testPrunedScanUsesItsOutputRowCountOnce() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 1000)) {
+ Mockito.when(fixture.table.getPartitionNum()).thenReturn(3);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(1L, 30L,
true)).thenReturn(10L);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(2L, 30L,
true)).thenReturn(30L);
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ Statistics result = fixture.compute();
+ Assertions.assertEquals(40, result.getRowCount());
+ Assertions.assertEquals(36,
result.findColumnStatistics(fixture.slot).numNulls);
+ Assertions.assertEquals(4,
result.findColumnStatistics(fixture.slot).ndv);
+ }
+ }
+
+ @Test
+ void testExplicitScanEstimateUsesTableFallbackOnlyOnce() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 90)) {
+ Mockito.when(((OlapTableWrapper)
fixture.table).hasRowCountEstimates(30L)).thenReturn(true);
+ Mockito.when(fixture.table.getPartitionNum()).thenReturn(3);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(1L, 30L,
true)).thenReturn(10L);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(2L, 30L,
true)).thenReturn(-1L);
+ fixture.tableStatistic(statistic(1000, 100, 900));
+
+ // One known partition contributes 10 rows; the missing one uses
90 / 3 table rows.
+ Statistics result = fixture.compute();
+ ColumnStatistic column = result.findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(40, result.getRowCount());
+ Assertions.assertEquals(40, column.count);
+ Assertions.assertEquals(36, column.numNulls);
+ Assertions.assertEquals(4, column.ndv);
+ }
+ }
+
+ @Test
+ void testUnknownRowCountDoesNotBecomeKnownOneRowDistribution() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, -1)) {
+ fixture.tableStatistic(statistic(1000, 100, 100));
+ Statistics stats = fixture.compute();
+ Assertions.assertEquals(1, stats.getRowCount());
+
Assertions.assertTrue(stats.findColumnStatistics(fixture.slot).isUnKnown);
+ }
+ }
+
+ @Test
+ void testUnknownExplicitRowCountDoesNotBecomeKnownOneRowDistribution() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, -1)) {
+ Mockito.when(((OlapTableWrapper)
fixture.table).hasRowCountEstimates(30L)).thenReturn(true);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(1L, 30L,
true)).thenReturn(-1L);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(2L, 30L,
true)).thenReturn(-1L);
+ fixture.tableStatistic(statistic(1000, 100, 100));
+
+ Statistics result = fixture.compute();
+ Assertions.assertEquals(1, result.getRowCount());
+
Assertions.assertTrue(result.findColumnStatistics(fixture.slot).isUnKnown);
+ }
+ }
+
+ @Test
+ void testScanMinimumUsesOneConsistentPopulation() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 0)) {
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ Statistics stats = fixture.compute();
+ ColumnStatistic column = stats.findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(1, stats.getRowCount());
+ Assertions.assertEquals(1, column.count);
+ Assertions.assertEquals(0.9, column.numNulls, 1e-9);
+ Assertions.assertEquals(0.1, column.ndv, 1e-9);
+ }
+ }
+
+ @Test
+ void testWeightedPartitionPopulationAndNoCacheMutation() {
+ PartitionColumnStatistic first = partitionStatistic(100, 90, 1);
+ PartitionColumnStatistic second = partitionStatistic(900, 90, 2);
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ fixture.context.getSessionVariable().enablePartitionAnalyze = true;
+ fixture.tableStatistic(statistic(10_000, 1000, 9000));
+ fixture.partitionStatistics(first, second);
+ ColumnStatistic result =
fixture.compute().findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(18, result.numNulls);
+ Assertions.assertEquals(2, result.ndv);
+ Assertions.assertEquals(100, result.count);
+ Assertions.assertEquals(1, first.ndv.estimateCardinality());
+ Assertions.assertEquals(1, second.ndv.estimateCardinality());
+ Assertions.assertEquals(18,
fixture.compute().findColumnStatistics(fixture.slot).numNulls);
+ }
+ }
+
+ @Test
+ void testMissingPartitionFallsBackAsOnePopulation() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ fixture.context.getSessionVariable().enablePartitionAnalyze = true;
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ fixture.partitionStatistics(partitionStatistic(100, 10, 1),
PartitionColumnStatistic.UNKNOWN);
+ ColumnStatistic result =
fixture.compute().findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(90, result.numNulls);
+ Assertions.assertEquals(10, result.ndv);
+ }
+ }
+
+ @Test
+ void testCurrentSnapshotWrapperKeepsOrdinaryStatistics() {
+ try (ScanFixture fixture = new ScanFixture(OlapTableWrapper.class,
100)) {
+ Mockito.when(((OlapTableWrapper)
fixture.table).getPartitionOffset(Mockito.anyLong())).thenReturn(null);
+ ColumnStatistic source = statistic(1000, 24, 100);
+ fixture.tableStatistic(source);
+ ColumnStatistic result =
fixture.compute().findColumnStatistics(fixture.slot);
+ Assertions.assertEquals(24, result.ndv);
+ Assertions.assertEquals(100, result.numNulls);
+ Mockito.verify(fixture.cache).getOlapTableStats(fixture.source,
10L);
+ }
+ }
+
+ @Test
+ void testAliasesPropagateScanOriginalWithoutRescaling() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ fixture.tableStatistic(statistic(1000, 100, 900));
+ Statistics scanStats = fixture.compute();
+ Alias alias = new Alias(fixture.slot, "before_key");
+ LogicalProject<LogicalOlapScan> project = new
LogicalProject<>(ImmutableList.of(alias), fixture.scan);
+ Statistics result = new StatsCalculator((CascadesContext)
null).computeProject(project, scanStats);
+ ColumnStatistic column =
result.findColumnStatistics(alias.toSlot());
+ Assertions.assertEquals(90, column.numNulls);
+ Assertions.assertEquals(10, column.ndv);
+ Assertions.assertEquals(10, column.original.ndv);
+ }
+ }
+
+ @Test
+ void testHistoricalFilterIgnoresTableWideDeltaRows() {
+ try (ScanFixture fixture = new ScanFixture(OlapTableWrapper.class,
100)) {
+ Mockito.when(((OlapTableWrapper)
fixture.table).hasRowCountEstimates(10L)).thenReturn(true);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(1L, 10L,
true)).thenReturn(40L);
+ Mockito.when(fixture.table.getRowCountForPartitionIndex(2L, 10L,
true)).thenReturn(60L);
+ long sourceTableId = fixture.source.getId();
+ Mockito.when(fixture.table.getId()).thenReturn(sourceTableId);
+ TableStatsMeta tableStats = Mockito.mock(TableStatsMeta.class);
+
Mockito.when(tableStats.getBaseIndexDeltaRowCount(fixture.table)).thenReturn(1_000_000L);
+
Mockito.when(fixture.analysisManager.findTableStatsStatus(sourceTableId)).thenReturn(tableStats);
+ fixture.tableStatistic(statistic(10_000, 10, 0));
+
+ Statistics scanStats = fixture.compute();
+ LogicalFilter<LogicalOlapScan> filter = new LogicalFilter<>(
+ ImmutableSet.of(new IsNull(fixture.slot)), fixture.scan);
+ Statistics filtered = new StatsCalculator((CascadesContext)
null).computeFilter(filter, scanStats);
+ Assertions.assertEquals(100, scanStats.getRowCount());
+ Assertions.assertEquals(0, scanStats.getDeltaRowCount());
+ Assertions.assertEquals(0, filtered.getRowCount());
+ }
+ }
+
+ @Test
+ void testIsNullKeepsFractionalNullEstimateAfterEnforceValid() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 10)) {
+ fixture.tableStatistic(statistic(1000, 999, 1));
+ Statistics scanStats = fixture.compute();
+ scanStats.enforceValid();
+
+ LogicalFilter<LogicalOlapScan> filter = new LogicalFilter<>(
+ ImmutableSet.of(new IsNull(fixture.slot)), fixture.scan);
+ Statistics filtered = new StatsCalculator((CascadesContext)
null).computeFilter(filter, scanStats);
+ Assertions.assertEquals(0.01,
scanStats.findColumnStatistics(fixture.slot).numNulls, 1e-12);
+ Assertions.assertEquals(0.01, filtered.getRowCount(), 1e-12);
+ }
+ }
+
+ @Test
+ void testHistoricalEqualityOutsideSourceBoundsUsesNdv() {
+ try (ScanFixture fixture = new ScanFixture(OlapTableWrapper.class,
100)) {
+ fixture.tableStatistic(new ColumnStatisticBuilder(statistic(1000,
10, 0))
+ .setMinValue(1).setMinExpr(new IntLiteral(1))
+ .setMaxValue(10).setMaxExpr(new IntLiteral(10)).build());
+ Statistics scanStats = fixture.compute();
+ scanStats.enforceValid();
+
+ LogicalFilter<LogicalOlapScan> filter = new LogicalFilter<>(
+ ImmutableSet.of(new EqualTo(fixture.slot, new
IntegerLiteral(20))), fixture.scan);
+ Statistics filtered = new StatsCalculator((CascadesContext)
null).computeFilter(filter, scanStats);
+ Assertions.assertEquals(10, filtered.getRowCount(), 1e-9);
+ }
+ }
+
+ @Test
+ void testArithmeticInPredicateWithUnknownStreamBoundsUsesNdv() {
+ ColumnStatistic source = new ColumnStatisticBuilder(statistic(1000,
10, 0))
+ .setMinValue(1).setMaxValue(10).build();
+ ColumnStatistic column =
StatsCalculator.estimateStreamColumnStatistics(source, 100,
DoubleType.INSTANCE);
+ SlotReference left = new SlotReference("a", DoubleType.INSTANCE, true);
+ SlotReference right = new SlotReference("b", DoubleType.INSTANCE,
true);
+ Statistics scanStats = new Statistics(100, ImmutableMap.of(left,
column, right, column));
+ ImmutableList<Expression> options = ImmutableList.of(new
DoubleLiteral(1), new DoubleLiteral(2));
+ InPredicate divideColumns = new InPredicate(new Divide(left, right),
options);
+ InPredicate divideConstant = new InPredicate(new Divide(new
DoubleLiteral(10), right), options);
+ InPredicate multiplyByZero = new InPredicate(new Multiply(left, new
DoubleLiteral(0)),
+ ImmutableList.of(new DoubleLiteral(0), new DoubleLiteral(1)));
+ FilterEstimation filter = new FilterEstimation();
+ Assertions.assertEquals(20, filter.estimate(divideColumns,
scanStats).getRowCount(), 1e-9);
+ Assertions.assertEquals(20, filter.estimate(divideConstant,
scanStats).getRowCount(), 1e-9);
+ Assertions.assertEquals(20, filter.estimate(multiplyByZero,
scanStats).getRowCount(), 1e-9);
+ }
+
+ @Test
+ void testFilterAndSnapshotUnionUseAdjustedPopulationOnce() {
+ try (ScanFixture fixture = new
ScanFixture(OlapChangelogTableWrapper.class, 100)) {
+ ColumnStatistic source = new
ColumnStatisticBuilder(statistic(1000, 100, 900))
+ .setMinValue(1).setMaxValue(100).build();
+ fixture.tableStatistic(source);
+ Statistics left = fixture.compute();
+ StatsCalculator calculator = new StatsCalculator((CascadesContext)
null);
+ LogicalFilter<LogicalOlapScan> filter = new LogicalFilter<>(
+ ImmutableSet.of(new IsNull(fixture.slot)), fixture.scan);
+ Statistics filtered = calculator.computeFilter(filter, left);
+ Assertions.assertEquals(90, filtered.getRowCount());
+
+ SlotReference rightSlot = new SlotReference("right_key",
IntegerType.INSTANCE, true);
+ ColumnStatistic rightColumn = estimate(source, 200);
+ Statistics right = new Statistics(200, ImmutableMap.of(rightSlot,
rightColumn));
+ LogicalUnion union = new LogicalUnion(Qualifier.ALL,
ImmutableList.of(fixture.slot),
+ ImmutableList.of(ImmutableList.of(fixture.slot),
ImmutableList.of(rightSlot)),
+ ImmutableList.of(), false, ImmutableList.of(fixture.scan,
fixture.scan));
+ Statistics combined = calculator.computeUnion(union,
ImmutableList.of(left, right));
+ Assertions.assertEquals(300, combined.getRowCount());
+ Assertions.assertEquals(270,
combined.findColumnStatistics(fixture.slot).numNulls);
+ Assertions.assertEquals(20,
combined.findColumnStatistics(fixture.slot).ndv);
+ }
+ }
+
+ private static ColumnStatistic statistic(double count, double ndv, double
nulls) {
+ return new
ColumnStatisticBuilder(count).setNdv(ndv).setNumNulls(nulls).setAvgSizeByte(4).build();
+ }
+
+ private static ColumnStatistic estimate(ColumnStatistic source, double
rows) {
+ return StatsCalculator.estimateStreamColumnStatistics(source, rows,
IntegerType.INSTANCE);
+ }
+
+ private static PartitionColumnStatistic partitionStatistic(double count,
double nulls, long value) {
+ Hll128 ndv = new Hll128();
+ ndv.update(value);
+ return new
PartitionColumnStatisticBuilder(count).setNdv(ndv).setNumNulls(nulls).setAvgSizeByte(4).build();
+ }
+
+ private static class ScanFixture implements AutoCloseable {
+ private final ConnectContext previousContext = ConnectContext.get();
+ private final boolean previousInternalSchema =
FeConstants.enableInternalSchemaDb;
+ private final ConnectContext context = new ConnectContext();
+ private final AnalysisManager analysisManager =
Mockito.mock(AnalysisManager.class);
+ private final StatisticsCache cache =
Mockito.mock(StatisticsCache.class);
+ private final StatisticsCache.OlapTableStatistics sourceStats
+ = Mockito.mock(StatisticsCache.OlapTableStatistics.class);
+ private final OlapTable source = Mockito.mock(OlapTable.class);
+ private final OlapTable table;
+ private final LogicalOlapScan scan;
+ private final SlotReference slot;
+ private final SlotReference internalSlot;
+ private final MockedStatic<Env> mockedEnv;
+
+ ScanFixture(Class<? extends OlapTable> type, long rowCount) {
+ context.setThreadLocalInfo();
+ context.getSessionVariable().enableStats = true;
+ context.getSessionVariable().enablePartitionAnalyze = false;
+ FeConstants.enableInternalSchemaDb = true;
+ table = Mockito.mock(type);
+ scan = type == OlapTableStreamWrapper.class ?
Mockito.mock(LogicalOlapTableStreamScan.class)
+ : Mockito.mock(LogicalOlapScan.class);
+ if (table instanceof OlapTableStreamWrapper) {
+ Mockito.when(((OlapTableStreamWrapper)
table).getBaseTable()).thenReturn(source);
+ } else {
+ Mockito.when(((OlapTableWrapper)
table).getOriginTable()).thenReturn(source);
+ Mockito.when(((OlapTableWrapper)
table).getPartitionOffset(Mockito.anyLong()))
+ .thenReturn(Pair.of(1L, 2L));
+ }
+ Column column = new Column("val", PrimitiveType.INT);
+ slot = new SlotReference(new ExprId(1), "val",
IntegerType.INSTANCE, true,
+ ImmutableList.of("test", "tbl"), table, column, table,
column);
+ Column internal = new Column(Column.CHANGELOG_TSO_COL,
PrimitiveType.BIGINT);
+ internal.setIsVisible(false);
+ internalSlot = SlotReference.fromColumn(new ExprId(2), table,
internal, ImmutableList.of("test", "tbl"));
+ Mockito.when(source.getColumn("val")).thenReturn(column);
+ Mockito.when(source.getBaseIndexId()).thenReturn(10L);
+ Mockito.when(source.getId()).thenReturn(20L);
+ if (table instanceof OlapChangelogTableWrapper) {
+ Mockito.when(((OlapChangelogTableWrapper)
table).isStreamScan()).thenReturn(true);
+ }
+ long indexId = type == OlapChangelogTableWrapper.class ? 30L : 10L;
+ Mockito.when(table.getBaseIndexId()).thenReturn(indexId);
+ Mockito.when(table.getRowCountForIndex(indexId,
true)).thenReturn(rowCount);
+ Mockito.when(table.getPartitionNum()).thenReturn(2);
+ Mockito.when(table.getQualifiedDbName()).thenReturn("test");
+ Mockito.when(scan.getTable()).thenReturn(table);
+ Mockito.when(scan.getSelectedIndexId()).thenReturn(indexId);
+
Mockito.when(scan.getSelectedPartitionIds()).thenReturn(ImmutableList.of(1L,
2L));
+ Mockito.when(scan.getOutput()).thenReturn(ImmutableList.of(slot,
internalSlot));
+ Mockito.when(scan.getAllChildrenTypes()).thenReturn(new BitSet());
+
Mockito.when(scan.getVirtualColumns()).thenReturn(ImmutableList.of());
+ for (long id = 1; id <= 2; id++) {
+ Partition partition = Mockito.mock(Partition.class);
+ Mockito.when(partition.getName()).thenReturn("p" + id);
+ Mockito.when(source.getPartition(id)).thenReturn(partition);
+ }
+ Env env = Mockito.mock(Env.class);
+ Mockito.when(env.getAnalysisManager()).thenReturn(analysisManager);
+ Mockito.when(env.getStatisticsCache()).thenReturn(cache);
+
Mockito.when(cache.getOlapTableStats(scan)).thenReturn(sourceStats);
+ Mockito.when(cache.getOlapTableStats(source,
10L)).thenReturn(sourceStats);
+ mockedEnv = Mockito.mockStatic(Env.class);
+ mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+ }
+
+ void tableStatistic(ColumnStatistic statistic) {
+ Mockito.when(sourceStats.getColumnStatistics("val",
context)).thenReturn(statistic);
+ }
+
+ void partitionStatistics(PartitionColumnStatistic first,
PartitionColumnStatistic second) {
+ Mockito.when(sourceStats.getPartitionColumnStatistics("p1", "val",
context)).thenReturn(first);
+ Mockito.when(sourceStats.getPartitionColumnStatistics("p2", "val",
context)).thenReturn(second);
+ }
+
+ Statistics compute() {
+ return new StatsCalculator((CascadesContext)
null).computeOlapScan(scan);
+ }
+
+ @Override
+ public void close() {
+ mockedEnv.close();
+ FeConstants.enableInternalSchemaDb = previousInternalSchema;
+ ConnectContext.remove();
+ if (previousContext != null) {
+ previousContext.setThreadLocalInfo();
+ }
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainTableStreamPlanTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainTableStreamPlanTest.java
index f03059af436..978e76bb4c0 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainTableStreamPlanTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/ExplainTableStreamPlanTest.java
@@ -464,6 +464,7 @@ public class ExplainTableStreamPlanTest extends
TestWithFeService {
if (!(scanNode.getOlapTable() instanceof
OlapChangelogTableWrapper)) {
continue;
}
+ Assertions.assertTrue(((OlapChangelogTableWrapper)
scanNode.getOlapTable()).isStreamScan());
List<TScanRangeLocations> locations =
scanNode.getScanRangeLocations(Long.MAX_VALUE);
Assertions.assertFalse(locations.isEmpty());
for (TScanRangeLocations loc : locations) {
@@ -744,6 +745,7 @@ public class ExplainTableStreamPlanTest extends
TestWithFeService {
if (!(scanNode.getOlapTable() instanceof
OlapChangelogTableWrapper)) {
continue;
}
+ Assertions.assertFalse(((OlapChangelogTableWrapper)
scanNode.getOlapTable()).isStreamScan());
List<TScanRangeLocations> locations =
scanNode.getScanRangeLocations(Long.MAX_VALUE);
Assertions.assertFalse(locations.isEmpty());
for (TScanRangeLocations loc : locations) {
@@ -917,6 +919,7 @@ public class ExplainTableStreamPlanTest extends
TestWithFeService {
Assertions.assertEquals(mow ? 1 : 0, changelogScans.size());
for (LogicalOlapScan scan : changelogScans) {
OlapChangelogTableWrapper wrapper = (OlapChangelogTableWrapper)
scan.getTable();
+ Assertions.assertFalse(wrapper.isStreamScan());
Assertions.assertFalse(wrapper.getPartitionIds().isEmpty());
for (Long partitionId : wrapper.getPartitionIds()) {
Assertions.assertEquals(Pair.of(exclusiveBound, null),
wrapper.getPartitionOffset(partitionId));
diff --git
a/regression-test/data/table_stream_p0/test_stream_column_statistics.out
b/regression-test/data/table_stream_p0/test_stream_column_statistics.out
new file mode 100644
index 00000000000..20e31539461
--- /dev/null
+++ b/regression-test/data/table_stream_p0/test_stream_column_statistics.out
@@ -0,0 +1,41 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !snapshot_null_selectivity --
+0.90
+
+-- !dup_snapshot --
+1 \N
+2 20
+3 20
+
+-- !dup_delta --
+4 \N
+5 50
+
+-- !dup_reset --
+1 \N
+2 20
+3 20
+4 \N
+5 50
+
+-- !unique_snapshot --
+1 \N
+2 20
+3 30
+
+-- !unique_delta --
+1 \N UPDATE_BEFORE
+1 10 UPDATE_AFTER
+2 20 DELETE
+4 \N APPEND
+
+-- !unique_reset --
+1 10
+3 30
+4 \N
+
+-- !snapshot_join --
+1 \N \N
+2 20 20
+3 20 30
+
diff --git
a/regression-test/suites/table_stream_p0/test_stream_column_statistics.groovy
b/regression-test/suites/table_stream_p0/test_stream_column_statistics.groovy
new file mode 100644
index 00000000000..6798ff8bbdb
--- /dev/null
+++
b/regression-test/suites/table_stream_p0/test_stream_column_statistics.groovy
@@ -0,0 +1,93 @@
+// 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.
+
+suite("test_stream_column_statistics") {
+ sql "DROP STREAM IF EXISTS stream_col_stats_dup_s"
+ sql "DROP STREAM IF EXISTS stream_col_stats_unique_s"
+ sql "DROP TABLE IF EXISTS stream_col_stats_dup"
+ sql "DROP TABLE IF EXISTS stream_col_stats_unique"
+ sql """
+ CREATE TABLE stream_col_stats_dup (id INT, v INT)
+ DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num"="1", "changelog.enable"="true")
+ """
+ sql """
+ CREATE TABLE stream_col_stats_unique (id INT, v INT)
+ UNIQUE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num"="1",
"enable_unique_key_merge_on_write"="true",
+ "changelog.enable"="true",
"changelog.need_historical_value"="true")
+ """
+ sql "INSERT INTO stream_col_stats_dup VALUES (1, NULL), (2, 20), (3, 20)"
+ sql "INSERT INTO stream_col_stats_unique VALUES (1, NULL), (2, 20), (3,
30)"
+ sql """CREATE STREAM stream_col_stats_dup_s ON TABLE stream_col_stats_dup
+ PROPERTIES ("type"="append_only", "show_initial_rows"="false")"""
+ sql """CREATE STREAM stream_col_stats_unique_s ON TABLE
stream_col_stats_unique
+ PROPERTIES ("type"="min_delta", "show_initial_rows"="false")"""
+ sql "INSERT INTO stream_col_stats_dup VALUES (4, NULL), (5, 50)"
+ sql "INSERT INTO stream_col_stats_unique VALUES (1, 10), (4, NULL)"
+ sql "DELETE FROM stream_col_stats_unique WHERE id = 2"
+ sql "SYNC"
+
+ // Keep v's source population at 1000 rows with 900 NULLs. The later
injection for id
+ // sets the table-level row-count fallback. A snapshot can use its
partition baseline instead.
+ sql """ALTER TABLE stream_col_stats_dup MODIFY COLUMN v SET STATS
+ ('row_count'='1000', 'ndv'='100', 'num_nulls'='900', 'avg_size'='4',
+ 'min_value'='1', 'max_value'='100')"""
+ sql """ALTER TABLE stream_col_stats_dup MODIFY COLUMN id SET STATS
+ ('row_count'='100', 'ndv'='100', 'num_nulls'='0', 'avg_size'='4',
+ 'min_value'='1', 'max_value'='100')"""
+ sql """ALTER TABLE stream_col_stats_unique MODIFY COLUMN v SET STATS
+ ('row_count'='1000', 'ndv'='100', 'num_nulls'='900', 'avg_size'='4',
+ 'min_value'='1', 'max_value'='100')"""
+ sql """ALTER TABLE stream_col_stats_unique MODIFY COLUMN id SET STATS
+ ('row_count'='100', 'ndv'='100', 'num_nulls'='0', 'avg_size'='4',
+ 'min_value'='1', 'max_value'='100')"""
+
+ def plan = sql_return_maparray """
+ EXPLAIN PHYSICAL PLAN SELECT v FROM stream_col_stats_dup_s@snapshot()
WHERE v IS NULL
+ """
+ def rowEstimate = { String operator ->
+ def node = plan.find { it["Explain String(Nereids
Planner)"].contains(operator) }
+ assertTrue(node != null, "Missing ${operator} in ${plan}")
+ def stats = node["Explain String(Nereids Planner)"] =~
/stats=(\p{Nd}+(?:[.,'’\p{Zs}\u066b\u066c]\p{Nd}+)*)/
+ assertTrue(stats.find(), "Missing row estimate for ${operator} in
${node}")
+ // EXPLAIN uses localized groups of three digits and up to two
fractional digits.
+ def parts = stats.group(1).split(/[^\p{Nd}]+/).toList()
+ if (parts.size() > 1 && parts.last().length() <= 2) {
+ return (parts[0..-2].join("") + "." + parts.last()) as BigDecimal
+ }
+ return parts.join("") as BigDecimal
+ }
+ // Check the column distribution against the estimate chosen for this
snapshot.
+ def scanRows = rowEstimate("PhysicalOlapScan")
+ def filterRows = rowEstimate("PhysicalFilter")
+ assertTrue(scanRows > 0, "Expected a positive snapshot scan estimate in
${plan}")
+ qt_snapshot_null_selectivity "SELECT CAST(${filterRows} / ${scanRows} AS
DECIMAL(3, 2))"
+
+ order_qt_dup_snapshot "SELECT id, v FROM stream_col_stats_dup_s@snapshot()"
+ order_qt_dup_delta "SELECT id, v FROM stream_col_stats_dup_s"
+ order_qt_dup_reset "SELECT id, v FROM stream_col_stats_dup_s@reset()"
+ order_qt_unique_snapshot "SELECT id, v FROM
stream_col_stats_unique_s@snapshot()"
+ order_qt_unique_delta "SELECT id, v, __DORIS_STREAM_CHANGE_TYPE_COL__ FROM
stream_col_stats_unique_s"
+ order_qt_unique_reset "SELECT id, v FROM stream_col_stats_unique_s@reset()"
+ sql "SET enable_runtime_filter_prune=true"
+ order_qt_snapshot_join """
+ SELECT d.id, d.v, u.v
+ FROM stream_col_stats_dup_s@snapshot() d
+ LEFT JOIN stream_col_stats_unique_s@snapshot() u ON d.id = u.id
+ """
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]