This is an automated email from the ASF dual-hosted git repository.
yujun777 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 4bbad788fd9 [feat](ivm) Export per-view refresh summary metrics
(#71062)
4bbad788fd9 is described below
commit 4bbad788fd96e6a378f2fd539babaccfba217ae0
Author: yujun <[email protected]>
AuthorDate: Tue Dec 1 07:11:07 2026 +0800
[feat](ivm) Export per-view refresh summary metrics (#71062)
### Background
Incrementally maintained materialized views refresh through the MTMV
task scheduler. The FE already exposes aggregate IVM task metrics and
saves a refresh summary for each view in its metadata.
### What problem does this PR solve?
Issue Number: None
Related PR: #69856 (aggregate refresh metrics and persisted summaries)
PR Type: Enhancement
Problem Summary:
The metrics endpoint reports aggregate refresh failures and fallbacks.
Diagnosing a repeatedly failing or slow view requires a per-view
breakdown. This change exposes four refresh summary metrics on the
Master FE so alerts can identify the affected view.
### Details
- **Change map:** 306 production lines and 443 test lines, including
deletions. The production change covers journal replay, Master FE
snapshots, and metric rendering. The tests cover summary persistence,
snapshot lifecycle, and the SQL refresh path.
- **Before and after:** Master `/metrics` now exposes
`doris_fe_ivm_consecutive_failures`,
`doris_fe_ivm_refresh_failed_tasks_total`,
`doris_fe_ivm_refresh_fallbacks_total`, and
`doris_fe_ivm_refresh_duration_seconds` with `db_name`, `mv_name`, and
`mv_id`. Duration appears after the first successful or failed refresh.
- **Configs and defaults:** `enable_changelog_monitor` is enabled by
default. The mutable `changelog_monitor_interval_seconds` defaults to 15
seconds. Scrapes read the published snapshot while catalog collection
runs on the daemon.
- **Impact on existing users:** Old images and journals still restore
the existing summary. The per-view failed-task total starts with the
first failed result recorded by an upgraded Master. A sequence recorded
with each new terminal result makes summary replay idempotent. A task
result that the existing catalog lookup cannot resolve may be skipped.
Later sequences can still advance the summary after a view rename. Each
summary accepts task sequences only for its owning view ID.
- **Behavior change:** The Master FE exports per-view series for live
IVM views. A successful refresh resets consecutive failures and
preserves the cumulative totals.
---
.../main/java/org/apache/doris/common/Config.java | 9 ++
.../main/java/org/apache/doris/catalog/Env.java | 13 ++
.../main/java/org/apache/doris/catalog/MTMV.java | 16 ++-
.../apache/doris/changelog/ChangelogMonitor.java | 104 +++++++++++++++
.../doris/changelog/ChangelogMonitorSnapshot.java | 32 +++++
.../apache/doris/job/extensions/mtmv/MTMVTask.java | 16 +++
.../doris/metric/IvmRefreshSnapshotMetrics.java | 61 +++++++++
.../org/apache/doris/metric/JsonMetricVisitor.java | 4 +-
.../java/org/apache/doris/metric/MetricRepo.java | 5 +
.../apache/doris/mtmv/ivm/IvmRefreshSummary.java | 46 ++++++-
.../doris/changelog/ChangelogMonitorTest.java | 144 +++++++++++++++++++++
.../metric/IvmRefreshSnapshotMetricsTest.java | 62 +++++++++
.../java/org/apache/doris/mtmv/AlterMTMVTest.java | 59 +++++++++
.../test/java/org/apache/doris/mtmv/MTMVTest.java | 58 ++++++++-
.../doris/mtmv/ivm/IvmRefreshSummaryTest.java | 51 +++++---
.../ivm/test_ivm_refresh_method_metrics.groovy | 71 +++++++++-
16 files changed, 718 insertions(+), 33 deletions(-)
diff --git a/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
b/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
index d1176bcf522..d50ff07e294 100644
--- a/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
+++ b/fe/fe-common/src/main/java/org/apache/doris/common/Config.java
@@ -2684,6 +2684,15 @@ public class Config extends ConfigBase {
description = "Whether to enable the changelog feature, including
the commit TSO")
public static boolean enable_feature_changelog = false;
+ @ConfField(mutable = true, masterOnly = true, varType =
VariableAnnotation.EXPERIMENTAL,
+ description = "Whether the Master FE samples IVM materialized
views for monitoring.")
+ public static volatile boolean enable_changelog_monitor = true;
+
+ @ConfField(mutable = true, masterOnly = true, varType =
VariableAnnotation.EXPERIMENTAL,
+ description = "The interval in seconds at which the Master FE
samples IVM materialized views, "
+ + "with a minimum of one second.")
+ public static volatile int changelog_monitor_interval_seconds = 15;
+
@ConfField(mutable = false, masterOnly = false, varType =
VariableAnnotation.EXPERIMENTAL, description = "Set the "
+ "maximum " + "byte " + "length " + "of a " + "binlog " +
"message")
public static int max_binlog_messsage_size = 1024 * 1024 * 1024;
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
index 0c2da26eb38..68eeb1ad58d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/Env.java
@@ -50,6 +50,7 @@ import org.apache.doris.catalog.info.PartitionNamesInfo;
import org.apache.doris.catalog.info.TableNameInfo;
import org.apache.doris.catalog.stream.BaseTableStream;
import org.apache.doris.catalog.stream.TableStreamManager;
+import org.apache.doris.changelog.ChangelogMonitor;
import org.apache.doris.changelog.ChangelogTtlDiscovery;
import org.apache.doris.clone.ColocateTableCheckerAndBalancer;
import org.apache.doris.clone.DynamicPartitionScheduler;
@@ -336,6 +337,7 @@ import org.apache.thrift.TException;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
+import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.nio.file.Path;
@@ -572,6 +574,7 @@ public class Env {
private ConstraintManager constraintManager;
private BinlogGcer binlogGcer;
+ private final ChangelogMonitor changelogMonitor = new
ChangelogMonitor(this);
private final ChangelogTtlDiscovery changelogTtlDiscovery = new
ChangelogTtlDiscovery();
private QueryCancelWorker queryCancelWorker;
@@ -2090,6 +2093,7 @@ public class Env {
if (Config.isCloudMode()) {
changelogTtlDiscovery.start();
}
+ changelogMonitor.start();
columnIdFlusher.start();
insertOverwriteManager.start();
dictionaryManager.start();
@@ -5668,6 +5672,10 @@ public class Env {
return this.isElectable;
}
+ public ChangelogMonitor getChangelogMonitor() {
+ return changelogMonitor;
+ }
+
public boolean isMaster() {
return feType == FrontendNodeType.MASTER;
}
@@ -7000,6 +7008,11 @@ public class Env {
if ("ldap_default_roles".equals(key)) {
getAuth().getLdapManager().refresh(true, null);
}
+ Field field = ConfigBase.getField(key);
+ if (field != null && "enable_changelog_monitor".equals(field.getName())
+ && "false".equalsIgnoreCase(value.trim())) {
+ changelogMonitor.reset();
+ }
if (configtoThreads.get(key) != null) {
try {
// not atomic. maybe delay to aware. but acceptable.
diff --git a/fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java
b/fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java
index 7b3b4aa8a34..a280269a40e 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java
@@ -318,6 +318,15 @@ public class MTMV extends OlapTable {
return getIvmInfo().isEnableIvm();
}
+ public IvmRefreshSummary.MetricValues getIvmRefreshMetricValues() {
+ readMvLock();
+ try {
+ return ivmRefreshSummary.metricValues();
+ } finally {
+ readMvUnlock();
+ }
+ }
+
/**
* Whether a refresh task of this IVM MV has ever succeeded. Until one
has, the MV has no baseline for the
* incremental refresh to keep up, and the refresh that builds it is not
the incremental refresh falling back.
@@ -456,10 +465,9 @@ public class MTMV extends OlapTable {
this.status.setRefreshState(MTMVRefreshState.FAIL);
}
this.jobInfo.addHistoryTask(task);
- if (ivmInfo.isEnableIvm()) {
- // From the task as the journal carries it, here and in the
replay alike, so that the summary does
- // not depend on how many tasks the history keeps and a
follower that takes over has the same one.
- ivmRefreshSummary.update(task);
+ if (ivmInfo.isEnableIvm() && task.belongsToMtmv(id)) {
+ // Summary sequences belong to one MV. A stale name can now
refer to another MV.
+ ivmRefreshSummary.update(task, isReplay);
}
compatiblePctSnapshot(partitionSnapshots);
// What this task wrote is described by the epochs just recorded,
so a partition the result
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java
b/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java
new file mode 100644
index 00000000000..ebe1352f13d
--- /dev/null
+++ b/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.changelog;
+
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.MTMV;
+import org.apache.doris.catalog.Table;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.util.MasterDaemon;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/** Samples IVM refresh summaries independently of the metrics scrape path. */
+public class ChangelogMonitor extends MasterDaemon {
+ private static final Logger LOG =
LogManager.getLogger(ChangelogMonitor.class);
+ private static final long CHECK_INTERVAL_MS = 1000;
+
+ private final Env env;
+ private volatile SamplingState state = new SamplingState();
+
+ private static class SamplingState {
+ private long lastRoundNanos;
+ private boolean hasRun;
+ private volatile ChangelogMonitorSnapshot snapshot;
+ }
+
+ public ChangelogMonitor(Env env) {
+ super("changelog-monitor", CHECK_INTERVAL_MS);
+ this.env = env;
+ }
+
+ @Override
+ protected void runAfterCatalogReady() {
+ sample(System.nanoTime());
+ }
+
+ void sample(long now) {
+ SamplingState current = state;
+ if (!isActive()) {
+ current.snapshot = null;
+ current.hasRun = false;
+ return;
+ }
+
+ long interval = TimeUnit.SECONDS.toNanos(Math.max(1,
Config.changelog_monitor_interval_seconds));
+ if (current.hasRun && now - current.lastRoundNanos < interval) {
+ return;
+ }
+ current.hasRun = true;
+ current.lastRoundNanos = now;
+ try {
+ current.snapshot = collect();
+ } catch (RuntimeException e) {
+ LOG.warn("Failed to collect a changelog monitor snapshot", e);
+ }
+ }
+
+ private boolean isActive() {
+ return Config.enable_changelog_monitor && env.isMaster() &&
env.isReady();
+ }
+
+ ChangelogMonitorSnapshot collect() {
+ List<ChangelogMonitorSnapshot.IvmRefresh> refreshes = new
ArrayList<>();
+ for (Database db : env.getInternalCatalog().getDbs()) {
+ for (Table table : db.getTables()) {
+ if (table instanceof MTMV mv && mv.isIvm()) {
+ refreshes.add(new ChangelogMonitorSnapshot.IvmRefresh(
+ db.getFullName(), mv.getName(), mv.getId(),
mv.getIvmRefreshMetricValues()));
+ }
+ }
+ }
+ return new ChangelogMonitorSnapshot(System.currentTimeMillis(),
refreshes);
+ }
+
+ public void reset() {
+ // An in-flight round can only publish into the old state.
+ state = new SamplingState();
+ }
+
+ public ChangelogMonitorSnapshot getSnapshot() {
+ return isActive() ? state.snapshot : null;
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitorSnapshot.java
b/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitorSnapshot.java
new file mode 100644
index 00000000000..3bd70e0e355
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitorSnapshot.java
@@ -0,0 +1,32 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.changelog;
+
+import org.apache.doris.mtmv.ivm.IvmRefreshSummary;
+
+import java.util.List;
+
+/** The complete results of one monitoring round on the Master FE. */
+public record ChangelogMonitorSnapshot(long sampleTimeMs, List<IvmRefresh>
ivmRefreshes) {
+ public ChangelogMonitorSnapshot {
+ ivmRefreshes = List.copyOf(ivmRefreshes);
+ }
+
+ public record IvmRefresh(String dbName, String mvName, long mvId,
IvmRefreshSummary.MetricValues values) {
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java
b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java
index 9bad81fb20f..b59c2527533 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java
@@ -335,6 +335,9 @@ public class MTMVTask extends AbstractTask {
// reason is ivmFallbackReason. A fallback that committed nothing did not
change how the MV was refreshed.
@SerializedName("ifb")
private boolean ivmFallback;
+ // Assigned under the MV write lock when this result is accepted. Zero
denotes a legacy or canceled result.
+ @SerializedName("iss")
+ private long ivmSummarySeq;
// The kinds of work this task has committed, which ivmRefreshMethod is
decided from. Concurrent because a STOP
// decides it from the cancel thread while the worker may still be
committing.
private transient Set<IvmRefreshMethod> committedRefreshKinds =
ConcurrentHashMap.newKeySet();
@@ -363,6 +366,7 @@ public class MTMVTask extends AbstractTask {
// only for test
public MTMVTask(MTMV mtmv, MTMVRelation relation, MTMVTaskContext
taskContext) {
this.mtmv = mtmv;
+ this.mtmvId = mtmv.getId();
this.relation = relation;
this.taskContext = taskContext;
}
@@ -2228,6 +2232,18 @@ public class MTMVTask extends AbstractTask {
return ivmFailureReason;
}
+ public boolean belongsToMtmv(long mvId) {
+ return mtmvId == mvId;
+ }
+
+ public long getIvmSummarySeq() {
+ return ivmSummarySeq;
+ }
+
+ public void setIvmSummarySeq(long ivmSummarySeq) {
+ this.ivmSummarySeq = ivmSummarySeq;
+ }
+
public boolean isIvmFallback() {
return ivmFallback;
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/metric/IvmRefreshSnapshotMetrics.java
b/fe/fe-core/src/main/java/org/apache/doris/metric/IvmRefreshSnapshotMetrics.java
new file mode 100644
index 00000000000..ebb3f934a1c
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/metric/IvmRefreshSnapshotMetrics.java
@@ -0,0 +1,61 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.metric;
+
+import org.apache.doris.changelog.ChangelogMonitorSnapshot;
+import org.apache.doris.metric.Metric.MetricType;
+import org.apache.doris.metric.Metric.MetricUnit;
+import org.apache.doris.mtmv.ivm.IvmRefreshSummary;
+
+import java.util.List;
+
+final class IvmRefreshSnapshotMetrics {
+ private IvmRefreshSnapshotMetrics() {
+ }
+
+ static void visit(MetricVisitor visitor, ChangelogMonitorSnapshot
snapshot) {
+ for (ChangelogMonitorSnapshot.IvmRefresh refresh :
snapshot.ivmRefreshes()) {
+ 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,
+ "Duration of the last successful or failed refresh of
this IVM materialized view",
+ values.lastRefreshDurationMs() / 1000.0);
+ }
+ }
+ }
+
+ private static void visit(MetricVisitor visitor, List<MetricLabel> labels,
String name, MetricType type,
+ MetricUnit unit, String description, Number value) {
+ Metric<Number> metric = new Metric<>(name, type, unit, description) {
+ @Override
+ public Number getValue() {
+ return value;
+ }
+ };
+ visitor.visit(MetricVisitor.FE_PREFIX, metric.setLabels(labels));
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/metric/JsonMetricVisitor.java
b/fe/fe-core/src/main/java/org/apache/doris/metric/JsonMetricVisitor.java
index 01652bc5cc8..d46540effa8 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/metric/JsonMetricVisitor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/metric/JsonMetricVisitor.java
@@ -25,6 +25,7 @@ import org.apache.doris.monitor.jvm.JvmStats.Threads;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Snapshot;
+import com.google.gson.JsonPrimitive;
import java.util.ArrayList;
import java.util.Iterator;
@@ -132,7 +133,8 @@ public class JsonMetricVisitor extends MetricVisitor {
if (i++ > 0) {
sb.append(",\n");
}
-
sb.append("\t\t\"").append(label.getKey()).append("\":\"").append(label.getValue()).append("\"");
+ sb.append("\t\t").append(new
JsonPrimitive(label.getKey())).append(':')
+ .append(new
JsonPrimitive(String.valueOf(label.getValue())));
}
}
sb.append("\n\t},\n");
diff --git a/fe/fe-core/src/main/java/org/apache/doris/metric/MetricRepo.java
b/fe/fe-core/src/main/java/org/apache/doris/metric/MetricRepo.java
index 2b7b9744476..39928013d21 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/metric/MetricRepo.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/metric/MetricRepo.java
@@ -22,6 +22,7 @@ import org.apache.doris.alter.AlterJobV2.JobType;
import org.apache.doris.catalog.Database;
import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.TabletSlidingWindowAccessStats;
+import org.apache.doris.changelog.ChangelogMonitorSnapshot;
import org.apache.doris.cloud.CloudWarmUpJob;
import org.apache.doris.cloud.JobWarmUpStats;
import org.apache.doris.cloud.catalog.CloudTabletRebalancer;
@@ -1816,6 +1817,10 @@ public final class MetricRepo {
visitor.visitWorkloadGroup();
+ ChangelogMonitorSnapshot snapshot =
Env.getCurrentEnv().getChangelogMonitor().getSnapshot();
+ if (snapshot != null) {
+ IvmRefreshSnapshotMetrics.visit(visitor, snapshot);
+ }
return visitor.finish();
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmRefreshSummary.java
b/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmRefreshSummary.java
index b0951b1ad9f..746cca2b945 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmRefreshSummary.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/mtmv/ivm/IvmRefreshSummary.java
@@ -17,8 +17,10 @@
package org.apache.doris.mtmv.ivm;
+import org.apache.doris.job.common.TaskStatus;
import org.apache.doris.job.extensions.mtmv.MTMVTask;
+import com.google.common.base.Preconditions;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;
@@ -41,6 +43,10 @@ public class IvmRefreshSummary {
// Failed tasks since the latest successful one.
@SerializedName("cf")
private int consecutiveFailures;
+ @SerializedName("ftc")
+ private long failedTaskCount;
+ @SerializedName("lass")
+ private long lastAppliedSummarySeq;
// Finish times in milliseconds, 0 when there has been none.
@SerializedName("lst")
private long lastSuccessTimeMs;
@@ -67,8 +73,30 @@ public class IvmRefreshSummary {
@SerializedName("s")
private boolean succeeded;
- /** Takes in the result of a task, which has ended as SUCCESS, FAILED or
CANCELED. */
- public void update(MTMVTask task) {
+ /** Applies a terminal result under the owning MV's write lock. */
+ public void update(MTMVTask task, boolean isReplay) {
+ if (task.getStatus() == TaskStatus.CANCELED) {
+ return;
+ }
+ Preconditions.checkState(task.getStatus() == TaskStatus.SUCCESS ||
task.getStatus() == TaskStatus.FAILED,
+ "A task result cannot be %s, taskId=%s", task.getStatus(),
task.getTaskId());
+ long seq = task.getIvmSummarySeq();
+ if (seq == 0 && !isReplay) {
+ seq = lastAppliedSummarySeq + 1;
+ task.setIvmSummarySeq(seq);
+ }
+ if (seq != 0 && seq <= lastAppliedSummarySeq) {
+ return;
+ }
+ // A result with an unavailable target may have been skipped. A later
sequence can still advance.
+ // Old journal records still restore the existing summary fields.
+ applyResult(task, seq != 0);
+ if (seq != 0) {
+ lastAppliedSummarySeq = seq;
+ }
+ }
+
+ private void applyResult(MTMVTask task, boolean countFailure) {
switch (task.getStatus()) {
case SUCCESS:
consecutiveFailures = 0;
@@ -77,12 +105,13 @@ public class IvmRefreshSummary {
break;
case FAILED:
consecutiveFailures++;
+ if (countFailure) {
+ failedTaskCount++;
+ }
lastFailureTimeMs = task.getFinishTimeMs();
lastFailureReason = task.getIvmFailureReason();
lastErrorMessage = StringUtils.abbreviate(task.getErrMsg(),
MAX_ERROR_MESSAGE_LENGTH);
break;
- case CANCELED:
- return;
default:
throw new IllegalStateException("A task result cannot be " +
task.getStatus()
+ ", taskId=" + task.getTaskId());
@@ -96,6 +125,15 @@ public class IvmRefreshSummary {
}
}
+ public record MetricValues(int consecutiveFailures, long failedTaskCount,
long fallbackCount,
+ boolean hasCompletedRefresh, long lastRefreshDurationMs) {
+ }
+
+ public MetricValues metricValues() {
+ return new MetricValues(consecutiveFailures, failedTaskCount,
fallbackCount,
+ lastSuccessTimeMs != 0 || lastFailureTimeMs != 0,
lastRefreshDurationMs);
+ }
+
public int getConsecutiveFailures() {
return consecutiveFailures;
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/changelog/ChangelogMonitorTest.java
b/fe/fe-core/src/test/java/org/apache/doris/changelog/ChangelogMonitorTest.java
new file mode 100644
index 00000000000..14ed7a418df
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/changelog/ChangelogMonitorTest.java
@@ -0,0 +1,144 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.changelog;
+
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.MTMV;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.ConfigBase;
+import org.apache.doris.datasource.InternalCatalog;
+import org.apache.doris.mtmv.ivm.IvmRefreshSummary;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+
+class ChangelogMonitorTest {
+ @Test
+ void publishesOnlyCompletedMasterSnapshots() {
+ Env env = Mockito.mock(Env.class);
+ InternalCatalog catalog = Mockito.mock(InternalCatalog.class);
+ Database database = Mockito.mock(Database.class);
+ MTMV first = Mockito.mock(MTMV.class);
+ MTMV second = Mockito.mock(MTMV.class);
+ MTMV plainMv = Mockito.mock(MTMV.class);
+ OlapTable plainTable = Mockito.mock(OlapTable.class);
+ Mockito.when(env.getInternalCatalog()).thenReturn(catalog);
+ Mockito.when(env.isReady()).thenReturn(true);
+ Mockito.when(catalog.getDbs()).thenReturn(List.of(database));
+ Mockito.when(database.getFullName()).thenReturn("sales");
+ Mockito.when(database.getTables()).thenReturn(List.of(first, second,
plainMv, plainTable));
+ Mockito.when(first.isIvm()).thenReturn(true);
+ Mockito.when(first.getId()).thenReturn(7L);
+ Mockito.when(first.getName()).thenReturn("first");
+ Mockito.when(first.getIvmRefreshMetricValues()).thenReturn(new
IvmRefreshSummary.MetricValues(1, 1, 0, true, 0));
+ Mockito.when(second.isIvm()).thenReturn(true);
+ Mockito.when(second.getId()).thenReturn(8L);
+ Mockito.when(second.getName()).thenReturn("second");
+ Mockito.when(second.getIvmRefreshMetricValues())
+ .thenReturn(new IvmRefreshSummary.MetricValues(0, 0, 0, false,
0));
+ ChangelogMonitor monitor = new ChangelogMonitor(env);
+
+ boolean enabled = Config.enable_changelog_monitor;
+ int interval = Config.changelog_monitor_interval_seconds;
+ try {
+ Config.enable_changelog_monitor = true;
+ Config.changelog_monitor_interval_seconds = 1;
+ monitor.sample(0);
+ Assertions.assertNull(monitor.getSnapshot());
+ Mockito.verify(env, Mockito.never()).getInternalCatalog();
+
+ Mockito.when(env.isMaster()).thenReturn(true);
+ Assertions.assertNull(monitor.getSnapshot());
+ monitor.sample(0);
+ ChangelogMonitorSnapshot snapshot = monitor.getSnapshot();
+ Assertions.assertEquals(List.of(7L, 8L),
+
snapshot.ivmRefreshes().stream().map(ChangelogMonitorSnapshot.IvmRefresh::mvId).toList());
+ Assertions.assertSame(snapshot, monitor.getSnapshot());
+ Mockito.verify(env).getInternalCatalog();
+
+ Mockito.when(second.getIvmRefreshMetricValues()).thenThrow(new
IllegalStateException("test failure"));
+ monitor.sample(1_000_000_000L);
+ Assertions.assertSame(snapshot, monitor.getSnapshot());
+
+ Mockito.when(database.getTables()).thenReturn(List.of(first));
+ Mockito.when(first.getName()).thenReturn("renamed");
+ monitor.sample(2_000_000_000L);
+ Assertions.assertEquals(List.of("renamed"),
+ monitor.getSnapshot().ivmRefreshes().stream()
+
.map(ChangelogMonitorSnapshot.IvmRefresh::mvName).toList());
+
+ Config.enable_changelog_monitor = false;
+ Assertions.assertNull(monitor.getSnapshot());
+ monitor.reset();
+ Config.enable_changelog_monitor = true;
+ Assertions.assertNull(monitor.getSnapshot());
+ monitor.sample(0);
+ Assertions.assertNotNull(monitor.getSnapshot());
+ Mockito.when(env.isMaster()).thenReturn(false);
+ Assertions.assertNull(monitor.getSnapshot());
+ } finally {
+ Config.enable_changelog_monitor = enabled;
+ Config.changelog_monitor_interval_seconds = interval;
+ }
+ }
+
+ @Test
+ void disablingThroughExperimentalConfigAliasClearsSnapshot() throws
Exception {
+ Env env = new Env(false) {
+ @Override
+ public boolean isMaster() {
+ return true;
+ }
+
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+ };
+ ChangelogMonitor monitor = env.getChangelogMonitor();
+
+ Field configField = Config.class.getField("enable_changelog_monitor");
+ String alias = "experimental_enable_changelog_monitor";
+ Map<String, Field> oldFields = ConfigBase.confFields;
+ boolean enabled = Config.enable_changelog_monitor;
+ try {
+ ConfigBase.confFields = Map.of(alias, configField);
+ Config.enable_changelog_monitor = true;
+ monitor.sample(0);
+ Assertions.assertNotNull(monitor.getSnapshot());
+
+ env.setMutableConfigWithCallback(alias, "false");
+ Assertions.assertNull(monitor.getSnapshot());
+ env.setMutableConfigWithCallback(alias, "true");
+ Assertions.assertNull(monitor.getSnapshot());
+
+ monitor.sample(0);
+ Assertions.assertNotNull(monitor.getSnapshot());
+ } finally {
+ Config.enable_changelog_monitor = enabled;
+ ConfigBase.confFields = oldFields;
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/metric/IvmRefreshSnapshotMetricsTest.java
b/fe/fe-core/src/test/java/org/apache/doris/metric/IvmRefreshSnapshotMetricsTest.java
new file mode 100644
index 00000000000..7c2508dd305
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/metric/IvmRefreshSnapshotMetricsTest.java
@@ -0,0 +1,62 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.metric;
+
+import org.apache.doris.changelog.ChangelogMonitorSnapshot;
+import org.apache.doris.mtmv.ivm.IvmRefreshSummary;
+
+import com.google.gson.JsonParser;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+class IvmRefreshSnapshotMetricsTest {
+ @Test
+ void rendersPerViewSamplesWithTypesAndEscapedLabels() {
+ String mvName = "a\"quoted";
+ ChangelogMonitorSnapshot snapshot = new ChangelogMonitorSnapshot(1,
List.of(
+ new ChangelogMonitorSnapshot.IvmRefresh("sales", mvName, 1,
+ new IvmRefreshSummary.MetricValues(1, 2, 3, true,
125)),
+ new ChangelogMonitorSnapshot.IvmRefresh("sales", "fresh", 2,
+ new IvmRefreshSummary.MetricValues(0, 0, 0, false, 0)),
+ new ChangelogMonitorSnapshot.IvmRefresh("sales", "zero", 3,
+ new IvmRefreshSummary.MetricValues(0, 0, 0, true,
0))));
+
+ MetricVisitor prometheus = new PrometheusMetricVisitor();
+ IvmRefreshSnapshotMetrics.visit(prometheus, snapshot);
+ String result = prometheus.finish();
+ Assertions.assertTrue(result.contains("# TYPE
doris_fe_ivm_refresh_failed_tasks_total counter"));
+ Assertions.assertTrue(result.contains("# TYPE
doris_fe_ivm_refresh_fallbacks_total counter"));
+ Assertions.assertTrue(result.contains("# TYPE
doris_fe_ivm_consecutive_failures gauge"));
+ Assertions.assertTrue(result.contains("# TYPE
doris_fe_ivm_refresh_duration_seconds gauge"));
+
Assertions.assertTrue(result.contains("doris_fe_ivm_refresh_duration_seconds"
+ + "{db_name=\"sales\", mv_name=\"a\\\"quoted\", mv_id=\"1\"}
0.125"));
+
Assertions.assertFalse(result.contains("doris_fe_ivm_refresh_duration_seconds"
+ + "{db_name=\"sales\", mv_name=\"fresh\", mv_id=\"2\"}"));
+
Assertions.assertTrue(result.contains("doris_fe_ivm_refresh_duration_seconds"
+ + "{db_name=\"sales\", mv_name=\"zero\", mv_id=\"3\"} 0.0"));
+
+ MetricVisitor json = new JsonMetricVisitor();
+ IvmRefreshSnapshotMetrics.visit(json, snapshot);
+ var samples = JsonParser.parseString(json.finish()).getAsJsonArray();
+ Assertions.assertEquals(11, samples.size());
+ Assertions.assertEquals(mvName,
+
samples.get(0).getAsJsonObject().getAsJsonObject("tags").get("mv_name").getAsString());
+ }
+}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/AlterMTMVTest.java
b/fe/fe-core/src/test/java/org/apache/doris/mtmv/AlterMTMVTest.java
index 9e1e3d5271d..474b5c82402 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/AlterMTMVTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/AlterMTMVTest.java
@@ -26,6 +26,10 @@ import org.apache.doris.catalog.info.TableNameInfo;
import org.apache.doris.common.Config;
import org.apache.doris.common.DdlException;
import org.apache.doris.common.util.DebugPointUtil;
+import org.apache.doris.job.common.TaskStatus;
+import org.apache.doris.job.extensions.mtmv.MTMVTask;
+import org.apache.doris.job.extensions.mtmv.MTMVTask.MTMVTaskTriggerMode;
+import org.apache.doris.job.extensions.mtmv.MTMVTaskContext;
import org.apache.doris.mtmv.MTMVRefreshEnum.RefreshMethod;
import org.apache.doris.mtmv.ivm.IvmInfo;
import org.apache.doris.mtmv.ivm.IvmUtil;
@@ -540,6 +544,61 @@ public class AlterMTMVTest extends TestWithFeService {
Assertions.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty());
}
+ @Test
+ public void testReplayIvmTaskResultAfterRename() throws Exception {
+ createDatabaseAndUse("ivm_rename_replay_test");
+ createTableWithChangelog("CREATE TABLE rename_base (k1 int, v1 int) "
+ + "DUPLICATE KEY(k1) DISTRIBUTED BY HASH(k1) BUCKETS 1 "
+ + "PROPERTIES ('replication_num' = '1', 'changelog.enable' =
'true')");
+ String createMv = "CREATE MATERIALIZED VIEW ivm_old_name "
+ + "BUILD DEFERRED REFRESH INCREMENTAL ON MANUAL DISTRIBUTED BY
RANDOM BUCKETS 1 "
+ + "PROPERTIES ('replication_num' = '1') AS SELECT k1, v1 FROM
rename_base";
+ createMvByNereids(createMv);
+ Database db =
Env.getCurrentInternalCatalog().getDbOrDdlException("ivm_rename_replay_test");
+ MTMV mv = (MTMV) db.getTableOrMetaException("ivm_old_name");
+ AlterMTMV oldNameResult = failedIvmTaskResult(db.getId(), mv, 1);
+ alterMv("ALTER MATERIALIZED VIEW ivm_old_name RENAME ivm_new_name");
+
+ // The old name no longer resolves. A later result must still advance
the summary.
+ replayFromJournal(oldNameResult);
+ Assertions.assertEquals(0L,
mv.getIvmRefreshMetricValues().failedTaskCount());
+
+ replayFromJournal(failedIvmTaskResult(db.getId(), mv, 2));
+ Assertions.assertEquals("ivm_new_name", mv.getName());
+ Assertions.assertEquals(1L,
mv.getIvmRefreshMetricValues().failedTaskCount());
+ Assertions.assertEquals(1,
mv.getIvmRefreshMetricValues().consecutiveFailures());
+
+ createMvByNereids(createMv);
+ MTMV replacement = (MTMV) db.getTableOrMetaException("ivm_old_name");
+ Assertions.assertNotEquals(mv.getId(), replacement.getId());
+ replayFromJournal(oldNameResult);
+ Assertions.assertEquals(0L,
replacement.getIvmRefreshMetricValues().failedTaskCount());
+
+ // A late live result addressed by the reused name must not get a
sequence from this MV.
+ oldNameResult.getTask().setIvmSummarySeq(0);
+ Env.getCurrentEnv().getAlterInstance().processAlterMTMV(oldNameResult,
false);
+ Assertions.assertEquals(0L,
oldNameResult.getTask().getIvmSummarySeq());
+ replayFromJournal(oldNameResult);
+ Assertions.assertEquals(0,
replacement.getIvmRefreshMetricValues().consecutiveFailures());
+
+ replayFromJournal(failedIvmTaskResult(db.getId(), replacement, 1));
+ Assertions.assertEquals(1L,
replacement.getIvmRefreshMetricValues().failedTaskCount());
+ }
+
+ private static AlterMTMV failedIvmTaskResult(long dbId, MTMV mv, long seq)
{
+ AlterMTMV result = new AlterMTMV(new
TableNameInfo(mv.getQualifiedDbName(), mv.getName()),
+ MTMVAlterOpType.ADD_TASK);
+ MTMVTask task = new MTMVTask(dbId, mv.getId(),
MTMVTaskContext.forMvDefault(MTMVTaskTriggerMode.SYSTEM));
+ task.setStatus(TaskStatus.FAILED);
+ task.setStartTimeMs(1_000L);
+ task.setFinishTimeMs(2_000L);
+ task.setIvmSummarySeq(seq);
+ result.setTask(task);
+ result.setRelation(mv.getRelation());
+ result.setPartitionSnapshots(Map.of());
+ return result;
+ }
+
private static void replayFromJournal(AlterMTMV alter) throws Exception {
AlterMTMV replayed;
try (DataInputStream in = new DataInputStream(new
ByteArrayInputStream(journalBytes(alter)))) {
diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java
b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java
index f3d4fd192ba..9215ec38454 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java
@@ -94,7 +94,7 @@ public class MTMVTest {
+ "querySql='select * from xxx;', "
+ "status=MTMVStatus{state=INIT, schemaChangeDetail='null',
refreshState=INIT}, "
+ "jobInfo=MTMVJobInfo{jobName='job1', "
- + "historyTasks=[MTMVTask{dbId=0, mtmvId=0, taskContext=null, "
+ + "historyTasks=[MTMVTask{dbId=0, mtmvId=1, taskContext=null, "
+ "needRefreshPartitions=null, completedPartitions=null,
refreshMode=null} "
+ "AbstractTask{jobId=null, taskId=1, status=null,
createTimeMs=null, startTimeMs=null, "
+ "finishTimeMs=null, taskType=null, errMsg='null'}]},
mvProperties={}, "
@@ -557,6 +557,7 @@ public class MTMVTest {
Assertions.assertEquals(5, journaled.size());
IvmRefreshSummary summary = Deencapsulation.getField(master,
"ivmRefreshSummary");
Assertions.assertEquals(0, summary.getConsecutiveFailures());
+ Assertions.assertEquals(2L, summary.metricValues().failedTaskCount());
Assertions.assertEquals(IvmRefreshFailureStage.EXECUTION_FAILED.name(),
summary.getLastFailureReason());
Assertions.assertEquals(IvmRefreshMethod.MIXED,
summary.getLastRefreshMethod());
Assertions.assertEquals(1L, summary.getFallbackCount());
@@ -566,6 +567,61 @@ public class MTMVTest {
Assertions.assertEquals(GsonUtils.GSON.toJson(summary),
GsonUtils.GSON.toJson(replayed));
}
+ @Test
+ public void testIvmSummaryCountsOnlyNewResultsAcrossImageAndReplay()
throws Exception {
+ MTMV master = buildSerializableMTMV();
+ master.getIvmInfo().setEnableIvm(true);
+ MTMVTask legacy = endedTask(master, TaskStatus.FAILED,
IvmRefreshMethod.NONE, null, null);
+ withMockedEditLog(Lists.newArrayList(),
+ () ->
Assertions.assertTrue(master.addTaskResult(taskResult(master, legacy), true)));
+ Assertions.assertEquals(new IvmRefreshSummary.MetricValues(1, 0, 0,
true, 1000),
+ master.getIvmRefreshMetricValues());
+
+ JsonObject oldImage =
JsonParser.parseString(GsonUtils.GSON.toJson(master)).getAsJsonObject();
+ oldImage.getAsJsonObject("irs").remove("ftc");
+ oldImage.getAsJsonObject("irs").remove("lass");
+ MTMV follower = GsonUtils.GSON.fromJson(oldImage, MTMV.class);
+ Assertions.assertEquals(master.getIvmRefreshMetricValues(),
follower.getIvmRefreshMetricValues());
+
+ MTMVTask failed = endedTask(master, TaskStatus.FAILED,
IvmRefreshMethod.COMPLETE, null,
+ IvmFailureReason.CHANGELOG_BROKEN.name());
+ failed.setTaskId(99L);
+ MTMVTask recovered = endedTask(master, TaskStatus.SUCCESS,
IvmRefreshMethod.NONE, null, null);
+ recovered.setTaskId(3L);
+ recovered.setFinishTimeMs(1125L);
+ List<AlterMTMV> records = Lists.newArrayList();
+ int historyCount = Config.max_persistence_task_count;
+ try {
+ Config.max_persistence_task_count = 0;
+ withMockedEditLog(records, () -> {
+ Assertions.assertTrue(master.addTaskResult(taskResult(master,
failed), false));
+ Assertions.assertTrue(master.addTaskResult(taskResult(master,
recovered), false));
+ Assertions.assertTrue(master.addTaskResult(taskResult(master,
failed), false));
+ });
+ } finally {
+ Config.max_persistence_task_count = historyCount;
+ }
+ IvmRefreshSummary.MetricValues expected = new
IvmRefreshSummary.MetricValues(0, 1, 1, true, 125);
+ Assertions.assertEquals(expected, master.getIvmRefreshMetricValues());
+ Assertions.assertEquals(1L, failed.getIvmSummarySeq());
+ Assertions.assertEquals(2L, recovered.getIvmSummarySeq());
+
+ withMockedEditLog(Lists.newArrayList(), () -> {
+ for (AlterMTMV record : records) {
+ AlterMTMV replayed =
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(record), AlterMTMV.class);
+ Assertions.assertTrue(follower.addTaskResult(replayed, true));
+ }
+ });
+ Assertions.assertEquals(expected,
follower.getIvmRefreshMetricValues());
+
+ MTMV promoted =
GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(follower), MTMV.class);
+ MTMVTask next = endedTask(promoted, TaskStatus.FAILED,
IvmRefreshMethod.NONE, null, null);
+ withMockedEditLog(Lists.newArrayList(),
+ () ->
Assertions.assertTrue(promoted.addTaskResult(taskResult(promoted, next),
false)));
+ Assertions.assertEquals(3L, next.getIvmSummarySeq());
+ Assertions.assertEquals(2L,
promoted.getIvmRefreshMetricValues().failedTaskCount());
+ }
+
/** An MV that is not an IVM MV records its task results without a refresh
summary. */
@Test
public void testAPlainMvKeepsNoRefreshSummary() {
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/mtmv/ivm/IvmRefreshSummaryTest.java
b/fe/fe-core/src/test/java/org/apache/doris/mtmv/ivm/IvmRefreshSummaryTest.java
index 6e06f666121..e96ea04dea3 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/mtmv/ivm/IvmRefreshSummaryTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/mtmv/ivm/IvmRefreshSummaryTest.java
@@ -35,15 +35,18 @@ public class IvmRefreshSummaryTest {
public void testConsecutiveFailuresAreTheFailuresSinceTheLatestSuccess() {
IvmRefreshSummary summary = new IvmRefreshSummary();
- summary.update(failed(1000L, 2000L,
IvmRefreshFailureStage.EXECUTION_FAILED.name(), "first"));
- summary.update(failed(3000L, 4000L,
IvmRefreshFailureStage.EXECUTION_FAILED.name(), "second"));
+ summary.update(failed(1000L, 2000L,
IvmRefreshFailureStage.EXECUTION_FAILED.name(), "first"), false);
+ summary.update(failed(3000L, 4000L,
IvmRefreshFailureStage.EXECUTION_FAILED.name(), "second"), false);
Assertions.assertEquals(2, summary.getConsecutiveFailures());
- summary.update(canceled());
+ Assertions.assertEquals(2L, summary.metricValues().failedTaskCount());
+ summary.update(canceled(), false);
Assertions.assertEquals(2, summary.getConsecutiveFailures());
+ Assertions.assertEquals(2L, summary.metricValues().failedTaskCount());
- summary.update(succeeded(5000L, 6000L, IvmRefreshMethod.NONE));
+ summary.update(succeeded(5000L, 6000L, IvmRefreshMethod.NONE), false);
Assertions.assertEquals(0, summary.getConsecutiveFailures());
- summary.update(failed(7000L, 8000L,
IvmRefreshFailureStage.OTHER.name(), "third"));
+ Assertions.assertEquals(2L, summary.metricValues().failedTaskCount());
+ summary.update(failed(7000L, 8000L,
IvmRefreshFailureStage.OTHER.name(), "third"), false);
Assertions.assertEquals(1, summary.getConsecutiveFailures());
}
@@ -57,7 +60,7 @@ public class IvmRefreshSummaryTest {
IvmRefreshSummary summary = new IvmRefreshSummary();
String longMessage = Strings.repeat("x",
IvmRefreshSummary.MAX_ERROR_MESSAGE_LENGTH * 2);
- summary.update(failed(1000L, 1500L,
IvmFailureReason.MIN_MAX_BOUNDARY_HIT.name(), longMessage));
+ summary.update(failed(1000L, 1500L,
IvmFailureReason.MIN_MAX_BOUNDARY_HIT.name(), longMessage), false);
Assertions.assertEquals(1500L, summary.getLastFailureTimeMs());
Assertions.assertEquals(IvmFailureReason.MIN_MAX_BOUNDARY_HIT.name(),
summary.getLastFailureReason());
Assertions.assertEquals(IvmRefreshSummary.MAX_ERROR_MESSAGE_LENGTH,
summary.getLastErrorMessage().length());
@@ -66,7 +69,7 @@ public class IvmRefreshSummaryTest {
Assertions.assertEquals(500L, summary.getLastRefreshDurationMs());
Assertions.assertEquals(0L, summary.getLastSuccessTimeMs());
- summary.update(succeeded(2000L, 4500L, IvmRefreshMethod.COMPLETE));
+ summary.update(succeeded(2000L, 4500L, IvmRefreshMethod.COMPLETE),
false);
Assertions.assertEquals(4500L, summary.getLastSuccessTimeMs());
Assertions.assertEquals(IvmRefreshMethod.COMPLETE,
summary.getLastRefreshMethod());
Assertions.assertEquals(2500L, summary.getLastRefreshDurationMs());
@@ -74,7 +77,7 @@ public class IvmRefreshSummaryTest {
Assertions.assertEquals(IvmFailureReason.MIN_MAX_BOUNDARY_HIT.name(),
summary.getLastFailureReason());
// A canceled task has no finish time, so it changes neither the
latest method nor the latest duration.
- summary.update(canceled());
+ summary.update(canceled(), false);
Assertions.assertEquals(IvmRefreshMethod.COMPLETE,
summary.getLastRefreshMethod());
Assertions.assertEquals(2500L, summary.getLastRefreshDurationMs());
}
@@ -84,18 +87,18 @@ public class IvmRefreshSummaryTest {
public void testFallbacksCountTheTasksThatFellBack() {
IvmRefreshSummary summary = new IvmRefreshSummary();
- summary.update(succeeded(1000L, 2000L, IvmRefreshMethod.INCREMENTAL));
+ summary.update(succeeded(1000L, 2000L, IvmRefreshMethod.INCREMENTAL),
false);
Assertions.assertEquals(0L, summary.getFallbackCount());
MTMVTask fellBack = succeeded(3000L, 4000L, IvmRefreshMethod.COMPLETE);
fellBack(fellBack, IvmFailureReason.MIN_MAX_BOUNDARY_HIT.name());
- summary.update(fellBack);
+ summary.update(fellBack, false);
MTMVTask fellBackAndFailed = failed(5000L, 6000L,
IvmRefreshFailureStage.EXECUTION_FAILED.name(), "failed");
fellBack(fellBackAndFailed, IvmFailureReason.CHANGELOG_BROKEN.name());
- summary.update(fellBackAndFailed);
+ summary.update(fellBackAndFailed, false);
MTMVTask fellBackAndCanceled = canceled();
fellBack(fellBackAndCanceled,
IvmFailureReason.PLAN_SIGNATURE_MISMATCH.name());
- summary.update(fellBackAndCanceled);
+ summary.update(fellBackAndCanceled, false);
Assertions.assertEquals(2L, summary.getFallbackCount());
Assertions.assertEquals(IvmFailureReason.CHANGELOG_BROKEN.name(),
summary.getLastFallbackReason());
@@ -107,12 +110,12 @@ public class IvmRefreshSummaryTest {
public void testOnlyASuccessMarksTheMvRefreshed() {
IvmRefreshSummary summary = new IvmRefreshSummary();
- summary.update(failed(1000L, 2000L,
IvmRefreshFailureStage.OTHER.name(), "failed"));
- summary.update(canceled());
+ summary.update(failed(1000L, 2000L,
IvmRefreshFailureStage.OTHER.name(), "failed"), false);
+ summary.update(canceled(), false);
Assertions.assertFalse(summary.hasSucceeded());
- summary.update(succeeded(3000L, 4000L, IvmRefreshMethod.COMPLETE));
- summary.update(failed(5000L, 6000L,
IvmRefreshFailureStage.OTHER.name(), "failed"));
+ summary.update(succeeded(3000L, 4000L, IvmRefreshMethod.COMPLETE),
false);
+ summary.update(failed(5000L, 6000L,
IvmRefreshFailureStage.OTHER.name(), "failed"), false);
Assertions.assertTrue(summary.hasSucceeded());
}
@@ -122,7 +125,21 @@ public class IvmRefreshSummaryTest {
MTMVTask running = new MTMVTask();
running.setStatus(TaskStatus.RUNNING);
- Assertions.assertThrows(IllegalStateException.class, () -> new
IvmRefreshSummary().update(running));
+ Assertions.assertThrows(IllegalStateException.class, () -> new
IvmRefreshSummary().update(running, false));
+ }
+
+ @Test
+ public void testReplayContinuesAfterMissingSummarySequence() {
+ IvmRefreshSummary summary = new IvmRefreshSummary();
+ MTMVTask later = failed(1000, 2000,
IvmRefreshFailureStage.OTHER.name(), "later");
+ later.setIvmSummarySeq(2L);
+ summary.update(later, true);
+
+ MTMVTask older = failed(1000, 1100,
IvmRefreshFailureStage.OTHER.name(), "older");
+ older.setIvmSummarySeq(1L);
+ summary.update(older, true);
+ Assertions.assertEquals(new IvmRefreshSummary.MetricValues(1, 1, 0,
true, 1000),
+ summary.metricValues());
}
private static MTMVTask succeeded(long startTimeMs, long finishTimeMs,
IvmRefreshMethod method) {
diff --git
a/regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_method_metrics.groovy
b/regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_method_metrics.groovy
index 8f9882038c5..7fdb703a9a2 100644
--- a/regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_method_metrics.groovy
+++ b/regression-test/suites/mtmv_p0/ivm/test_ivm_refresh_method_metrics.groovy
@@ -18,6 +18,8 @@
import org.apache.doris.regression.util.Http
import org.awaitility.Awaitility
+import java.util.concurrent.Callable
+
import static java.util.concurrent.TimeUnit.SECONDS
/**
@@ -53,13 +55,24 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
String mvName = "ivm_refresh_method_metrics_mv"
String masterMetricsUrl =
"http://${getMasterIp()}:${getMasterPort()}/metrics"
- // The value of every doris_fe_ivm_ series the Master exports, by the
series.
- def ivmSeries = {
+ def clusterMetrics = [
+ "doris_fe_ivm_refresh_tasks_total",
+ "doris_fe_ivm_refresh_duration_seconds_total",
+ "doris_fe_ivm_fallbacks_total",
+ "doris_fe_ivm_refresh_failures_total",
+ "doris_fe_ivm_schedule_rejected_total"
+ ] as Set
+ def ivmSeries = { Set names ->
Map<String, Double> values = [:]
for (String line : Http.GET(masterMetricsUrl, false,
false).readLines()) {
if (line.startsWith("doris_fe_ivm_")) {
int split = line.lastIndexOf(' ')
- values.put(line.substring(0, split),
Double.parseDouble(line.substring(split + 1)))
+ String series = line.substring(0, split)
+ int labelStart = series.indexOf('{')
+ String metric = labelStart < 0 ? series : series.substring(0,
labelStart)
+ if (names.contains(metric)) {
+ values.put(series, Double.parseDouble(line.substring(split
+ 1)))
+ }
}
}
return values
@@ -94,10 +107,10 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
// and the run times added, which vary from run to run and are returned
apart, by method.
def refresh = { String statement ->
String previousTaskId = latestTaskId()
- Map<String, Double> before = ivmSeries()
+ Map<String, Double> before = ivmSeries(clusterMetrics)
sql statement
String taskId = waitForNewTask(previousTaskId)
- Map<String, Double> after = ivmSeries()
+ Map<String, Double> after = ivmSeries(clusterMetrics)
Map<String, Double> counted = [:]
Map<String, Double> seconds = [:]
String durationPrefix =
'doris_fe_ivm_refresh_duration_seconds_total{method="'
@@ -169,8 +182,50 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
GROUP BY dt
"""
+ sql "DROP MATERIALIZED VIEW IF EXISTS ivm_refresh_summary_idle_mv"
+ sql """
+ CREATE MATERIALIZED VIEW ivm_refresh_summary_idle_mv
+ BUILD DEFERRED REFRESH INCREMENTAL FALLBACK ON MANUAL
+ PARTITION BY(dt)
+ DISTRIBUTED BY HASH(dt) BUCKETS 1
+ PROPERTIES ("replication_num" = "1", "ivm_minmax_top_k" = "1")
+ AS SELECT dt, MIN(v) AS min_v, MAX(v) AS max_v, COUNT(*) AS cnt
+ FROM ivm_refresh_method_metrics_t
+ GROUP BY dt
+ """
+ def mvIds = sql_return_maparray("""
+ SELECT Id, Name FROM mv_infos('database'='${context.dbName}')
+ WHERE Name IN ('${mvName}', 'ivm_refresh_summary_idle_mv')
+ """).collectEntries { [(it.Name.toString()): it.Id.toString()] }
+ assertEquals(2, mvIds.size())
+
+ String consecutive = "doris_fe_ivm_consecutive_failures"
+ String failures = "doris_fe_ivm_refresh_failed_tasks_total"
+ String fallbacks = "doris_fe_ivm_refresh_fallbacks_total"
+ String duration = "doris_fe_ivm_refresh_duration_seconds"
+ def summaryMetrics = [consecutive, failures, fallbacks, duration] as Set
+ def summaryKey = { String metric, String name ->
+ "${metric}{db_name=\"${context.dbName}\", mv_name=\"${name}\",
mv_id=\"${mvIds[name]}\"}".toString()
+ }
+ def matchesSummary = { Map<String, Double> samples, String name, int
streak, int failed, int fallback,
+ boolean completed ->
+ Double elapsed = samples[summaryKey(duration, name)]
+ samples[summaryKey(consecutive, name)] == streak
+ && samples[summaryKey(failures, name)] == failed
+ && samples[summaryKey(fallbacks, name)] == fallback
+ && (completed ? elapsed != null && elapsed >= 0 : elapsed ==
null)
+ }
+ def waitForSummary = { int streak, int failed, int fallback, boolean
completed ->
+ Awaitility.await().atMost(120, SECONDS).pollInterval(2,
SECONDS).until({
+ Map<String, Double> samples = ivmSeries(summaryMetrics)
+ matchesSummary(samples, mvName, streak, failed, fallback,
completed) &&
+ matchesSummary(samples, "ivm_refresh_summary_idle_mv", 0,
0, 0, false)
+ } as Callable<Boolean>)
+ }
+ waitForSummary(0, 0, 0, false)
+
// Every series is there from 0, before a task has counted in it.
- Map<String, Double> initial = ivmSeries()
+ Map<String, Double> initial = ivmSeries(clusterMetrics)
assertTrue(initial.containsKey(tasks("canceled", "mixed")),
initial.toString())
assertTrue(initial.containsKey('doris_fe_ivm_fallbacks_total{reason="incomplete_refresh_snapshot"}'))
assertTrue(initial.containsKey('doris_fe_ivm_refresh_failures_total{reason="partition_sync_failed"}'))
@@ -182,6 +237,7 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
qt_first_baseline_task taskQuery(baselineTask)
assertEquals([(tasks("success", "complete")): 1.0d], baselineCounted)
assertEquals(["complete"], baselineSeconds.keySet().toList())
+ waitForSummary(0, 0, 0, true)
// 2. New rows are caught up incrementally, and a refresh with nothing new
to catch up commits nothing.
sql """INSERT INTO ivm_refresh_method_metrics_t VALUES ('2026-03-10', 5,
50)"""
@@ -201,6 +257,7 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
qt_strict_failure_task taskQuery(strictTask)
assertEquals([(tasks("failed", "none")): 1.0d,
'doris_fe_ivm_refresh_failures_total{reason="min_max_boundary_hit"}': 1.0d],
strictCounted)
+ waitForSummary(1, 1, 0, true)
// 4. Allowed to fall back, the same refresh rebuilds the MV: a fallback,
for the reason the delta gave up.
def (fallbackTask, fallbackCounted, fallbackSeconds) =
@@ -208,6 +265,7 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
qt_fallback_task taskQuery(fallbackTask)
assertEquals([(tasks("success", "complete")): 1.0d,
'doris_fe_ivm_fallbacks_total{reason="min_max_boundary_hit"}': 1.0d],
fallbackCounted)
+ waitForSummary(0, 1, 1, true)
order_qt_mv_after_fallback """SELECT dt, min_v, max_v, cnt FROM
${mvName}"""
order_qt_base_after_fallback """
SELECT dt, MIN(v), MAX(v), COUNT(*) FROM ivm_refresh_method_metrics_t
GROUP BY dt
@@ -217,6 +275,7 @@ suite("test_ivm_refresh_method_metrics", "nonConcurrent") {
def (completeTask, completeCounted, completeSeconds) = refresh("REFRESH
MATERIALIZED VIEW ${mvName} COMPLETE")
qt_complete_task taskQuery(completeTask)
assertEquals([(tasks("success", "complete")): 1.0d], completeCounted)
+ waitForSummary(0, 1, 1, true)
// 6. Truncating a base partition leaves its MV partition needing a
rebuild, which no delta can make: an incremental
// refresh rebuilds it first and then catches up the other partitions,
refreshing the MV in two ways at once.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]