yujun777 commented on code in PR #71199:
URL: https://github.com/apache/doris/pull/71199#discussion_r4788562487


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/SchemaTable.java:
##########
@@ -915,6 +915,9 @@ public class SchemaTable extends Table {
                             .column("CONSUMPTION_STATUS", 
ScalarType.createVarchar(NAME_CHAR_LEN))
                             .column("LAG", 
ScalarType.createVarchar(NAME_CHAR_LEN))
                             .column("LAST_CONSUMPTION_TIME", 
ScalarType.createType(PrimitiveType.BIGINT))
+                            .column("PENDING_AGE_SECONDS", 
ScalarType.createType(PrimitiveType.DOUBLE))

Review Comment:
   Doris rolling upgrades follow the documented BE-first, FE-second order (the 
same contract used by other information_schema column additions such as #69557 
on catalog_meta_cache_statistics, where SchemaTable.TABLE_MAP is static). 
During a BE-first upgrade, the mixed-version state is New BE + Old FE, which 
our SchemaTableStreamConsumptionScanner already supports by padding legacy 
7-column responses and preserving legacy projections.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,179 @@
+// 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.catalog.stream;
+
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.changelog.ChangelogUtils;
+import org.apache.doris.tso.TSOTimestamp;
+
+/**
+ * Shared checkpoint resumability rules for OLAP table streams, used by both 
the scan rewrite path
+ * and stream monitoring / consumption diagnostics.
+ */
+public final class StreamResumabilityChecker {
+    private StreamResumabilityChecker() {
+    }
+
+    public enum Status {
+        RESUMABLE(1),
+        CANNOT_RESUME(0),
+        UNKNOWN(-1);
+
+        private final int code;
+
+        Status(int code) {
+            this.code = code;
+        }
+
+        public int code() {
+            return code;
+        }
+    }
+
+    public enum Reason {
+        NONE(""),
+        BASE_TABLE_MISSING("BASE_TABLE_MISSING"),
+        STREAM_DISABLED("STREAM_DISABLED"),
+        STREAM_STALE("STREAM_STALE"),
+        CHANGELOG_DISABLED("CHANGELOG_DISABLED"),
+        TTL_EXPIRED("TTL_EXPIRED"),
+        NO_BASELINE_OFFSET("NO_BASELINE_OFFSET"),
+        TSO_UNINITIALIZED("TSO_UNINITIALIZED"),
+        STATE_UNAVAILABLE("STATE_UNAVAILABLE");
+
+        private final String code;
+
+        Reason(String code) {
+            this.code = code;
+        }
+
+        public String code() {
+            return code;
+        }
+    }
+
+    public record Result(Status status, Reason reason) {
+        public static Result resumable() {
+            return new Result(Status.RESUMABLE, Reason.NONE);
+        }
+
+        public static Result cannotResume(Reason reason) {
+            return new Result(Status.CANNOT_RESUME, reason);
+        }
+
+        public static Result unknown(Reason reason) {
+            return new Result(Status.UNKNOWN, reason);
+        }
+    }
+
+    /** Compute the inclusive TTL expiration cutoff TSO, or null if TTL is 
disabled or referenceTso is unavailable. */
+    public static Long calculateCutoffTso(OlapTable baseTable, Long 
referenceTso) {
+        if (baseTable == null || !baseTable.hasChangelogTtl()) {
+            return null;
+        }
+        if (referenceTso == null || referenceTso <= 0) {
+            return null;
+        }
+        return TSOTimestamp.calculateCutoff(referenceTso, 
baseTable.getChangelogConfig().getTtlSeconds());
+    }
+
+    /** Check stream-wide prerequisites before inspecting individual 
partitions. */
+    public static Result checkStreamLevel(OlapTableStream stream, OlapTable 
baseTable) {
+        if (stream.isDisabled()) {
+            return Result.cannotResume(Reason.STREAM_DISABLED);
+        }
+        if (stream.isStale()) {
+            return Result.cannotResume(Reason.STREAM_STALE);
+        }
+        if (baseTable == null || baseTable.isDropped) {
+            return Result.cannotResume(Reason.BASE_TABLE_MISSING);
+        }
+        if (!baseTable.hasChangelog()) {
+            return Result.cannotResume(Reason.CHANGELOG_DISABLED);
+        }
+        return Result.resumable();
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     * Even for scan types that clip an expired start TSO instead of throwing, 
clipping means
+     * incomplete resumption and reports {@link Status#CANNOT_RESUME}.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, boolean hasData,
+            Long offset, Long historicalTso, long endTso, long 
oldestPendingTimeMs, long provenOldestWriteTimeMs) {
+        // Initial-snapshot partitions read the base table directly and do not 
depend on changelog retention.
+        if (historicalTso != null) {
+            return Result.resumable();
+        }
+        if (!hasData) {
+            return Result.resumable();
+        }
+        // Caught-up partitions (offset == endTso) are skipped by incremental 
scans and do not read changelog.
+        if (StreamPendingAgeTracker.isCaughtUp(hasData, offset, historicalTso, 
endTso)) {
+            return Result.resumable();
+        }
+        if (!hasChangelogTtl) {
+            return Result.resumable();
+        }
+        if (cutoffTso == null) {
+            return Result.unknown(Reason.TSO_UNINITIALIZED);
+        }
+        if (offset != null && offset >= 0) {
+            Long startTso = TSOTimestamp.toExclusiveBound(offset);
+            if (ChangelogUtils.isStartTsoExpired(startTso, cutoffTso)) {

Review Comment:
   Fixed in 7fa3824b395. Added 
StreamResumabilityChecker.rejectsExpiredStart(stream, baseTable) matching 
NormalizeOlapTableStreamScan.applyChangelogTtl(): MIN_DELTA and IVM streams 
continue to report CANNOT_RESUME (TTL_EXPIRED) for any expired start TSO, while 
clipping modes (user APPEND_ONLY / DETAIL streams) evaluate the pending-write 
bounds (RESUMABLE when all pending writes are proven newer than cutoff, 
CANNOT_RESUME when a pending write is expired, UNKNOWN otherwise). Updated both 
regression suites and added unit tests in StreamResumabilityCheckerTest.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,179 @@
+// 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.catalog.stream;
+
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.changelog.ChangelogUtils;
+import org.apache.doris.tso.TSOTimestamp;
+
+/**
+ * Shared checkpoint resumability rules for OLAP table streams, used by both 
the scan rewrite path
+ * and stream monitoring / consumption diagnostics.
+ */
+public final class StreamResumabilityChecker {
+    private StreamResumabilityChecker() {
+    }
+
+    public enum Status {
+        RESUMABLE(1),
+        CANNOT_RESUME(0),
+        UNKNOWN(-1);
+
+        private final int code;
+
+        Status(int code) {
+            this.code = code;
+        }
+
+        public int code() {
+            return code;
+        }
+    }
+
+    public enum Reason {
+        NONE(""),
+        BASE_TABLE_MISSING("BASE_TABLE_MISSING"),
+        STREAM_DISABLED("STREAM_DISABLED"),
+        STREAM_STALE("STREAM_STALE"),
+        CHANGELOG_DISABLED("CHANGELOG_DISABLED"),
+        TTL_EXPIRED("TTL_EXPIRED"),
+        NO_BASELINE_OFFSET("NO_BASELINE_OFFSET"),
+        TSO_UNINITIALIZED("TSO_UNINITIALIZED"),
+        STATE_UNAVAILABLE("STATE_UNAVAILABLE");
+
+        private final String code;
+
+        Reason(String code) {
+            this.code = code;
+        }
+
+        public String code() {
+            return code;
+        }
+    }
+
+    public record Result(Status status, Reason reason) {
+        public static Result resumable() {
+            return new Result(Status.RESUMABLE, Reason.NONE);
+        }
+
+        public static Result cannotResume(Reason reason) {
+            return new Result(Status.CANNOT_RESUME, reason);
+        }
+
+        public static Result unknown(Reason reason) {
+            return new Result(Status.UNKNOWN, reason);
+        }
+    }
+
+    /** Compute the inclusive TTL expiration cutoff TSO, or null if TTL is 
disabled or referenceTso is unavailable. */
+    public static Long calculateCutoffTso(OlapTable baseTable, Long 
referenceTso) {
+        if (baseTable == null || !baseTable.hasChangelogTtl()) {
+            return null;
+        }
+        if (referenceTso == null || referenceTso <= 0) {
+            return null;
+        }
+        return TSOTimestamp.calculateCutoff(referenceTso, 
baseTable.getChangelogConfig().getTtlSeconds());
+    }
+
+    /** Check stream-wide prerequisites before inspecting individual 
partitions. */
+    public static Result checkStreamLevel(OlapTableStream stream, OlapTable 
baseTable) {
+        if (stream.isDisabled()) {
+            return Result.cannotResume(Reason.STREAM_DISABLED);
+        }
+        if (stream.isStale()) {
+            return Result.cannotResume(Reason.STREAM_STALE);
+        }
+        if (baseTable == null || baseTable.isDropped) {
+            return Result.cannotResume(Reason.BASE_TABLE_MISSING);
+        }
+        if (!baseTable.hasChangelog()) {
+            return Result.cannotResume(Reason.CHANGELOG_DISABLED);
+        }
+        return Result.resumable();
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     * Even for scan types that clip an expired start TSO instead of throwing, 
clipping means
+     * incomplete resumption and reports {@link Status#CANNOT_RESUME}.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, boolean hasData,
+            Long offset, Long historicalTso, long endTso, long 
oldestPendingTimeMs, long provenOldestWriteTimeMs) {
+        // Initial-snapshot partitions read the base table directly and do not 
depend on changelog retention.
+        if (historicalTso != null) {
+            return Result.resumable();
+        }
+        if (!hasData) {
+            return Result.resumable();
+        }
+        // Caught-up partitions (offset == endTso) are skipped by incremental 
scans and do not read changelog.
+        if (StreamPendingAgeTracker.isCaughtUp(hasData, offset, historicalTso, 
endTso)) {
+            return Result.resumable();
+        }
+        if (!hasChangelogTtl) {
+            return Result.resumable();
+        }
+        if (cutoffTso == null) {
+            return Result.unknown(Reason.TSO_UNINITIALIZED);
+        }
+        if (offset != null && offset >= 0) {
+            Long startTso = TSOTimestamp.toExclusiveBound(offset);
+            if (ChangelogUtils.isStartTsoExpired(startTso, cutoffTso)) {
+                return Result.cannotResume(Reason.TTL_EXPIRED);
+            }
+            return Result.resumable();

Review Comment:
   Fixed in 7fa3824b395. Added an internal persisted property 
ChangelogConfig.PRIOR_CLEANUP_CUTOFF_TSO 
(__changelog_prior_cleanup_cutoff_tso), recorded by 
SchemaChangeHandler.updateChangelogConfig() when extending 
changelog.ttl_seconds after all partitions adopt the longer TTL. 
StreamResumabilityChecker.checkPartition() now checks priorCleanupCutoffTso as 
well and reports UNKNOWN (STATE_UNAVAILABLE) when a checkpoint precedes it and 
pending-write bounds cannot prove all pending writes landed afterward. Added 
unit tests in StreamResumabilityCheckerTest.



##########
fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java:
##########
@@ -52,45 +60,123 @@ public ChangelogMonitor(Env env) {
 
     @Override
     protected void runAfterCatalogReady() {
-        sample(System.nanoTime());
+        sample(System.nanoTime(), System::currentTimeMillis, System::nanoTime);
     }
 
-    void sample(long now) {
+    void sample(long nowNanos) {
+        sample(nowNanos, System::currentTimeMillis, () -> nowNanos);
+    }
+
+    void sample(long nowNanos, long nowWallMs) {
+        sample(nowNanos, () -> nowWallMs, () -> nowNanos);
+    }
+
+    void sample(long nowNanos, LongSupplier wallClockMs, LongSupplier 
nanoClock) {
         SamplingState current = state;
         if (!isActive()) {
             current.snapshot = null;
             current.hasRun = false;
+            current.pendingAgeTracker.clear();
+            current.lastIvmRefreshes = Collections.emptyList();
+            current.lastStreamHealths = Collections.emptyMap();
             return;
         }
 
         long interval = TimeUnit.SECONDS.toNanos(Math.max(1, 
Config.changelog_monitor_interval_seconds));
-        if (current.hasRun && now - current.lastRoundNanos < interval) {
+        if (current.hasRun && nowNanos - current.lastRoundNanos < interval) {
             return;
         }
         current.hasRun = true;
-        current.lastRoundNanos = now;
+        current.lastRoundNanos = nowNanos;
         try {
-            current.snapshot = collect();
+            ChangelogMonitorSnapshot next = collect(current, wallClockMs, 
nanoClock);
+            if (next != null) {
+                current.lastIvmRefreshes = next.ivmRefreshes();
+                current.lastStreamHealths = next.streamHealthById();
+                current.snapshot = next;
+            }
         } catch (RuntimeException e) {
             LOG.warn("Failed to collect a changelog monitor snapshot", e);
+            current.pendingAgeTracker.invalidateCaughtUpObservations();
+            if (!current.lastStreamHealths.isEmpty() && current.snapshot != 
null) {
+                List<ChangelogMonitorSnapshot.StreamHealth> sanitized =
+                        
sanitizeRetainedStreamHealths(current.lastStreamHealths);
+                ChangelogMonitorSnapshot refreshed = new 
ChangelogMonitorSnapshot(
+                        current.snapshot.sampleTimeMs(), 
current.snapshot.ivmRefreshes(), sanitized);
+                current.lastStreamHealths = refreshed.streamHealthById();
+                current.snapshot = refreshed;
+            }
         }
     }
 
     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()));
+    private static List<ChangelogMonitorSnapshot.StreamHealth> 
sanitizeRetainedStreamHealths(
+            Map<Long, ChangelogMonitorSnapshot.StreamHealth> priorHealths) {
+        List<ChangelogMonitorSnapshot.StreamHealth> preserved = new 
ArrayList<>(priorHealths.size());
+        for (ChangelogMonitorSnapshot.StreamHealth prior : 
priorHealths.values()) {
+            
preserved.add(OlapStreamMonitorCollector.clearCaughtUpForRetainedStream(prior));
+        }
+        return preserved;
+    }
+
+    ChangelogMonitorSnapshot collect(SamplingState current, LongSupplier 
wallClockMs, LongSupplier nanoClock) {
+        List<ChangelogMonitorSnapshot.IvmRefresh> refreshes;
+        boolean ivmFailed = false;
+        try {
+            List<ChangelogMonitorSnapshot.IvmRefresh> collected = new 
ArrayList<>();
+            for (Database db : env.getInternalCatalog().getDbs()) {
+                for (Table table : db.getTables()) {
+                    if (table instanceof MTMV mv && mv.isIvm()) {
+                        collected.add(new ChangelogMonitorSnapshot.IvmRefresh(
+                                db.getFullName(), mv.getName(), mv.getId(), 
mv.getIvmRefreshMetricValues()));
+                    }
                 }
             }
+            refreshes = collected;
+        } catch (RuntimeException e) {
+            LOG.warn("Failed to collect IVM refresh metrics; preserving prior 
IVM snapshot", e);
+            ivmFailed = true;
+            refreshes = current.lastIvmRefreshes;
         }
-        return new ChangelogMonitorSnapshot(System.currentTimeMillis(), 
refreshes);
+        List<ChangelogMonitorSnapshot.StreamHealth> streamHealths;
+        boolean streamFailed = false;
+        try {
+            streamHealths = OlapStreamMonitorCollector.collect(

Review Comment:
   Fixed in 7fa3824b395. Decoupled IVM refresh summary sampling from OLAP 
stream collection in ChangelogMonitor: runAfterCatalogReady() now collects and 
publishes IVM metrics synchronously on its own cadence while dispatching 
OlapStreamMonitorCollector.collect() onto a dedicated single-thread daemon 
executor (non-overlapping), so stalled Cloud MetaService RPCs cannot delay IVM 
metric publication. Added 
ChangelogMonitorTest#ivmMetricsAdvanceWhileAsyncStreamReadIsBlocked.



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