This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 4a3ee3c4ec3 branch-4.2 [improvement](statistics) Backport sample 
analyze hot-value changes (#69209, #69225) (#71345)
4a3ee3c4ec3 is described below

commit 4a3ee3c4ec3561218a8705ae1ff9a3ae04cf86be
Author: minghong <[email protected]>
AuthorDate: Fri Dec 4 14:16:34 2026 +0800

    branch-4.2 [improvement](statistics) Backport sample analyze hot-value 
changes (#69209, #69225) (#71345)
    
    ### Background
    
    Doris chooses a sampling estimator for each column. The linear estimator
    previously ran an extra aggregation over the sample to collect hot
    values, including when an OLAP sample fell back to a full scan. DUJ1
    already groups the sample for its NDV estimate and can reuse those
    groups.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: #69209 (remove hot-value aggregation from the linear
    estimator), #69225 (accept `WITH HOT VALUE` on sample analyze)
    
    PR Type: Enhancement
    
    Problem Summary:
    
    Backport both changes to `branch-4.2`. The linear estimator returns a
    NULL `hot_value` in the existing result column. DUJ1 continues to
    collect hot values from its grouped sample. Table and database `ANALYZE`
    commands accept `WITH SAMPLE ... WITH HOT VALUE`, with hot-value
    collection still determined by the estimator.
    
    ### Details
    
    - **Before and after** — Linear sampling avoids an extra pass over the
    sample. Accepting the options together lets callers use the same syntax
    for both estimators.
    - **Configs and defaults** — Uses the existing hot-value collection
    setting for DUJ1 and the explicit full-analyze path.
    - **Impact on existing users** — Use a full analyze with `WITH HOT
    VALUE` to collect hot values for a column that uses the linear estimator
    when sampled. Partition-level analysis still uses its existing
    per-partition statistics.
    
    ### Testing
    
    - FE Checkstyle and `git diff --check` passed.
    - `./run-fe-ut.sh --run` passed all 40 tests in `HMSAnalysisTaskTest`,
    `OlapAnalysisTaskTest`, and `AnalyzeTableCommandTest`.
    - The backport includes the upstream regression updates for linear and
    DUJ1 sampling, explicit full analyze, and the aggregation plan that
    depends on hot values. Local regression verification is pending.
    
    ### Notes for Reviewers
    
    This branch implements Hive sampling in `HMSAnalysisTask`. The backport
    applies the same estimator-specific SQL parameters there and keeps the
    branch's JMockit setup in the FE tests. The linear template represents
    the missing hot-value statistics as NULL in the existing result column.
    
    ### Release note
    
    Sample analyze skips hot-value collection for columns that use the
    linear estimator. Table and database sample analyze accept `WITH HOT
    VALUE`. DUJ1 continues to collect hot values automatically.
    
    ### Check List (For Author)
    
    - Test
        - [ ] Regression test
        - [x] Unit Test
    - Behavior changed
        - [x] Yes, as described above.
    - Does this need documentation?
        - [x] No separate documentation change in this backport.
    - Pre-submission status
    - Partially verified. FE unit tests and Checkstyle passed. Regression
    verification is pending.
    
    ### Check List (For Reviewer who merge this PR)
    
    - [ ] Confirm the release note
    - [ ] Confirm test cases
    - [ ] Confirm document
    
    ### AI Disclosure
    
    - Tool: Codex.
    - Generated: 4.2 conflict resolutions, test adaptations, and this
    description.
    - Human review: Pending.
---
 .../trees/plans/commands/AnalyzeCommand.java       |  9 ++-
 .../apache/doris/statistics/BaseAnalysisTask.java  | 31 +++++----
 .../apache/doris/statistics/ColumnStatistic.java   |  3 +-
 .../apache/doris/statistics/HMSAnalysisTask.java   |  3 +-
 .../apache/doris/statistics/OlapAnalysisTask.java  | 18 +++---
 .../plans/commands/AnalyzeTableCommandTest.java    | 66 +++++++++++++++++--
 .../doris/statistics/OlapAnalysisTaskTest.java     | 67 ++++++++++++--------
 .../stats/col_stats/hot_value_analyze_sync.groovy  | 12 +++-
 .../agg_strategy/physical_agg_regulator.groovy     |  8 ++-
 .../statistics/test_full_analyze_hot_value.groovy  | 73 +++++++++++++++-------
 .../suites/statistics/test_hot_value.groovy        | 26 ++++----
 11 files changed, 217 insertions(+), 99 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeCommand.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeCommand.java
index 34323496fb4..548da3505fb 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeCommand.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeCommand.java
@@ -140,14 +140,17 @@ public abstract class AnalyzeCommand extends Command 
implements ForwardWithSync
 
     /**
      * Validate analyze command properties.
+     *
+     * <p>{@code WITH HOT VALUE} is deliberately not validated against the 
analysis method. The flag
+     * only selects the hot value template of a full analyze; a sample analyze 
collects hot values
+     * depending on the estimator it picks per column at execution time (DUJ1 
does, the linear
+     * estimator does not), which cannot be known here. The combination is 
therefore accepted, and
+     * the flag simply has no effect on a sample analyze.
      */
     public void validate(ConnectContext ctx) throws UserException {
         if (analyzeProperties != null) {
             analyzeProperties.check();
         }
-        if (analyzeProperties.hasCollectHotValue() && getAnalysisMethod() == 
AnalysisInfo.AnalysisMethod.SAMPLE) {
-            throw new AnalysisException("Sample analyze always collects hot 
value");
-        }
     }
 
 }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/statistics/BaseAnalysisTask.java 
b/fe/fe-core/src/main/java/org/apache/doris/statistics/BaseAnalysisTask.java
index c374cccbb50..b3aa85d9a35 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/BaseAnalysisTask.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/BaseAnalysisTask.java
@@ -140,6 +140,14 @@ public abstract class BaseAnalysisTask {
             + "FROM (SELECT ${colName}${lengthAssert} "
             +     "FROM ${catalogName}.${dbName}.${tblName} ${index}) __lc_t";
 
+    // Hot values are intentionally NOT collected by the linear estimator. The 
extra
+    // GROUP BY over the sampled column re-reads the whole sample and is the 
dominant cost
+    // of this template, which is used for every single distribution / single 
key column
+    // sample analyze. `hot_value` keeps its position in the result set and is 
reported as
+    // NULL, which every reader treats as "not collected" (see 
ColumnStatistic#hotValues),
+    // so the row layout stays identical to that of the other templates. Hot 
values are
+    // still collected by DUJ1_ANALYZE_TEMPLATE, which derives them from the 
grouped sample
+    // it already builds for the NDV estimate.
     protected static final String LINEAR_ANALYZE_TEMPLATE = "WITH cte1 AS ("
             +     "SELECT ${colName}${lengthAssert} "
             +     "FROM ${catalogName}.${dbName}.${tblName} ${index} 
${sampleHints} ${limit} ${preAggHint}), "
@@ -157,19 +165,10 @@ public abstract class BaseAnalysisTask {
             +     "SUBSTRING(CAST(${min} AS STRING), 1, 1024) AS `min`, "
             +     "SUBSTRING(CAST(${max} AS STRING), 1, 1024) AS `max`, "
             +     "${dataSizeFunction} * ${scaleFactor} AS `data_size`, "
-            +     "NOW() FROM cte1), "
-            + "cte3 AS ("
-            +     "SELECT IFNULL(GROUP_CONCAT(CONCAT("
-            +         "REPLACE(REPLACE(t.`column_key`, \":\", \"\\\\:\"), 
\";\", \"\\\\;\"), "
-            +         "\" :\", ROUND(t.`count` / ${rowCount2}, 2)), \" ;\"), 
'') "
-            +         "as `hot_value` "
-            +     "FROM ("
-            +         "SELECT ${subStringColName} as `hash_value`, "
-            +         "MAX(${colName}) as `column_key`, "
-            +         "COUNT(1) AS `count` "
-            +         "FROM cte1 WHERE ${colName} IS NOT NULL "
-            +         "GROUP BY `hash_value` ORDER BY `count` DESC LIMIT 
${hotValueCollectCount}) t) "
-            + "SELECT * FROM cte2 CROSS JOIN cte3";
+            +     "NOW() AS `update_time`, "
+            +     "null as `hot_value` "
+            +     "FROM cte1) "
+            + "SELECT * FROM cte2";
 
     protected static final String DUJ1_ANALYZE_TEMPLATE = "WITH cte1 AS ("
             + "SELECT MAX(t0.`col_value`) as `col_value`, COUNT(1) as `count`, 
