hello-stephen commented on code in PR #71199:
URL: https://github.com/apache/doris/pull/71199#discussion_r4786636548


##########
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:
   [P2] Keep existing wildcard queries working during rolling upgrades
   
   An upgraded query FE expands an existing `SELECT * FROM 
information_schema.table_stream_consumption` to ten slots. `SchemaScanNode` can 
still schedule that scan on a base-version BE, whose 
`SchemaScanOperatorX::prepare()` fails on the first new slot with `no match 
column for this column(PENDING_AGE_SECONDS)`. That check runs before the 
scanner can fetch or pad a legacy response. Gate the new schema on cluster 
support or provide a scan path that can serve the new descriptor throughout the 
upgrade. Add a mixed-version wildcard case alongside the legacy projection 
cases.



##########
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:
   [P2] Account for physical cleanup when checking an extended TTL
   
   The current TTL cutoff can move backward even though completed changelog 
compaction already removed pending records. With a checkpoint at t=10s and 
pending writes at t=20s and t=90s, a 30s TTL lets compaction at t=100s remove 
the t=20s write. Extending TTL to 120s through 
`SchemaChangeHandler.updateChangelogConfig()` moves the cutoff before the 
unchanged checkpoint and this branch returns `RESUMABLE`. The t=20s change is 
still missing from the stream read. Use verified retained-history information 
when reporting complete resumability, or return unknown when a prior cleanup 
could have left a gap.



##########
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:
   [P2] Check which pending changes an append-only read would skip
   
   A duplicate-key user stream uses `APPEND_ONLY`, so 
`NormalizeOlapTableStreamScan.applyChangelogTtl()` clips an expired start. 
Create a stream without initial rows after the only prior write has expired, 
then insert one fresh row. Consuming before that new row expires returns the 
entire pending delta because the clipped interval contains no pending writes. 
This branch still emits `CAN_RESUME=0` with `TTL_EXPIRED` in SQL and metrics. 
Both new regression suites set up this case and assert the false alarm. Keep 
the expired-start failure for scan modes that reject it. For clipping modes, 
use available pending-write bounds and report unknown when those bounds cannot 
establish completeness.



##########
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:
   [P2] Keep IVM metrics on their sampling cadence during Cloud stream reads
   
   The daemon publishes the IVM values only after the synchronous stream 
collector returns. One stalled `getTableStreamOffset` call can take about 60 
seconds under the default 30-second RPC deadline and one deadline retry. Serial 
chunks and metadata lock waits can delay publication further. During that 
interval a first scrape has no per-view IVM series, or it keeps getting the 
previous values even though IVM collection itself succeeded. The fallback 
budget does not bound primary requests. Give IVM metrics an independent 
publication and sampling cadence, and verify they advance while the stream read 
is blocked.



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