github-actions[bot] commented on code in PR #62501:
URL: https://github.com/apache/doris/pull/62501#discussion_r3114737052


##########
fe/fe-core/src/main/java/org/apache/doris/cloud/CacheHotspotManager.java:
##########
@@ -904,4 +1137,69 @@ public void replayCloudWarmUpJob(CloudWarmUpJob 
cloudWarmUpJob) throws Exception
         }
     }
 
+    /**
+     * Resolve glob-based ON TABLES filter to a map of matching table ID → 
"db.table" name
+     * by iterating all databases and tables in the internal catalog.
+     */
+    public Map<Long, String> resolveTableIds(OnTablesFilter filter) {

Review Comment:
   `getTableNamesOrEmptyWithLock()` returns every catalog entry name here, and 
we never filter the resolved object type. That means ordinary VIEWs can satisfy 
the initial `ON TABLES` match check and show up in `MatchedTables` even though 
load-driven warmup is only triggered from BE rowset writes. A job like `ON 
TABLES (INCLUDE 'db.v_*')` can be accepted with only views matched and then 
never warm anything. We should restrict this to writable types (`OlapTable` / 
MTMV) before adding the ID.



##########
be/src/service/http/action/warmup_stats_action.cpp:
##########
@@ -0,0 +1,99 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "service/http/action/warmup_stats_action.h"
+
+#include <list>
+#include <set>
+#include <string>
+
+#include "cloud/cloud_warmup_metrics.h"
+#include "service/http/http_channel.h"
+#include "service/http/http_headers.h"
+#include "service/http/http_request.h"
+#include "service/http/http_status.h"
+#include "util/easy_json.h"
+
+namespace doris {
+
+// Fill windowed num/size metrics into a JSON object
+static void fill_windowed(EasyJson& parent, const std::string& key, 
MBvarWindowedAdder& num_adder,
+                          MBvarWindowedAdder& size_adder, const std::string& 
dim_key) {
+    EasyJson obj = parent.Set(key, EasyJson::kObject);
+    EasyJson num = obj.Set("num", EasyJson::kObject);
+    num["5m"] = num_adder.get_window_value(dim_key, 0);
+    num["30m"] = num_adder.get_window_value(dim_key, 1);
+    num["1h"] = num_adder.get_window_value(dim_key, 2);
+    EasyJson size = obj.Set("size", EasyJson::kObject);
+    size["5m"] = size_adder.get_window_value(dim_key, 0);
+    size["30m"] = size_adder.get_window_value(dim_key, 1);
+    size["1h"] = size_adder.get_window_value(dim_key, 2);
+}
+
+void WarmUpStatsAction::handle(HttpRequest* req) {
+    // Collect all job_id dimension keys from all metrics
+    std::set<std::string> all_keys;
+    for (auto& k : g_warmup_ed_requested_segment_num.list_dimensions()) 
all_keys.insert(k);

Review Comment:
   `all_keys` is discovered only from the segment counters. When 
`file_cache_enable_only_warm_up_idx=true`, target BEs never touch the segment 
metrics but they still emit index finish/fail metrics, so the job disappears 
from `/api/warmup_event_driven_stats` entirely on the target side. FE then 
aggregates zero finish/fail for a successful index-only warmup. Please union 
the dimension keys from the index metrics too.



##########
be/src/cloud/cloud_warm_up_manager.cpp:
##########
@@ -628,26 +684,30 @@ Status CloudWarmUpManager::_do_warm_up_rowset(RowsetMeta& 
rs_meta,
     g_file_cache_warm_up_rowset_last_call_unix_ts.set_value(now_ts);
     auto ret_st = Status::OK();
 

Review Comment:
   Now that `replicas` can contain entries for multiple warmup jobs / 
destinations, this loop needs to be best-effort per entry. The existing 
`cntl.Failed()` branch later in the function still returns immediately, so one 
transient BRPC failure on the first destination skips every later job in this 
loop. That breaks the advertised multi-destination independence. We should 
record the error in `ret_st` and continue fan-out to the remaining entries.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/WarmUpClusterCommand.java:
##########
@@ -203,6 +230,24 @@ public void validate(ConnectContext connectContext) throws 
UserException {

Review Comment:
   This validation block never rejects `WITH TABLE ... ON TABLES (...)`. The 
grammar accepts that combination, but `CacheHotspotManager.createJob()` takes 
the `isWarmUpWithTable()` branch first and ignores `onTablesRules`, so a 
statement that looks like filtered event-driven warmup is executed as a 
one-shot explicit-table job instead. Please reject the combination here (or 
define and implement the combined semantics) so we don't silently run the wrong 
job type.



##########
fe/fe-core/src/main/java/org/apache/doris/cloud/CloudWarmUpJob.java:
##########
@@ -461,6 +511,141 @@ public String getSrcClusterName() {
         return srcClusterName;
     }
 
+    public boolean hasTableFilter() {
+        return tableFilterRules != null && !tableFilterRules.isEmpty();
+    }
+
+    public String getTableFilterExpr() {
+        return tableFilterExpr;
+    }
+
+    public List<PersistedTableFilterRule> getTableFilterRules() {
+        return tableFilterRules;
+    }
+
+    public OnTablesFilter getOnTablesFilter() {
+        return onTablesFilter;
+    }
+
+    /**
+     * Returns the set of currently matched table IDs.
+     */
+    public Set<Long> getCurrentTableIds() {
+        return currentTableIdNames.keySet();
+    }
+
+    /**
+     * Sets the current matched table ID-to-name mapping.
+     */
+    public void setCurrentTableIdNames(Map<Long, String> idNames) {
+        this.currentTableIdNames = idNames;
+    }
+
+    public Map<Long, String> getCurrentTableIdNames() {
+        return currentTableIdNames;
+    }
+
+    /**
+     * Compute the canonical table filter expression from persisted rules.
+     * Returns empty string when no table filter rules exist.
+     */
+    private String computeTableFilterExpr() {
+        List<PersistedTableFilterRule> normalizedRules = 
normalizeTableFilterRules(tableFilterRules);
+        tableFilterRules = normalizedRules;
+        if (normalizedRules.isEmpty()) {
+            return "";
+        }
+        return canonicalizeNormalizedRules(normalizedRules);
+    }
+
+    /**
+     * Generate canonical JSON from persisted rules for JobKey dedup and SHOW 
output.
+     * Steps: group by type → sort alphabetically → deduplicate → compact JSON.
+     */
+    public static String canonicalize(List<PersistedTableFilterRule> rules) {
+        return canonicalizeNormalizedRules(normalizeTableFilterRules(rules));
+    }
+
+    private static String 
canonicalizeNormalizedRules(List<PersistedTableFilterRule> normalizedRules) {
+        List<String> includes = normalizedRules.stream()
+                .filter(r -> "INCLUDE".equals(r.ruleType))
+                .map(r -> r.pattern)
+                .collect(Collectors.toList());
+        List<String> excludes = normalizedRules.stream()
+                .filter(r -> "EXCLUDE".equals(r.ruleType))
+                .map(r -> r.pattern)
+                .collect(Collectors.toList());
+
+        JsonObject json = new JsonObject();
+        JsonArray incArr = new JsonArray();
+        includes.forEach(incArr::add);
+        json.add("include", incArr);
+        if (!excludes.isEmpty()) {
+            JsonArray excArr = new JsonArray();
+            excludes.forEach(excArr::add);
+            json.add("exclude", excArr);
+        }
+        return json.toString();
+    }
+
+    /**
+     * Rebuild the transient OnTablesFilter and tableFilterExpr from persisted 
tableFilterRules.
+     * Called after deserialization (EditLog replay, FE restart).
+     */
+    public void rebuildOnTablesFilter() {
+        if (tableFilterRules == null || tableFilterRules.isEmpty()) {
+            return;
+        }
+        this.tableFilterExpr = computeTableFilterExpr();
+        List<OnTablesFilter.TableFilterRule> rules = tableFilterRules.stream()
+                .map(r -> new OnTablesFilter.TableFilterRule(
+                        "INCLUDE".equals(r.ruleType)
+                                ? 
OnTablesFilter.TableFilterRule.RuleType.INCLUDE
+                                : 
OnTablesFilter.TableFilterRule.RuleType.EXCLUDE,
+                        r.pattern))
+                .collect(Collectors.toList());
+        this.onTablesFilter = new OnTablesFilter(rules);
+    }
+
+    private static int tableFilterRuleTypeOrder(PersistedTableFilterRule rule) 
{
+        return "INCLUDE".equals(rule.ruleType) ? 0 : 1;
+    }
+
+    private static String normalizeTableFilterRuleType(String ruleType) {
+        Preconditions.checkNotNull(ruleType, "table filter rule type cannot be 
null");
+        Preconditions.checkState("INCLUDE".equalsIgnoreCase(ruleType) || 
"EXCLUDE".equalsIgnoreCase(ruleType),
+                "Unexpected table filter rule type: %s", ruleType);
+        return "INCLUDE".equalsIgnoreCase(ruleType) ? "INCLUDE" : "EXCLUDE";
+    }
+
+    private static PersistedTableFilterRule 
copyNormalizedTableFilterRule(PersistedTableFilterRule rule) {
+        PersistedTableFilterRule normalizedRule = new 
PersistedTableFilterRule();
+        normalizedRule.ruleType = normalizeTableFilterRuleType(rule.ruleType);
+        normalizedRule.pattern = rule.pattern;
+        return normalizedRule;
+    }
+
+    private static List<PersistedTableFilterRule> 
normalizeTableFilterRules(List<PersistedTableFilterRule> rules) {
+        if (rules == null || rules.isEmpty()) {
+            return new ArrayList<>();
+        }
+        List<PersistedTableFilterRule> sortedRules = rules.stream()
+                .map(CloudWarmUpJob::copyNormalizedTableFilterRule)
+                .sorted(TABLE_FILTER_RULE_COMPARATOR)
+                .collect(Collectors.toList());
+        List<PersistedTableFilterRule> normalizedRules = new ArrayList<>();
+        String lastRuleKey = null;
+        for (PersistedTableFilterRule rule : sortedRules) {
+            String ruleKey = rule.ruleType + "\0" + 
StringUtils.defaultString(rule.pattern);
+            if (ruleKey.equals(lastRuleKey)) {
+                continue;
+            }
+            normalizedRules.add(rule);
+            lastRuleKey = ruleKey;
+        }
+        return normalizedRules;
+    }
+

Review Comment:
   This starts sending filtered jobs to every BE unconditionally, but 
`table_ids` is only a new thrift field. Pre-upgrade BEs will drop the unknown 
field and register the job as cluster-level warmup, so an `ON TABLES` job 
silently warms all tables during an FE-first / mixed-BE rollout. We need a 
version gate / feature check before allowing filtered jobs, or some 
compatibility fallback that refuses to install the job on old BEs.



##########
fe/fe-common/src/main/java/org/apache/doris/common/Config.java:
##########
@@ -3228,6 +3228,11 @@ public static int metaServiceRpcRetryTimes() {
     @ConfField(mutable = true, masterOnly = true)
     public static long cloud_warm_up_job_max_bytes_per_batch = 21474836480L; 
// 20GB
 
+    @ConfField(mutable = true, masterOnly = true, description = {
+            "zh-CN: 定期刷新 table-level warmup 任务匹配的 table ID 集合的时间间隔(毫秒)",
+            "en: Interval in milliseconds to refresh matched table IDs for 
table-level warmup jobs"})
+    public static long cloud_warm_up_table_filter_refresh_interval_ms = 60000; 
// 60 seconds

Review Comment:
   This is marked `mutable = true`, but `TableFilterRefreshDaemon` copies the 
value once in its constructor and never calls `setInterval()`. Changing the 
config at runtime won't change the refresh cadence until FE restart. Either 
make it immutable or re-read and apply the new value during daemon execution.



##########
regression-test/suites/cloud_p0/cache/multi_cluster/warm_up/on_tables/test_warm_up_event_on_tables_include.groovy:
##########
@@ -0,0 +1,165 @@
+// 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.
+
+import org.apache.doris.regression.suite.ClusterOptions
+import org.apache.doris.regression.util.WarmupMetricsUtils
+import groovy.json.JsonSlurper
+
+suite('test_warm_up_event_on_tables_include', 'docker') {
+    def options = new ClusterOptions()
+    options.feConfigs += [
+        'cloud_cluster_check_interval_second=1',
+        'cloud_warm_up_table_filter_refresh_interval_ms=1000',
+    ]
+    options.beConfigs += [
+        'file_cache_enter_disk_resource_limit_mode_percent=99',
+        'enable_evict_file_cache_in_advance=false',
+        'file_cache_background_monitor_interval_ms=1000',
+    ]
+    options.cloudMode = true
+    options.beNum = 1
+
+    docker(options) {
+        Closure sqlRunner = { String q -> sql(q) }
+
+        def clusterName1 = "warmup_source"
+        def clusterName2 = "warmup_target"
+
+        cluster.addBackend(1, clusterName1)
+        cluster.addBackend(1, clusterName2)
+
+        sql """use @${clusterName1}"""
+
+        def dbName = "test_on_tables_inc_db"
+        def dbExcluded = "test_on_tables_exc_db"
+        def jobIds = []
+
+        try {
+            sql """CREATE DATABASE IF NOT EXISTS ${dbName}"""
+            sql """CREATE DATABASE IF NOT EXISTS ${dbExcluded}"""
+
+            sql """use ${dbName}"""
+            sql """CREATE TABLE IF NOT EXISTS orders (id INT, amount DOUBLE)
+                   DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+                   PROPERTIES ("file_cache_ttl_seconds" = "3600")"""
+            sql """CREATE TABLE IF NOT EXISTS customers (id INT, name STRING)
+                   DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+                   PROPERTIES ("file_cache_ttl_seconds" = "3600")"""
+
+            sql """use ${dbExcluded}"""
+            sql """CREATE TABLE IF NOT EXISTS logs (id INT, msg STRING)
+                   DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+                   PROPERTIES ("file_cache_ttl_seconds" = "3600")"""
+
+            // Create INCLUDE wildcard job
+            sql """use @${clusterName1}"""
+            def jobId_ = sql """
+                WARM UP CLUSTER ${clusterName2} WITH CLUSTER ${clusterName1}
+                ON TABLES (
+                    INCLUDE '${dbName}.*'
+                )
+                PROPERTIES (
+                    "sync_mode" = "event_driven",
+                    "sync_event" = "load"
+                )
+            """
+            def jobId = jobId_[0][0]
+            jobIds << jobId
+            logger.info("Warm-up job ID: ${jobId}")
+
+            sleep(3000)
+
+            def baseMetrics = WarmupMetricsUtils.getWarmupMetrics(sqlRunner, 
clusterName1, clusterName2)
+            logger.info("Baseline metrics: ${baseMetrics}")
+
+            // Negative proof: insert ONLY into excluded db
+            def numExcludedInserts = 5
+            sql """use ${dbExcluded}"""
+            for (int i = 0; i < numExcludedInserts; i++) {
+                sql """INSERT INTO logs VALUES (${i}, 'log_message_${i}')"""
+            }
+            sleep(5000)
+
+            def metricsAfterExcluded = 
WarmupMetricsUtils.logWarmupMetrics(sqlRunner, clusterName1, clusterName2)
+            def excludedSubmittedDelta = metricsAfterExcluded.submitted - 
baseMetrics.submitted
+            def excludedFinishedDelta = metricsAfterExcluded.finished - 
baseMetrics.finished
+            assert excludedSubmittedDelta == 0 : "Excluded inserts should not 
submit segments, delta=${excludedSubmittedDelta}"
+            assert excludedFinishedDelta == 0 : "Excluded inserts should not 
finish segments, delta=${excludedFinishedDelta}"
+
+            // Positive proof: insert into included db
+            def numIncludedInserts = 5
+            def expectedSegments = numIncludedInserts * 2  // 2 tables: orders 
+ customers
+            sql """use ${dbName}"""
+            for (int i = 0; i < numIncludedInserts; i++) {
+                sql """INSERT INTO orders VALUES (${i}, ${i * 10.5})"""
+                sql """INSERT INTO customers VALUES (${i}, 'customer_${i}')"""
+            }
+
+            def finalMetrics = 
WarmupMetricsUtils.waitForWarmupFinish(sqlRunner, clusterName1, clusterName2,
+                    metricsAfterExcluded.finished + expectedSegments)
+            WarmupMetricsUtils.logWarmupMetrics(sqlRunner, clusterName1, 
clusterName2)
+
+            def requestedDelta = finalMetrics.requested - 
metricsAfterExcluded.requested
+            def submittedDelta = finalMetrics.submitted - 
metricsAfterExcluded.submitted
+            def finishedDelta = finalMetrics.finished - 
metricsAfterExcluded.finished
+            def failedDelta = finalMetrics.failed - metricsAfterExcluded.failed
+            logger.info("Included warmup deltas: requested=${requestedDelta}, 
submitted=${submittedDelta}, finished=${finishedDelta}, failed=${failedDelta}")
+            assert requestedDelta >= expectedSegments : "Expected requested >= 
${expectedSegments}, got ${requestedDelta}"
+            assert submittedDelta >= expectedSegments : "Expected submitted >= 
${expectedSegments}, got ${submittedDelta}"
+            assert finishedDelta >= expectedSegments : "Expected finished >= 
${expectedSegments}, got ${finishedDelta}"
+            assert failedDelta == 0 : "Expected 0 failed segments, got 
${failedDelta}"
+
+            // Verify SHOW WARM UP JOB output
+            def jobInfo = sql """SHOW WARM UP JOB WHERE ID = ${jobId}"""
+            assert jobInfo[0][0] == jobId
+            assert jobInfo[0][1] == clusterName1
+            assert jobInfo[0][2] == clusterName2
+            assert jobInfo[0][3] in ["RUNNING", "PENDING"]
+            assert jobInfo[0][4] == "CLUSTER"

Review Comment:
   `ON TABLES` jobs are now created with `JobType.TABLES`, and `SHOW WARM UP 
JOB` prints that enum directly. This assertion still expects `CLUSTER`, so the 
regression case should fail once the implementation is correct. The expected 
type here should be `TABLES`.



##########
fe/fe-core/src/main/java/org/apache/doris/cloud/CloudWarmUpJob.java:
##########
@@ -699,8 +884,14 @@ private void runEventDrivenJob() throws Exception {
                     throw new IllegalArgumentException("Unknown SyncEvent " + 
syncEvent);
                 }
                 request.setEvent(event);
-                LOG.debug("send warm up request to BE {} ({}). job_id={}, 
event={}, request_type=SET_JOB(EVENT)",
-                        entry.getKey(), getBackendEndpoint(entry.getKey()), 
jobId, syncEvent);
+                if (hasTableFilter()) {
+                    request.setTableIds(currentTableIdNames != null
+                            ? new ArrayList<>(currentTableIdNames.keySet()) : 
new ArrayList<>());
+                }
+                LOG.debug("send warm up request to BE {} ({}). job_id={}, 
event={}, "
+                                + "request_type=SET_JOB(EVENT), 
table_ids_count={}",

Review Comment:
   `read()` only reconstructs `tableFilterExpr`. During image/checkpoint load 
`CloudEnv.loadCloudWarmUpJob()` calls `addCloudWarmUpJob()` rather than 
`replayCloudWarmUpJob()`, so the restored job never gets 
`rebuildOnTablesFilter()` / `currentTableIdNames`. After an FE restart an `ON 
TABLES` job comes back with a null filter and starts sending an empty 
`table_ids` list (or the refresh daemon keeps failing if Gson left the 
transient map null), so the job silently stops warming any tables until it is 
recreated. We need to rebuild the transient filter state on image load too, not 
just on journal replay.



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