SUM(`len`) as `column_length` "
@@ -611,6 +610,12 @@ public abstract class BaseAnalysisTask {
 
     protected abstract void deleteNotExistPartitionStats(AnalysisInfo jobInfo) 
throws DdlException;
 
+    /**
+     * Whether this task may collect hot values. It only decides which 
template a full analyze uses
+     * (with or without the hot value CTE). A sample analyze collects hot 
values only when the
+     * estimator it picked provides them, i.e. {@code DUJ1_ANALYZE_TEMPLATE}; 
the linear estimator
+     * never does, even though a sample job sets {@code collectHotValue} to 
true.
+     */
     protected boolean shouldCollectHotValue() {
         return Boolean.TRUE.equals(info.collectHotValue);
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/statistics/ColumnStatistic.java 
b/fe/fe-core/src/main/java/org/apache/doris/statistics/ColumnStatistic.java
index 8dfd8b86f1f..3b887086bc4 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/ColumnStatistic.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/ColumnStatistic.java
@@ -98,7 +98,8 @@ public class ColumnStatistic {
     public final String updatedTime;
 
     /**
-     * hotValues == null: not collected (e.g. full analyze). Do NOT use for 
optimization.
+     * hotValues == null: not collected (e.g. full analyze, or a sample 
analyze that used
+     * the linear estimator). Do NOT use for optimization.
      * hotValues != null && hotValues.isEmpty(): collected but no hot values 
(not skewed).
      * hotValues != null && !hotValues.isEmpty(): collected with hot values.
      */
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/statistics/HMSAnalysisTask.java 
b/fe/fe-core/src/main/java/org/apache/doris/statistics/HMSAnalysisTask.java
index 16bd4941223..8f26421e468 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/HMSAnalysisTask.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/HMSAnalysisTask.java
@@ -224,7 +224,6 @@ public class HMSAnalysisTask extends ExternalAnalysisTask {
         params.put("dataSizeFunction", getDataSizeFunction(col, false));
         Pair<Double, Long> sampleInfo = getSampleInfo();
         params.put("scaleFactor", String.valueOf(sampleInfo.first));
-        params.put("hotValueCollectCount", 
String.valueOf(SessionVariable.getHotValueCollectCount()));
         if (LOG.isDebugEnabled()) {
             LOG.debug("Will do sample collection for column {}", 
col.getName());
         }
@@ -252,10 +251,10 @@ public class HMSAnalysisTask extends ExternalAnalysisTask 
{
             sb.append(LINEAR_ANALYZE_TEMPLATE);
             params.put("ndvFunction", "ROUND(NDV(${colName}) * 
${scaleFactor})");
             params.put("rowCount", "ROUND(COUNT(1) * ${scaleFactor})");
-            params.put("rowCount2", "(SELECT COUNT(1) FROM cte1 WHERE 
${colName} IS NOT NULL)");
         } else {
             sb.append(DUJ1_ANALYZE_TEMPLATE);
             params.put("subStringColName", getStringTypeColName(col));
+            params.put("hotValueCollectCount", 
String.valueOf(SessionVariable.getHotValueCollectCount()));
             params.put("dataSizeFunction", getDataSizeFunction(col, true));
             params.put("ndvFunction", getNdvFunction("ROUND(SUM(t1.count) * 
${scaleFactor})"));
             params.put("rowCount", "ROUND(SUM(t1.count) * ${scaleFactor})");
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/statistics/OlapAnalysisTask.java 
b/fe/fe-core/src/main/java/org/apache/doris/statistics/OlapAnalysisTask.java
index 5b1f451004a..c9f716f3c90 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/OlapAnalysisTask.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/OlapAnalysisTask.java
@@ -119,19 +119,20 @@ public class OlapAnalysisTask extends BaseAnalysisTask {
         Map<String, String> params = buildSqlParams();
         params.put("min", StatisticsUtil.quote(min));
         params.put("max", StatisticsUtil.quote(max));
-        params.put("hotValueCollectCount", 
String.valueOf(SessionVariable.getHotValueCollectCount()));
         long tableRowCount = info.indexId == -1
                 ? tbl.getRowCount()
                 : ((OlapTable) tbl).getRowCountForIndex(info.indexId, false);
         SampleCollectInfo collectInfo = getSampleCollectInfo(tableRowCount);
         getSampleParams(params, tableRowCount, collectInfo);
-        StringSubstitutor stringSubstitutor = new StringSubstitutor(params);
-        String sql;
+        String template = LINEAR_ANALYZE_TEMPLATE;
         if (collectInfo.algorithm == AnalyzeSampleAlgorithm.DUJ1) {
-            sql = stringSubstitutor.replace(DUJ1_ANALYZE_TEMPLATE);
-        } else {
-            sql = stringSubstitutor.replace(LINEAR_ANALYZE_TEMPLATE);
+            // DUJ1 is the only sample algorithm that collects hot values, and 
it derives them
+            // from the grouped sample it already builds for the NDV estimate, 
so only it needs
+            // the top-N count.
+            params.put("hotValueCollectCount", 
String.valueOf(SessionVariable.getHotValueCollectCount()));
+            template = DUJ1_ANALYZE_TEMPLATE;
         }
+        String sql = new StringSubstitutor(params).replace(template);
         LOG.info("Analyze param: algorithm {}, partitionColumnTooMany {}, 
keyColumnTooMany {}",
                 collectInfo.algorithm, partitionColumnSampleTooManyRows, 
keyColumnSampleTooManyRows);
         LOG.debug(sql);
@@ -307,7 +308,6 @@ public class OlapAnalysisTask extends BaseAnalysisTask {
         params.put("rowCount", String.valueOf(tableRowCount));
         params.put("type", col.getType().toString());
         params.put("limit", "");
-        params.put("subStringColName", getStringTypeColName(col));
 
         // For agg table and mor unique table, set PREAGGOPEN preAggHint.
         if (((OlapTable) tbl).getKeysType().equals(KeysType.AGG_KEYS)
@@ -357,11 +357,13 @@ public class OlapAnalysisTask extends BaseAnalysisTask {
     protected void setSampleParamsByAlgorithm(Map<String, String> params, long 
tableRowCount,
             AnalyzeSampleAlgorithm algorithm) {
         if (algorithm == AnalyzeSampleAlgorithm.DUJ1) {
+            // DUJ1 is the only sample algorithm that collects hot values: it 
derives them from
+            // the grouped sample it already builds for the NDV estimate below.
+            params.put("subStringColName", getStringTypeColName(col));
             params.put("ndvFunction", 
getNdvFunction(String.valueOf(tableRowCount)));
             params.put("dataSizeFunction", getDataSizeFunction(col, true));
             params.put("rowCount2", "(SELECT SUM(`count`) FROM cte1 WHERE 
`col_value` IS NOT NULL)");
         } else {
-            params.put("rowCount2", "(SELECT COUNT(1) FROM cte1 WHERE 
${colName} IS NOT NULL)");
             // For single unique key, use count as ndv.
             if (isSingleUniqueKey()) {
                 params.put("ndvFunction", String.valueOf(tableRowCount));
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeTableCommandTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeTableCommandTest.java
index a5f16003984..6ae0c1d27ba 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeTableCommandTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/AnalyzeTableCommandTest.java
@@ -19,8 +19,12 @@ package org.apache.doris.nereids.trees.plans.commands;
 
 import org.apache.doris.analysis.AnalyzeProperties;
 import org.apache.doris.backup.CatalogMocker;
+import org.apache.doris.catalog.DatabaseIf;
 import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.TableIf;
 import org.apache.doris.common.AnalysisException;
+import org.apache.doris.datasource.CatalogIf;
+import org.apache.doris.datasource.CatalogMgr;
 import org.apache.doris.datasource.InternalCatalog;
 import org.apache.doris.info.PartitionNamesInfo;
 import org.apache.doris.info.TableNameInfo;
@@ -32,6 +36,7 @@ import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.statistics.AnalysisInfo;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
 import mockit.Expectations;
 import mockit.Mocked;
 import org.junit.jupiter.api.Assertions;
@@ -132,13 +137,66 @@ public class AnalyzeTableCommandTest {
     }
 
     @Test
-    void testSampleAnalyzeWithHotValueRejected() {
+    void testSampleAnalyzeWithHotValueAccepted(@Mocked CatalogMgr catalogMgr, 
@Mocked CatalogIf catalog,
+            @Mocked DatabaseIf database, @Mocked TableIf table) throws 
AnalysisException {
+        // WITH HOT VALUE is accepted on a sample analyze: the flag only 
selects the hot value
+        // template of a full analyze, while a sample analyze collects hot 
values depending on the
+        // estimator it picks per column at execution time.
+        new Expectations() {
+            {
+                ctx.getEnv();
+                result = env;
+                env.getCatalogMgr();
+                result = catalogMgr;
+                catalogMgr.getCatalogOrAnalysisException(internalCtl);
+                result = catalog;
+                catalog.getDbOrAnalysisException(CatalogMocker.TEST_DB_NAME);
+                result = database;
+                
database.getTableOrAnalysisException(CatalogMocker.TEST_TBL_NAME);
+                result = table;
+                ConnectContext.get();
+                result = ctx;
+                Env.getCurrentEnv();
+                result = env;
+                env.getAccessManager();
+                result = accessManager;
+                accessManager.checkTblPriv(ctx, internalCtl, 
CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME,
+                        PrivPredicate.SELECT);
+                result = true;
+                table.getSchemaAllIndexes(false);
+                result = ImmutableSet.of();
+            }
+        };
+
         NereidsParser parser = new NereidsParser();
         AnalyzeTableCommand command = (AnalyzeTableCommand) parser.parseSingle(
                 "ANALYZE TABLE test_db.test_tbl WITH SAMPLE ROWS 100 WITH HOT 
VALUE");
-        AnalysisException exception = 
Assertions.assertThrows(AnalysisException.class,
-                () -> command.validate(ctx));
-        Assertions.assertEquals("Sample analyze always collects hot value", 
exception.getDetailMessage());
+        Assertions.assertDoesNotThrow(() -> command.validate(ctx));
+        
Assertions.assertTrue(command.getAnalyzeProperties().hasCollectHotValue());
+        Assertions.assertEquals(AnalysisInfo.AnalysisMethod.SAMPLE, 
command.getAnalysisMethod());
+    }
+
+    @Test
+    void testSampleAnalyzeDatabaseWithHotValueAccepted(@Mocked CatalogIf 
catalog, @Mocked DatabaseIf database)
+            throws AnalysisException {
+        // The rejection lived in the validate shared by both commands, so 
ANALYZE DATABASE accepts
+        // the flag as well.
+        new Expectations() {
+            {
+                Env.getCurrentEnv();
+                result = env;
+                env.getCurrentCatalog();
+                result = catalog;
+                catalog.getDbOrAnalysisException(CatalogMocker.TEST_DB_NAME);
+                result = database;
+            }
+        };
+
+        NereidsParser parser = new NereidsParser();
+        AnalyzeDatabaseCommand command = (AnalyzeDatabaseCommand) 
parser.parseSingle(
+                "ANALYZE DATABASE test_db WITH SAMPLE ROWS 100 WITH HOT 
VALUE");
+        Assertions.assertDoesNotThrow(() -> command.validate(ctx));
+        Assertions.assertEquals(AnalysisInfo.AnalysisMethod.SAMPLE, 
command.getAnalysisMethod());
     }
 
     private Map<String, String> defaultAnalyzeProperties() {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/statistics/OlapAnalysisTaskTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/statistics/OlapAnalysisTaskTest.java
index 26aacda24ab..f7418abce38 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/statistics/OlapAnalysisTaskTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/statistics/OlapAnalysisTaskTest.java
@@ -191,13 +191,8 @@ public class OlapAnalysisTaskTest {
                         + "ROUND(SUM(CASE WHEN `null` IS NULL THEN 1 ELSE 0 
END) * ${scaleFactor}) AS `null_count`, "
                         + "SUBSTRING(CAST('1' AS STRING), 1, 1024) AS `min`, "
                         + "SUBSTRING(CAST('2' AS STRING), 1, 1024) AS `max`, "
-                        + "COUNT(1) * 4 * ${scaleFactor} AS `data_size`, NOW() 
FROM cte1), "
-                        + "cte3 AS (SELECT 
IFNULL(GROUP_CONCAT(CONCAT(REPLACE(REPLACE(t.`column_key`, "
-                        + "\":\", \"\\\\:\"), \";\", \"\\\\;\"), \" :\", 
ROUND(t.`count` / ${rowCount2}, 2)), "
-                        + "\" ;\"), '') as `hot_value` FROM (SELECT 
${subStringColName} as `hash_value`, "
-                        + "MAX(`null`) as `column_key`, COUNT(1) AS `count` 
FROM cte1 "
-                        + "WHERE `null` IS NOT NULL GROUP BY `hash_value` 
ORDER BY `count` DESC LIMIT 10) t) "
-                        + "SELECT * FROM cte2 CROSS JOIN cte3", sql);
+                        + "COUNT(1) * 4 * ${scaleFactor} AS `data_size`, NOW() 
AS `update_time`, "
+                        + "null as `hot_value` FROM cte1) SELECT * FROM cte2", 
sql);
             }
         };
 
@@ -416,8 +411,9 @@ public class OlapAnalysisTaskTest {
                 new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.FULL, null));
         Assertions.assertEquals("1", params.get("scaleFactor"));
         Assertions.assertEquals("", params.get("sampleHints"));
-        Assertions.assertEquals("(SELECT COUNT(1) FROM cte1 WHERE ${colName} 
IS NOT NULL)",
-                params.get("rowCount2"));
+        // The linear estimator does not collect hot values, so it fills no 
hot value param.
+        Assertions.assertNull(params.get("rowCount2"));
+        Assertions.assertNull(params.get("subStringColName"));
         Assertions.assertEquals("ROUND(NDV(${colName}) * ${scaleFactor})", 
params.get("ndvFunction"));
         Assertions.assertNull(params.get("preAggHint"));
         Assertions.assertEquals("COUNT(1)", params.get("rowCount"));
@@ -428,8 +424,8 @@ public class OlapAnalysisTaskTest {
                 new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.LINEAR,
                         Pair.of(Lists.newArrayList(1L, 2L), 100L)));
         Assertions.assertEquals("TABLET(1, 2)", params.get("sampleHints"));
-        Assertions.assertEquals("(SELECT COUNT(1) FROM cte1 WHERE ${colName} 
IS NOT NULL)",
-                params.get("rowCount2"));
+        Assertions.assertNull(params.get("rowCount2"));
+        Assertions.assertNull(params.get("subStringColName"));
         Assertions.assertEquals("ROUND(NDV(${colName}) * ${scaleFactor})", 
params.get("ndvFunction"));
         params.clear();
 
@@ -442,6 +438,7 @@ public class OlapAnalysisTaskTest {
         Assertions.assertEquals("TABLET(1, 2)", params.get("sampleHints"));
         Assertions.assertEquals("(SELECT SUM(`count`) FROM cte1 WHERE 
`col_value` IS NOT NULL)",
                 params.get("rowCount2"));
+        Assertions.assertEquals("${colName}", params.get("subStringColName"));
         
Assertions.assertTrue(params.get("ndvFunction").contains("`t1`.`col_value`"),
                 "DUJ1 ndvFunction must reference cte1 output, got: " + 
params.get("ndvFunction"));
         params.clear();
@@ -1157,7 +1154,7 @@ public class OlapAnalysisTaskTest {
     }
 
     @Test
-    public void testDoSampleAlwaysCollectsHotValue() throws Exception {
+    public void testDoSampleHotValueByAlgorithm() throws Exception {
         CatalogIf catalogIf = Mockito.mock(CatalogIf.class);
         DatabaseIf databaseIf = Mockito.mock(DatabaseIf.class);
         OlapTable tableIf = Mockito.mock(OlapTable.class);
@@ -1173,16 +1170,6 @@ public class OlapAnalysisTaskTest {
         Mockito.doReturn(new ResultRow(Lists.newArrayList("1", 
"2"))).when(task).collectMinMax();
         Mockito.doNothing().when(task).getSampleParams(ArgumentMatchers.any(), 
ArgumentMatchers.anyLong(),
                 ArgumentMatchers.any());
-        Mockito.doAnswer(invocation -> {
-            String sql = invocation.getArgument(0);
-            Assertions.assertTrue(sql.contains("as `hot_value`"), sql);
-            Assertions.assertTrue(sql.contains("cte3"), sql);
-            Assertions.assertTrue(sql.contains("CROSS JOIN cte3"), sql);
-            Assertions.assertTrue(sql.contains("LIMIT 10"), sql);
-            Assertions.assertFalse(sql.contains("null as `hot_value`"), sql);
-            return null;
-        }).when(task).runQuery(Mockito.anyString());
-
         task.col = new Column("testCol", 
Type.fromPrimitiveType(PrimitiveType.INT),
                 true, null, null, null);
         task.tbl = tableIf;
@@ -1195,11 +1182,39 @@ public class OlapAnalysisTaskTest {
         task.db = databaseIf;
         task.tableSample = new TableSample(false, 100L);
 
-        Mockito.doReturn(new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.LINEAR, null))
-                .when(task).getSampleCollectInfo(ArgumentMatchers.anyLong());
+        // The linear estimator does not collect hot values: the extra GROUP 
BY over the sampled
+        // column is the dominant cost of LINEAR_ANALYZE_TEMPLATE.
+        Mockito.doAnswer(invocation -> {
+            String sql = invocation.getArgument(0);
+            Assertions.assertTrue(sql.contains("null as `hot_value`"), sql);
+            Assertions.assertFalse(sql.contains("cte3"), sql);
+            Assertions.assertFalse(sql.contains("CROSS JOIN cte3"), sql);
+            Assertions.assertFalse(sql.contains("GROUP BY `hash_value`"), sql);
+            // The linear template carries no hot value placeholder at all. 
Which params each
+            // algorithm fills is pinned by testGetSampleParams.
+            Assertions.assertFalse(sql.contains("${hotValueCollectCount}"), 
sql);
+            Assertions.assertFalse(sql.contains("${subStringColName}"), sql);
+            Assertions.assertFalse(sql.contains("${rowCount2}"), sql);
+            return null;
+        }).when(task).runQuery(Mockito.anyString());
+        Mockito.doReturn(new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.LINEAR,
+                Pair.of(Lists.newArrayList(1L, 2L), 100L)))
+                .when(task).getSampleCollectInfo(Mockito.anyLong());
         task.doSample();
-        Mockito.doReturn(new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.DUJ1, null))
-                .when(task).getSampleCollectInfo(ArgumentMatchers.anyLong());
+
+        // DUJ1 still collects hot values: it derives them from the grouped 
sample it already
+        // builds for the NDV estimate.
+        Mockito.doAnswer(invocation -> {
+            String sql = invocation.getArgument(0);
+            Assertions.assertTrue(sql.contains("as `hot_value`"), sql);
+            Assertions.assertTrue(sql.contains("CROSS JOIN cte3"), sql);
+            Assertions.assertTrue(sql.contains("LIMIT 10"), sql);
+            Assertions.assertFalse(sql.contains("null as `hot_value`"), sql);
+            return null;
+        }).when(task).runQuery(Mockito.anyString());
+        Mockito.doReturn(new 
OlapAnalysisTask.SampleCollectInfo(AnalyzeSampleAlgorithm.DUJ1,
+                Pair.of(Lists.newArrayList(1L, 2L), 100L)))
+                .when(task).getSampleCollectInfo(Mockito.anyLong());
         task.doSample();
     }
 
diff --git 
a/regression-test/suites/nereids_p0/stats/col_stats/hot_value_analyze_sync.groovy
 
b/regression-test/suites/nereids_p0/stats/col_stats/hot_value_analyze_sync.groovy
index 39c43134ab7..8ebc437890e 100644
--- 
a/regression-test/suites/nereids_p0/stats/col_stats/hot_value_analyze_sync.groovy
+++ 
b/regression-test/suites/nereids_p0/stats/col_stats/hot_value_analyze_sync.groovy
@@ -49,10 +49,16 @@ suite('hot_value_analyze_sync') {
     String realDb = context.config.getDbNameByFile(context.file)
     sql """
     drop table if exists t1025;
-    create table t1025(a_1 int, b_5 int, c_10 int, d_1025 int) distributed by 
hash(c_10) properties('replication_num'='1');
-    insert into t1025 select 1, number%5 , number%10, number from 
numbers("number"="100");
+    create table t1025(a_1 int, b_5 int, c_10 int, d_1025 int) distributed by 
hash(c_10) buckets 1 properties('replication_num'='1');
+    insert into t1025 select 1, number%5 , number%10, number from 
numbers("number"="10000");
     """
-    wait_row_count_reported(realDb, "t1025", 0, 4, "100")
+    wait_row_count_reported(realDb, "t1025", 0, 4, "10000")
+    // One bucket, so sample analyze is guaranteed to sample instead of 
falling back to a full scan:
+    // getSampleCollectInfo falls back when the sample request exceeds the 
table, or when the picked
+    // tablets hold fewer rows than requested, and both fallbacks use the 
linear estimator for every
+    // column, which does not collect hot value (`null as hot_value`). d_1025 
is not the distribution
+    // column, so a real sample analyzes it with the DUJ1 estimator, which 
does collect hot value -
+    // the property this suite exists to check.
     sql "analyze table t1025 with sample rows 4000 with sync;"
     def result = sql "show column cached stats t1025"
     log.info(result.toString())
diff --git 
a/regression-test/suites/nereids_rules_p0/agg_strategy/physical_agg_regulator.groovy
 
b/regression-test/suites/nereids_rules_p0/agg_strategy/physical_agg_regulator.groovy
index 7b9f2c04f9a..39027faa3ae 100644
--- 
a/regression-test/suites/nereids_rules_p0/agg_strategy/physical_agg_regulator.groovy
+++ 
b/regression-test/suites/nereids_rules_p0/agg_strategy/physical_agg_regulator.groovy
@@ -22,8 +22,11 @@ suite("physical_agg_regulator") {
     set enable_parallel_result_sink=false;
     set be_number_for_test=1;
     """
+    // A sample request larger than the table falls back to a full scan with 
the linear estimator,
+    // which does not collect hot value. This case needs hot value to exercise 
the skew-aware
+    // aggregation shape, so ask for it explicitly instead of relying on the 
sample path.
     multi_sql """
-    analyze table t1025_skew5000 with sample rows 7000 with sync;
+    analyze table t1025_skew5000 with sync with hot value;
     --drop cached stats t1025;
     """
     // 这个预期应该使用cte之后any
@@ -31,8 +34,9 @@ suite("physical_agg_regulator") {
     select count(distinct a_1), count(distinct b_5) from t1025_skew5000 group 
by d_1025;"""
 
 
+    // Same reason as above: this table's plan expectations were built on 
collected hot values.
     multi_sql """
-    analyze table t1025 with sample rows 4000 with sync;
+    analyze table t1025 with sync with hot value;
     --drop cached stats t1025;
     """
     qt_not_skew """explain shape plan
diff --git 
a/regression-test/suites/statistics/test_full_analyze_hot_value.groovy 
b/regression-test/suites/statistics/test_full_analyze_hot_value.groovy
index ad7df099e8d..14928393224 100644
--- a/regression-test/suites/statistics/test_full_analyze_hot_value.groovy
+++ b/regression-test/suites/statistics/test_full_analyze_hot_value.groovy
@@ -133,42 +133,67 @@ suite("test_full_analyze_hot_value") {
     // All 100 rows have the same value " : ;a", so it should appear with 
ratio 1.0
     assertEquals("' : ;a':1.0", result[0][17])
 
-    // Test 5: Sample analyze collects hot_value by default.
+    // Test 5: A sample analyze whose sample request exceeds the table row 
count falls back to a
+    // full scan and uses the linear estimator, which does not collect 
hot_value.
     sql """drop stats full_hot_skew"""
     sql """analyze table full_hot_skew with sample rows 400 with sync"""
     result = sql """show column stats full_hot_skew(value1)"""
     logger.info("Test5 result: " + result)
     assertEquals(1, result.size())
-    assertTrue(result[0][17].contains(":"), "Sample analyze should also 
collect hot_value")
-    hotValues = result[0][17].split(";")
-    assertEquals(2, hotValues.length)
-    assertTrue(hotValues[0].trim() == "'1':0.5" || hotValues[0].trim() == 
"'0':0.5")
-    assertTrue(hotValues[1].trim() == "'1':0.5" || hotValues[1].trim() == 
"'0':0.5")
-
-    // Test 6: Sample analyze rejects WITH HOT VALUE because it always 
collects hot_value.
-    test {
-        sql """analyze table full_hot_skew with sample rows 400 with sync with 
hot value"""
-        exception "Sample analyze always collects hot value"
-    }
+    assertEquals("null", String.valueOf(result[0][17]))
 
-    // Test 7: Explicit full analyze produces same hot_value as sample analyze 
for same data.
+    // Test 6: WITH HOT VALUE is accepted on a sample analyze and has no 
effect here: hot values are
+    // collected only for the columns the DUJ1 estimator serves, and 
full_hot_skew is small enough
+    // that its sample analyze falls back to a full scan (rendered with the 
linear template), which
+    // does not collect them.
     sql """drop stats full_hot_skew"""
-    sql """analyze table full_hot_skew with sync with hot value"""
-    def fullResult = sql """show column stats full_hot_skew(value1)"""
+    sql """analyze table full_hot_skew with sample rows 400 with sync with hot 
value"""
+    result = sql """show column stats full_hot_skew(value1)"""
+    logger.info("Test6 result: " + result)
+    assertEquals(1, result.size())
+    assertEquals("null", String.valueOf(result[0][17]))
+
+    // Test 7: Explicit full analyze produces the same hot_value as a sample 
analyze that really
+    // samples. The column value is uniform, so the sampled rows always carry 
the same
+    // distribution as the whole table, and the table is larger than the 
requested sample rows,
+    // so sample analyze uses the DUJ1 estimator instead of falling back to a 
full scan.
+    sql """drop table if exists full_hot_sample_agree"""
+    sql """CREATE TABLE full_hot_sample_agree (
+            key1 int NULL,
+            value1 varchar(50) NULL
+        )ENGINE=OLAP
+        DUPLICATE KEY(`key1`)
+        COMMENT "OLAP"
+        DISTRIBUTED BY HASH(`key1`) BUCKETS 2
+        PROPERTIES (
+            "replication_num" = "1"
+        )
+    """
+    sql """insert into full_hot_sample_agree select number, " : ;a" from 
numbers("number"="10000")"""
+    wait_row_count_reported("test_full_analyze_hot_value", 
"full_hot_sample_agree", 0, 4, "10000")
+
+    sql """analyze table full_hot_sample_agree with sync with hot value"""
+    def fullResult = sql """show column stats full_hot_sample_agree(value1)"""
     logger.info("Test7 full result: " + fullResult)
     assertEquals(1, fullResult.size())
-    assertTrue(fullResult[0][17].contains(":"))
-    def fullParts = fullResult[0][17].split(";").collect { it.trim() }.sort()
+    assertEquals("' : ;a':1.0", fullResult[0][17])
 
-    sql """drop stats full_hot_skew"""
-    sql """analyze table full_hot_skew with sample rows 40000 with sync"""
-    def sampleResult = sql """show column stats full_hot_skew(value1)"""
+    sql """drop stats full_hot_sample_agree"""
+    sql """analyze table full_hot_sample_agree with sample rows 400 with 
sync"""
+    def sampleResult = sql """show column stats 
full_hot_sample_agree(value1)"""
     logger.info("Test7 sample result: " + sampleResult)
     assertEquals(1, sampleResult.size())
-    assertTrue(sampleResult[0][17].contains(":"))
-    // Both full and sample should produce the same hot_value entries (order 
may differ)
-    def sampleParts = sampleResult[0][17].split(";").collect { it.trim() 
}.sort()
-    assertEquals(fullParts, sampleParts)
+    // Both full and sample should produce the same hot_value entry.
+    assertEquals(fullResult[0][17], sampleResult[0][17])
+
+    // WITH HOT VALUE is accepted on a sample analyze and does not interfere 
with the estimator:
+    // this table really samples, so DUJ1 still collects the hot value.
+    sql """drop stats full_hot_sample_agree"""
+    sql """analyze table full_hot_sample_agree with sample rows 400 with sync 
with hot value"""
+    result = sql """show column stats full_hot_sample_agree(value1)"""
+    logger.info("Test7 sample with hot value result: " + result)
+    assertEquals(1, result.size())
+    assertEquals("' : ;a':1.0", result[0][17])
 
     // Test 8: Explicit full analyze on empty table should produce an empty 
hot_value string.
     sql """drop table if exists full_hot_empty"""
diff --git a/regression-test/suites/statistics/test_hot_value.groovy 
b/regression-test/suites/statistics/test_hot_value.groovy
index e61686ec3c9..d22b9a52577 100644
--- a/regression-test/suites/statistics/test_hot_value.groovy
+++ b/regression-test/suites/statistics/test_hot_value.groovy
@@ -117,6 +117,9 @@ suite("test_hot_value") {
     logger.info("result " + result)
     assertEquals(1, result.size())
     assertEquals("10000.0", result[0][2])
+    // key1 is the single distribution column, so a real sample analyzes it 
with the linear
+    // estimator, which does not collect hot_value.
+    assertEquals("null", String.valueOf(result[0][17]))
     result = sql """show column stats test1(value1)"""
     logger.info("1. result " + result)
     assertEquals(1, result.size())
@@ -136,29 +139,24 @@ suite("test_hot_value") {
     assertTrue(hotValues[1] == "'1':0.5" || hotValues[1] == "'0':0.5")
 
     sql """drop stats test1"""
+    // The requested sample rows are larger than the table, so sample analyze 
falls back to a
+    // full scan with the linear estimator, which does not collect hot_value.
     sql """analyze table test1 with sample rows 40000 with sync"""
     result = sql """show column stats test1(key1)"""
     logger.info("result " + result)
     assertEquals(1, result.size())
     assertEquals("10000.0", result[0][2])
+    assertEquals("null", String.valueOf(result[0][17]))
     result = sql """show column stats test1(value1)"""
     logger.info("2. result " + result)
-    logger.info("result.size()" + result.size())
     assertEquals(1, result.size())
-    logger.info("result[0][2] " + result[0][2])
     assertEquals("10000.0", result[0][2])
-    hotValues = result[0][17].split(";")
-    assertEquals(2, hotValues.length)
-    assertTrue(hotValues[0] == "'1':0.5" || hotValues[0] == "'0':0.5")
-    assertTrue(hotValues[1] == "'1':0.5" || hotValues[1] == "'0':0.5")
+    assertEquals("null", String.valueOf(result[0][17]))
     result = sql """show column cached stats test1(value1)"""
     logger.info("result " + result)
     assertEquals(1, result.size())
     assertEquals("10000.0", result[0][2])
-    hotValues = result[0][17].split(";")
-    assertEquals(2, hotValues.length)
-    assertTrue(hotValues[0] == "'1':0.5" || hotValues[0] == "'0':0.5")
-    assertTrue(hotValues[1] == "'1':0.5" || hotValues[1] == "'0':0.5")
+    assertEquals("null", String.valueOf(result[0][17]))
 
     sql """alter table test1 modify column value1 set stats 
('row_count'='100.0', 'ndv'='5.0', 'num_nulls'='0.0', 'data_size'='34.0', 
'min_value'='AFRICA', 'max_value'='MIDDLE EAST', 'hot_values'='aaa :0.8');"""
     result = sql """show column stats test1(value1)"""
@@ -203,13 +201,15 @@ suite("test_hot_value") {
     assertEquals("' : ;a':1.0", result[0][17])
 
     sql """drop stats test2"""
+    // As for test1 above, the requested sample rows are larger than the 
table, so sample analyze
+    // falls back to a full scan with the linear estimator, which does not 
collect hot_value.
     sql """analyze table test2 with sample rows 4000000 with sync"""
     result = sql """show column stats test2(value1)"""
     assertEquals(1, result.size())
-    assertEquals("' : ;a':1.0", result[0][17])
-    result = sql """show column cached stats test2(value1)"""   
+    assertEquals("null", String.valueOf(result[0][17]))
+    result = sql """show column cached stats test2(value1)"""
     assertEquals(1, result.size())
-    assertEquals("' : ;a':1.0", result[0][17])
+    assertEquals("null", String.valueOf(result[0][17]))
 
     sql """drop database if exists test_hot_value"""
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to