englefly commented on code in PR #70564:
URL: https://github.com/apache/doris/pull/70564#discussion_r4674828120


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java:
##########
@@ -535,142 +543,246 @@ private Optional<String> checkNdvValidation(OlapScan 
olapScan, double rowCount)
         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);

Review Comment:
   **[P2] 基表的旧取值范围会把有匹配行的快照过滤估成 0 行**
   
   例如,DUP 表在 `max(v)=10` 时完成 `ANALYZE`,随后写入 `v=20`,再创建 
`show_initial_rows=false` 的 stream。`SELECT v FROM s@snapshot() WHERE v=20` 
能读到新写入的行,但这里换算后的列统计仍保留 `max(v)=10`。`FilterEstimation` 把范围外的等值谓词估成 0 行,而 stream 
分支也跳过了 `deltaRowCount` 重估,导致下游 Join 收到 0 行的估算。
   
   建议在缺少与扫描 offset 对应的范围统计时,保留换算后的 NDV 和 NULL 数,并让这类范围外谓词使用非零的回退估算。



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java:
##########
@@ -535,142 +543,246 @@ private Optional<String> checkNdvValidation(OlapScan 
olapScan, double rowCount)
         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;
+    }
 
-        // 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 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;
+    }
 
-        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 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;
+    }
+
+    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 = hasUserInjectedStats(sourceTable)
+                ? Collections.emptyList() : getSelectedPartitionNames(scan, 
sourceTable);
+        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);
+        }
+    }
+
+    /**
+     * Estimate a stream/historical scan from one unmodified source 
population. The source range
+     * and NULL fraction are distribution approximations, including for 
DELETE/UPDATE_BEFORE;
+     * they are not exact historical bounds or measurements of the changed 
keys.
+     */
+    @VisibleForTesting
+    static ColumnStatistic estimateStreamColumnStatistics(ColumnStatistic 
source, double rowCount, DataType dataType) {
+        if (rowCount == 0) {
+            return new 
ColumnStatisticBuilder().setNdv(0).setNumNulls(0).setAvgSizeByte(0).build();
         }
-        return computeVirtualColumnStats(olapScan, builder.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)));
+        ColumnStatisticBuilder builder = new ColumnStatisticBuilder(source, 
rowCount)
+                .setNumNulls(numNulls)
+                .setNdv(Math.min(source.ndv, rowCount - numNulls))

Review Comment:
   **[P2] 浮点舍入会把小流批次的 NULL 估算放大**
   
   例如,源统计为 1,000 行、1 个 NULL、NDV 999,本次扫描估算 10 行。这里得到 
`numNulls=0.01`、`ndv=9.99`,但 `Statistics.enforceValid()` 检查 `numNulls <= 
rowCount - ndv` 时,右侧实际是 `0.009999999999999787`。校验失败后,`Math.max(1, ...)` 把 NULL 
数抬到 1,所以上层 `v IS NULL` 的行数估算会从 0.01 放大到 1。
   
   建议让换算结果与下游的浮点边界检查一致,并补一个先执行 `enforceValid()`、再估算 `IS NULL` 的用例。



-- 
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]

Reply via email to