hello-stephen commented on code in PR #71378:
URL: https://github.com/apache/doris/pull/71378#discussion_r4786955642
##########
fe/fe-core/src/main/java/org/apache/doris/metric/IvmRefreshSnapshotMetrics.java:
##########
@@ -29,23 +29,60 @@ private IvmRefreshSnapshotMetrics() {
}
static void visit(MetricVisitor visitor, ChangelogMonitorSnapshot
snapshot) {
- for (ChangelogMonitorSnapshot.IvmRefresh refresh :
snapshot.ivmRefreshes()) {
+ List<ChangelogMonitorSnapshot.IvmRefresh> refreshes =
snapshot.ivmRefreshes();
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
+ visit(visitor, baseLabels(refresh), "ivm_consecutive_failures",
MetricType.GAUGE, MetricUnit.NOUNIT,
+ "Consecutive failed refresh tasks of this IVM materialized
view",
+ refresh.values().consecutiveFailures());
+ }
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
+ visit(visitor, baseLabels(refresh),
"ivm_refresh_failed_tasks_total", MetricType.COUNTER, MetricUnit.NOUNIT,
+ "Total failed refresh tasks of this IVM materialized view",
+ refresh.values().failedTaskCount());
+ }
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
+ visit(visitor, baseLabels(refresh), "ivm_refresh_fallbacks_total",
MetricType.COUNTER, MetricUnit.NOUNIT,
+ "Total automatic refresh fallbacks of this IVM
materialized view",
+ refresh.values().fallbackCount());
+ }
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
IvmRefreshSummary.MetricValues values = refresh.values();
- List<MetricLabel> labels = List.of(new MetricLabel("db_name",
refresh.dbName()),
- new MetricLabel("mv_name", refresh.mvName()),
- new MetricLabel("mv_id", Long.toString(refresh.mvId())));
- visit(visitor, labels, "ivm_consecutive_failures",
MetricType.GAUGE, MetricUnit.NOUNIT,
- "Consecutive failed refresh tasks of this IVM materialized
view", values.consecutiveFailures());
- visit(visitor, labels, "ivm_refresh_failed_tasks_total",
MetricType.COUNTER, MetricUnit.NOUNIT,
- "Total failed refresh tasks of this IVM materialized
view", values.failedTaskCount());
- visit(visitor, labels, "ivm_refresh_fallbacks_total",
MetricType.COUNTER, MetricUnit.NOUNIT,
- "Total automatic refresh fallbacks of this IVM
materialized view", values.fallbackCount());
if (values.hasCompletedRefresh()) {
- visit(visitor, labels, "ivm_refresh_duration_seconds",
MetricType.GAUGE, MetricUnit.SECONDS,
+ visit(visitor, baseLabels(refresh),
"ivm_refresh_duration_seconds", MetricType.GAUGE,
+ MetricUnit.SECONDS,
"Duration of the last successful or failed refresh of
this IVM materialized view",
values.lastRefreshDurationMs() / 1000.0);
}
}
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
+ IvmRefreshSummary.MetricValues values = refresh.values();
+ visit(visitor, modeLabels(refresh, "incremental"),
"ivm_refresh_execution_seconds_total",
+ MetricType.COUNTER, MetricUnit.SECONDS,
+ "Total execution time of refresh phases of this IVM
materialized view, by mode",
+ values.incrementalDurationMs() / 1000.0);
+ visit(visitor, modeLabels(refresh, "rebuild"),
"ivm_refresh_execution_seconds_total",
+ MetricType.COUNTER, MetricUnit.SECONDS,
+ "Total execution time of refresh phases of this IVM
materialized view, by mode",
+ values.rebuildDurationMs() / 1000.0);
+ }
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh : refreshes) {
+ visit(visitor, baseLabels(refresh), "ivm_refresh_rows_total",
MetricType.COUNTER, MetricUnit.NOUNIT,
+ "Total committed loaded rows written by refresh tasks of
this IVM materialized view",
Review Comment:
[P3] Say that both counters exclude canceled refreshes. A STOP between
overwrite batches can leave earlier batches committed, but
`IvmRefreshSummary.update` skips the canceled result entirely. The current HELP
text reads as though it includes those rows and that execution time.
##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java:
##########
@@ -1735,10 +1782,12 @@ private IvmPlanSignature refreshPartitions(Set<String>
refreshPartitionNames,
? refreshPartitionNames : Sets.newHashSet(),
tableWithPartKey, statementContext);
setupComputeGroup(mtmvCtx);
AtomicReference<IvmPlanSignature> signatureRef = new
AtomicReference<>();
+ long loadedRows;
try {
MTMVPlanUtil.executeCommand(mtmvCtx, command, statementContext,
getRefreshAuditStmt(refreshMode, refreshPartitionNames),
createRefreshConsumer(signatureRef));
+ loadedRows = Math.max(0L, mtmvCtx.getState().getAffectedRows());
Review Comment:
[P2] Count committed rows even when waiting for visibility times out. With
`insert_visible_timeout_return_mode=error`, `OlapInsertExecutor` records a
committed load before setting the SQL state to ERR.
`InsertOverwriteTableCommand` still swaps those partitions, but
`MTMVPlanUtil.executeCommand` then throws before this read. The incremental
path in `IvmIncrRefreshManager` loses the same rows. Record rows from the
committed insert or published overwrite outcome independently of the task
status, so the error still propagates and a failed swap is not counted.
##########
regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_cost_metrics.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.util.Http
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_ivm_refresh_cost_metrics", "nonConcurrent") {
+ sql "SET enable_materialized_view_rewrite = false"
+ sql "SET enable_dml_materialized_view_rewrite = false"
+
+ String masterMetricsUrl =
"http://${getMasterIp()}:${getMasterPort()}/metrics"
+
+ def fetchMvCostMetrics = { String mvName ->
+ Map<String, Double> found = [:]
+ String mvFragment = "mv_name=\"${mvName}\""
+ for (String line : Http.GET(masterMetricsUrl, false,
false).readLines()) {
+ if (!line.contains(mvFragment)) {
+ continue
+ }
+ if
(line.startsWith("doris_fe_ivm_refresh_execution_seconds_total{")) {
+ int split = line.lastIndexOf(' ')
+ if (line.contains('mode="incremental"')) {
+ found.put("incremental",
Double.parseDouble(line.substring(split + 1)))
+ } else if (line.contains('mode="rebuild"')) {
+ found.put("rebuild",
Double.parseDouble(line.substring(split + 1)))
+ }
+ } else if (line.startsWith("doris_fe_ivm_refresh_rows_total{")) {
+ int split = line.lastIndexOf(' ')
+ found.put("rows", Double.parseDouble(line.substring(split +
1)))
+ }
+ }
+ return found
+ }
+
+ def waitForLatestTaskFinished = { String mvName, String previousTaskId ->
+ def taskResult
+ Awaitility.await().atMost(180, SECONDS).pollInterval(1,
SECONDS).until({
+ taskResult = sql_return_maparray("""
+ SELECT TaskId, Status FROM tasks('type'='mv')
+ WHERE MvDatabaseName = '${context.dbName}' AND MvName =
'${mvName}'
+ ORDER BY CreateTime DESC, TaskId DESC LIMIT 1
+ """)
+ return !taskResult.isEmpty()
+ && taskResult[0].TaskId.toString() != previousTaskId
+ && taskResult[0].Status.toString() != 'PENDING'
+ && taskResult[0].Status.toString() != 'RUNNING'
+ })
+ assertEquals("SUCCESS", taskResult[0].Status.toString())
+ return taskResult[0].TaskId.toString()
+ }
+
+ sql "DROP MATERIALIZED VIEW IF EXISTS ivm_cost_metrics_mv"
+ sql "DROP TABLE IF EXISTS ivm_cost_metrics_t"
+ sql """
+ CREATE TABLE ivm_cost_metrics_t (
+ dt DATE NOT NULL,
+ id BIGINT NOT NULL,
+ v INT
+ )
+ UNIQUE KEY(dt, id)
+ PARTITION BY RANGE(dt) (
+ PARTITION p1 VALUES [('2026-01-01'), ('2026-02-01')),
+ PARTITION p2 VALUES [('2026-02-01'), ('2026-03-01'))
+ )
+ 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 ivm_cost_metrics_t VALUES
+ ('2026-01-10', 1, 10),
+ ('2026-01-10', 2, 20),
+ ('2026-02-10', 3, 30)
+ """
+
+ sql """
+ CREATE MATERIALIZED VIEW ivm_cost_metrics_mv
+ BUILD DEFERRED REFRESH INCREMENTAL ON MANUAL
+ PARTITION BY (dt)
+ DISTRIBUTED BY HASH(dt) BUCKETS 1
+ PROPERTIES ("replication_num" = "1")
+ AS SELECT dt, SUM(v) AS sum_v, COUNT(*) AS cnt
+ FROM ivm_cost_metrics_t
+ GROUP BY dt
+ """
+
+ // 1. Initial refresh runs COMPLETE rebuild: writes 2 aggregated rows (one
per dt).
+ sql "REFRESH MATERIALIZED VIEW ivm_cost_metrics_mv COMPLETE"
+ String lastTaskId = waitForLatestTaskFinished("ivm_cost_metrics_mv", null)
+
+ Map<String, Double> afterComplete = [:]
+ Awaitility.await().atMost(45, SECONDS).pollInterval(1, SECONDS).until({
+ afterComplete = fetchMvCostMetrics("ivm_cost_metrics_mv")
+ return afterComplete.containsKey("rows") && afterComplete["rows"] ==
2.0d
+ && afterComplete.containsKey("rebuild") &&
afterComplete.containsKey("incremental")
+ })
+ assertTrue(afterComplete["rebuild"] >= 0.0d)
Review Comment:
[P3] Make this regression fail if neither execution timer records anything.
The COMPLETE, INCREMENTAL, and MIXED assertions all accept zero-valued timers,
and the FE unit tests supply timing values without exercising `MTMVTask`’s
clocks. Check that the mode that ran increases while the other stays unchanged,
using a controlled duration if needed to avoid sub-millisecond rounding.
##########
regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_cost_metrics.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.util.Http
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_ivm_refresh_cost_metrics", "nonConcurrent") {
+ sql "SET enable_materialized_view_rewrite = false"
+ sql "SET enable_dml_materialized_view_rewrite = false"
+
+ String masterMetricsUrl =
"http://${getMasterIp()}:${getMasterPort()}/metrics"
+
+ def fetchMvCostMetrics = { String mvName ->
+ Map<String, Double> found = [:]
+ String mvFragment = "mv_name=\"${mvName}\""
+ for (String line : Http.GET(masterMetricsUrl, false,
false).readLines()) {
+ if (!line.contains(mvFragment)) {
+ continue
+ }
+ if
(line.startsWith("doris_fe_ivm_refresh_execution_seconds_total{")) {
+ int split = line.lastIndexOf(' ')
+ if (line.contains('mode="incremental"')) {
+ found.put("incremental",
Double.parseDouble(line.substring(split + 1)))
+ } else if (line.contains('mode="rebuild"')) {
+ found.put("rebuild",
Double.parseDouble(line.substring(split + 1)))
+ }
+ } else if (line.startsWith("doris_fe_ivm_refresh_rows_total{")) {
+ int split = line.lastIndexOf(' ')
+ found.put("rows", Double.parseDouble(line.substring(split +
1)))
+ }
+ }
+ return found
+ }
+
+ def waitForLatestTaskFinished = { String mvName, String previousTaskId ->
+ def taskResult
+ Awaitility.await().atMost(180, SECONDS).pollInterval(1,
SECONDS).until({
+ taskResult = sql_return_maparray("""
+ SELECT TaskId, Status FROM tasks('type'='mv')
+ WHERE MvDatabaseName = '${context.dbName}' AND MvName =
'${mvName}'
+ ORDER BY CreateTime DESC, TaskId DESC LIMIT 1
+ """)
+ return !taskResult.isEmpty()
+ && taskResult[0].TaskId.toString() != previousTaskId
+ && taskResult[0].Status.toString() != 'PENDING'
+ && taskResult[0].Status.toString() != 'RUNNING'
+ })
+ assertEquals("SUCCESS", taskResult[0].Status.toString())
+ return taskResult[0].TaskId.toString()
+ }
+
+ sql "DROP MATERIALIZED VIEW IF EXISTS ivm_cost_metrics_mv"
+ sql "DROP TABLE IF EXISTS ivm_cost_metrics_t"
+ sql """
+ CREATE TABLE ivm_cost_metrics_t (
+ dt DATE NOT NULL,
+ id BIGINT NOT NULL,
+ v INT
+ )
+ UNIQUE KEY(dt, id)
+ PARTITION BY RANGE(dt) (
+ PARTITION p1 VALUES [('2026-01-01'), ('2026-02-01')),
+ PARTITION p2 VALUES [('2026-02-01'), ('2026-03-01'))
+ )
+ 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 ivm_cost_metrics_t VALUES
+ ('2026-01-10', 1, 10),
+ ('2026-01-10', 2, 20),
+ ('2026-02-10', 3, 30)
+ """
+
+ sql """
+ CREATE MATERIALIZED VIEW ivm_cost_metrics_mv
+ BUILD DEFERRED REFRESH INCREMENTAL ON MANUAL
+ PARTITION BY (dt)
+ DISTRIBUTED BY HASH(dt) BUCKETS 1
+ PROPERTIES ("replication_num" = "1")
+ AS SELECT dt, SUM(v) AS sum_v, COUNT(*) AS cnt
+ FROM ivm_cost_metrics_t
+ GROUP BY dt
+ """
+
+ // 1. Initial refresh runs COMPLETE rebuild: writes 2 aggregated rows (one
per dt).
+ sql "REFRESH MATERIALIZED VIEW ivm_cost_metrics_mv COMPLETE"
+ String lastTaskId = waitForLatestTaskFinished("ivm_cost_metrics_mv", null)
+
+ Map<String, Double> afterComplete = [:]
+ Awaitility.await().atMost(45, SECONDS).pollInterval(1, SECONDS).until({
+ afterComplete = fetchMvCostMetrics("ivm_cost_metrics_mv")
+ return afterComplete.containsKey("rows") && afterComplete["rows"] ==
2.0d
+ && afterComplete.containsKey("rebuild") &&
afterComplete.containsKey("incremental")
+ })
+ assertTrue(afterComplete["rebuild"] >= 0.0d)
+ assertEquals(0.0d, afterComplete["incremental"], 1e-6d)
+
+ // 2. Incremental refresh after inserting into p1: commits 1 delta row,
rebuild unchanged.
+ sql "INSERT INTO ivm_cost_metrics_t VALUES ('2026-01-10', 4, 40)"
+ sql "REFRESH MATERIALIZED VIEW ivm_cost_metrics_mv INCREMENTAL"
+ lastTaskId = waitForLatestTaskFinished("ivm_cost_metrics_mv", lastTaskId)
+
+ Map<String, Double> afterIncr = [:]
+ Awaitility.await().atMost(45, SECONDS).pollInterval(1, SECONDS).until({
+ afterIncr = fetchMvCostMetrics("ivm_cost_metrics_mv")
+ return afterIncr["rows"] == 3.0d
+ })
+ assertEquals(afterComplete["rebuild"], afterIncr["rebuild"], 1e-6d)
+ assertTrue(afterIncr["incremental"] >= 0.0d)
+
+ // 3. No-change incremental refresh does not increase rows counter.
+ sql "REFRESH MATERIALIZED VIEW ivm_cost_metrics_mv INCREMENTAL"
+ lastTaskId = waitForLatestTaskFinished("ivm_cost_metrics_mv", lastTaskId)
+ Map<String, Double> afterNoChange =
fetchMvCostMetrics("ivm_cost_metrics_mv")
Review Comment:
[P3] Check a post-task sample for the no-op, then assert the exact MIXED
increment. Task status comes from task history, but `/metrics` can still be
serving the preceding monitor snapshot, so the no-op check can pass on a stale
3. The later `rows > 3` would also accept an overcount or just one phase’s
rows. This fixture should add one row from each phase, taking the counter from
3 to 5.
--
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]