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


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,240 @@
+// 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.KeysType;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.changelog.ChangelogUtils;
+import org.apache.doris.mtmv.ivm.IvmUtil;
+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();
+    }
+
+    /**
+     * Whether {@code NormalizeOlapTableStreamScan.applyChangelogTtl()} 
rejects an expired start TSO for this
+     * stream instead of clipping it to the first retained TSO.
+     */
+    public static boolean rejectsExpiredStart(OlapTableStream stream, 
OlapTable baseTable) {
+        if (stream == null || baseTable == null) {
+            return true;
+        }
+        String streamName = stream.getName();
+        if (streamName != null && 
streamName.startsWith(IvmUtil.IVM_STREAM_PREFIX)) {
+            return true;
+        }
+        BaseTableStream.StreamScanType effectiveScanType = 
baseTable.getKeysType() == KeysType.DUP_KEYS
+                ? BaseTableStream.StreamScanType.APPEND_ONLY
+                : stream.getStreamScanType();
+        return effectiveScanType == null || effectiveScanType == 
BaseTableStream.StreamScanType.MIN_DELTA;
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, boolean hasData,
+            Long offset, Long historicalTso, long endTso, long 
oldestPendingTimeMs, long provenOldestWriteTimeMs) {
+        return checkPartition(hasChangelogTtl, cutoffTso, 0L, true, hasData, 
offset, historicalTso, endTso,
+                oldestPendingTimeMs, provenOldestWriteTimeMs);
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     *
+     * <p>For scan modes that reject an expired start TSO (MIN_DELTA and IVM 
streams), any expired positive
+     * offset reports {@link Status#CANNOT_RESUME} ({@link 
Reason#TTL_EXPIRED}). For clipping modes (user
+     * APPEND_ONLY / DETAIL streams), an expired start TSO only loses pending 
changes if unconsumed writes
+     * landed at or before the cutoff; pending-write bounds establish whether 
all pending writes are retained
+     * or report {@link Status#UNKNOWN} when completeness cannot be proven. 
When TTL was previously extended,
+     * {@code priorCleanupCutoffTso} guards against claiming resumability over 
records that earlier compaction
+     * could already have physically removed.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, long priorCleanupCutoffTso,
+            boolean rejectExpiredStart, 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);
+        }
+        long cutoffMs = TSOTimestamp.extractPhysicalTime(cutoffTso);
+        long priorCleanupCutoffMs = priorCleanupCutoffTso > 0
+                ? TSOTimestamp.extractPhysicalTime(priorCleanupCutoffTso) : 0L;
+        long effectiveRetainedCutoffMs = Math.max(cutoffMs, 
priorCleanupCutoffMs);
+
+        if (offset != null && offset >= 0) {
+            Long startTso = TSOTimestamp.toExclusiveBound(offset);
+            if (ChangelogUtils.isStartTsoExpired(startTso, cutoffTso)) {
+                if (rejectExpiredStart) {
+                    return Result.cannotResume(Reason.TTL_EXPIRED);
+                }
+                // Clipping mode (user APPEND_ONLY / DETAIL): check whether 
any pending write is skipped.
+                if (endTso >= 0 && endTso <= cutoffTso) {
+                    return Result.cannotResume(Reason.TTL_EXPIRED);
+                }
+                if (provenOldestWriteTimeMs > 0 && provenOldestWriteTimeMs <= 
cutoffMs) {
+                    return Result.cannotResume(Reason.TTL_EXPIRED);
+                }
+                if (oldestPendingTimeMs > 0 && oldestPendingTimeMs > 
effectiveRetainedCutoffMs) {
+                    return Result.resumable();
+                }
+                return Result.unknown(Reason.STATE_UNAVAILABLE);
+            }
+            if (priorCleanupCutoffTso > 0 && 
ChangelogUtils.isStartTsoExpired(startTso, priorCleanupCutoffTso)) {
+                // Current TTL cutoff moved earlier after a TTL extension, but 
prior compaction under the
+                // shorter TTL may have already removed pending records at or 
before priorCleanupCutoffTso.
+                if (oldestPendingTimeMs > 0 && oldestPendingTimeMs > 
priorCleanupCutoffMs) {
+                    return Result.resumable();
+                }
+                return Result.unknown(Reason.STATE_UNAVAILABLE);
+            }
+            return Result.resumable();
+        }
+        // Partition has data but no positive consumption baseline (newly 
added, empty at stream creation,
+        // or promoted/recovered). Use the two-sided TSO-domain interval 
[oldestPendingTimeMs, provenOldestWriteTimeMs]:
+        // - provenOldestWriteTimeMs (actual observed write) <= cutoffMs 
proves TTL_EXPIRED (no false expired).
+        // - oldestPendingTimeMs (proven lower bound from a verified caught-up 
observation with zero unpublished
+        //   committed transactions) > effectiveRetainedCutoffMs proves all 
unconsumed writes are retained.
+        // - Otherwise (cold start, unpublished pre-creation txn, 
REPLACE/RECOVER PARTITION, or straddling cutoff)
+        //   retention is unproven -> UNKNOWN (NO_BASELINE_OFFSET).
+        if (endTso >= 0 && endTso <= cutoffTso) {

Review Comment:
   [P2] Treat IVM partitions without a baseline as base-table reads
   
   An IVM partition with no consumed offset does not use this TTL-limited 
changelog path: `NormalizeOlapTableStreamScan.makeTableStreamScan()` moves 
those partitions into its history/base-table scan via 
`filterConsumedPartitionIds()`. A newly added or previously empty partition can 
therefore contain rows older than TTL and still refresh completely. This branch 
reports `CAN_RESUME=0 (TTL_EXPIRED)` for exactly that case, in both SQL and 
metrics. The existing `test_ivm_partition_without_offset.groovy` already 
demonstrates successful strict incremental refresh of these partitions after 
TTL expiration. Distinguish IVM's no-baseline base-table read from ordinary 
MIN_DELTA/user-stream TTL behavior and extend that test to check the 
diagnostics.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,240 @@
+// 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.KeysType;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.changelog.ChangelogUtils;
+import org.apache.doris.mtmv.ivm.IvmUtil;
+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();
+    }
+
+    /**
+     * Whether {@code NormalizeOlapTableStreamScan.applyChangelogTtl()} 
rejects an expired start TSO for this
+     * stream instead of clipping it to the first retained TSO.
+     */
+    public static boolean rejectsExpiredStart(OlapTableStream stream, 
OlapTable baseTable) {
+        if (stream == null || baseTable == null) {
+            return true;
+        }
+        String streamName = stream.getName();
+        if (streamName != null && 
streamName.startsWith(IvmUtil.IVM_STREAM_PREFIX)) {
+            return true;
+        }
+        BaseTableStream.StreamScanType effectiveScanType = 
baseTable.getKeysType() == KeysType.DUP_KEYS
+                ? BaseTableStream.StreamScanType.APPEND_ONLY
+                : stream.getStreamScanType();
+        return effectiveScanType == null || effectiveScanType == 
BaseTableStream.StreamScanType.MIN_DELTA;
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, boolean hasData,
+            Long offset, Long historicalTso, long endTso, long 
oldestPendingTimeMs, long provenOldestWriteTimeMs) {
+        return checkPartition(hasChangelogTtl, cutoffTso, 0L, true, hasData, 
offset, historicalTso, endTso,
+                oldestPendingTimeMs, provenOldestWriteTimeMs);
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     *
+     * <p>For scan modes that reject an expired start TSO (MIN_DELTA and IVM 
streams), any expired positive
+     * offset reports {@link Status#CANNOT_RESUME} ({@link 
Reason#TTL_EXPIRED}). For clipping modes (user
+     * APPEND_ONLY / DETAIL streams), an expired start TSO only loses pending 
changes if unconsumed writes
+     * landed at or before the cutoff; pending-write bounds establish whether 
all pending writes are retained
+     * or report {@link Status#UNKNOWN} when completeness cannot be proven. 
When TTL was previously extended,
+     * {@code priorCleanupCutoffTso} guards against claiming resumability over 
records that earlier compaction
+     * could already have physically removed.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, long priorCleanupCutoffTso,
+            boolean rejectExpiredStart, 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);
+        }
+        long cutoffMs = TSOTimestamp.extractPhysicalTime(cutoffTso);
+        long priorCleanupCutoffMs = priorCleanupCutoffTso > 0
+                ? TSOTimestamp.extractPhysicalTime(priorCleanupCutoffTso) : 0L;
+        long effectiveRetainedCutoffMs = Math.max(cutoffMs, 
priorCleanupCutoffMs);
+
+        if (offset != null && offset >= 0) {
+            Long startTso = TSOTimestamp.toExclusiveBound(offset);
+            if (ChangelogUtils.isStartTsoExpired(startTso, cutoffTso)) {
+                if (rejectExpiredStart) {
+                    return Result.cannotResume(Reason.TTL_EXPIRED);
+                }
+                // Clipping mode (user APPEND_ONLY / DETAIL): check whether 
any pending write is skipped.
+                if (endTso >= 0 && endTso <= cutoffTso) {

Review Comment:
   [P2] Do not count filtered-out operations as lost append-only changes
   
   For an `APPEND_ONLY` stream on a unique-key table, 
`makeIncrementalScanFromChangelog()` filters the changelog to 
`CHANGE_TYPE_APPEND`. If the stream is created after a row is inserted and the 
only subsequent write deletes or updates that existing row, `endTso` advances 
but the append-only reader emits no change (see the MoW append-only case in 
`test_table_stream_query_comprehensive.groovy`). After TTL expires this branch 
nevertheless asserts `CANNOT_RESUME`: there was no pending append row to lose. 
Retain the definite expiration result when relevant change evidence exists; 
report unknown for unique-key append-only streams when the operation type of 
expired writes cannot be established.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/TableProperty.java:
##########
@@ -638,6 +638,10 @@ public TableProperty buildBinlogConfig() {
         if (properties.containsKey(ChangelogConfig.CONFIG_VERSION)) {
             
changelogConfig.setConfigVersion(Long.parseLong(properties.get(ChangelogConfig.CONFIG_VERSION)));
         }
+        if (properties.containsKey(ChangelogConfig.PRIOR_CLEANUP_CUTOFF_TSO)) {

Review Comment:
   [P2] Distinguish missing pre-upgrade cleanup history from never-extended TTL
   
   The base version already supports extending `changelog.ttl_seconds`, but 
does not store this property. A table whose shorter retention removed pending 
changes and was then extended *before* upgrading is loaded here with 
`priorCleanupCutoffTso=0`. A checkpoint newer than the current, longer-TTL 
cutoff now reports `RESUMABLE`, although the older changes remain physically 
missing. The new property protects changes made on this head, not previously 
persisted altered tables. Represent the history as unknown for existing altered 
tables without the marker (or establish it from verified retained data), and 
add a legacy properties/replay case before making a positive resumability claim.



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -4349,6 +4349,16 @@ private void updateChangelogConfig(Database db, 
OlapTable table, ChangelogConfig
                 throw new DdlException(
                         "Partitions changed during changelog configuration 
update; retry ALTER TABLE");
             }
+            if (oldConfig.isTtlEnabled() && newConfig.getTtlSeconds() > 
oldConfig.getTtlSeconds()) {
+                Long refTso = 
org.apache.doris.catalog.stream.OlapStreamMonitorCollector
+                        .getReferenceTso(Env.getCurrentEnv());
+                long baseTso = (refTso != null && refTso > 0)
+                        ? refTso
+                        : 
org.apache.doris.tso.TSOTimestamp.composeRealTso(System.currentTimeMillis(), 
0L);

Review Comment:
   [P2] Bound prior cleanup in the TSO domain even during master startup
   
   The previous master's heartbeat reference is an allocated TSO, retained 
monotonically by BE `ClusterInfo`. A new master can accept ALTER after 
`Env.isReady` but before `TSOService.calibrateTimestamp()` finishes; 
calibration explicitly permits a local clock behind the previous durable 
window. Suppose the old reference was t=100s, TTL=30s, checkpoint=t=50s and 
compaction removed a pending t=60s write. If the new leader's clock is t=70s, 
extending TTL to a sufficiently long retention before calibration records prior 
cutoff=t=40s. Once TSO recovers, the current and recorded prior cutoffs can 
both precede the checkpoint, returning RESUMABLE despite the missing write. 
This fallback must not use an unproven local wall-clock bound. Use a 
conservative replayed allocator-window bound or defer successful extension 
publication until TSO is calibrated.



##########
fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java:
##########
@@ -21,76 +21,290 @@
 import org.apache.doris.catalog.Env;
 import org.apache.doris.catalog.MTMV;
 import org.apache.doris.catalog.Table;
+import org.apache.doris.catalog.stream.OlapStreamMonitorCollector;
+import org.apache.doris.catalog.stream.StreamPendingAgeTracker;
 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.Collections;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
 
-/** Samples IVM refresh summaries independently of the metrics scrape path. */
+/** Samples IVM refresh summaries and OLAP table streams 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;
 
+    @FunctionalInterface
+    interface StreamCollector {
+        List<ChangelogMonitorSnapshot.StreamHealth> collect(Env env, 
LongSupplier wallClockMs,
+                LongSupplier nanoClock, StreamPendingAgeTracker tracker,
+                Map<Long, ChangelogMonitorSnapshot.StreamHealth> 
previousByStreamId);
+    }
+
     private final Env env;
+    private final StreamCollector streamCollector;
+    private final ExecutorService streamExecutor;
     private volatile SamplingState state = new SamplingState();
 
     private static class SamplingState {
-        private long lastRoundNanos;
-        private boolean hasRun;
+        private final Object publishLock = new Object();
+        private long lastIvmRoundNanos;
+        private boolean ivmHasRun;
+        private long lastStreamRoundNanos;
+        private boolean streamHasRun;
+        private final AtomicBoolean streamInFlight = new AtomicBoolean(false);
         private volatile ChangelogMonitorSnapshot snapshot;
+        private final StreamPendingAgeTracker pendingAgeTracker = new 
StreamPendingAgeTracker();
+        private List<ChangelogMonitorSnapshot.IvmRefresh> lastIvmRefreshes = 
Collections.emptyList();
+        private Map<Long, ChangelogMonitorSnapshot.StreamHealth> 
lastStreamHealths = Collections.emptyMap();
     }
 
     public ChangelogMonitor(Env env) {
+        this(env, OlapStreamMonitorCollector::collect);
+    }
+
+    ChangelogMonitor(Env env, StreamCollector streamCollector) {
         super("changelog-monitor", CHECK_INTERVAL_MS);
         this.env = env;
+        this.streamCollector = streamCollector;
+        this.streamExecutor = Executors.newSingleThreadExecutor(r -> {
+            Thread t = new Thread(r, "changelog-monitor-stream-collector");
+            t.setDaemon(true);
+            return t;
+        });
     }
 
     @Override
     protected void runAfterCatalogReady() {
-        sample(System.nanoTime());
+        sampleAsyncStream(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);
+    }
+
+    /** Synchronous sampling used by deterministic unit tests. */
+    void sample(long nowNanos, LongSupplier wallClockMs, LongSupplier 
nanoClock) {
         SamplingState current = state;
         if (!isActive()) {
-            current.snapshot = null;
-            current.hasRun = false;
+            clearState(current);
             return;
         }
-
         long interval = TimeUnit.SECONDS.toNanos(Math.max(1, 
Config.changelog_monitor_interval_seconds));
-        if (current.hasRun && now - current.lastRoundNanos < interval) {
+        if (current.ivmHasRun && nowNanos - current.lastIvmRoundNanos < 
interval) {
             return;
         }
-        current.hasRun = true;
-        current.lastRoundNanos = now;
+        current.ivmHasRun = true;
+        current.lastIvmRoundNanos = nowNanos;
+        current.streamHasRun = true;
+        current.lastStreamRoundNanos = nowNanos;
         try {
-            current.snapshot = collect();
+            ChangelogMonitorSnapshot next = collect(current, wallClockMs, 
nanoClock);
+            if (next != null) {
+                synchronized (current.publishLock) {
+                    if (current == state) {
+                        current.lastIvmRefreshes = next.ivmRefreshes();
+                        current.lastStreamHealths = next.streamHealthById();
+                        current.snapshot = next;
+                    }
+                }
+            }
         } catch (RuntimeException e) {
             LOG.warn("Failed to collect a changelog monitor snapshot", e);
+            handleStreamFailure(current);
         }
     }
 
-    private boolean isActive() {
-        return Config.enable_changelog_monitor && env.isMaster() && 
env.isReady();
+    /**
+     * Daemon sampling path: IVM refresh summaries are collected and published 
synchronously on their
+     * own cadence, while OLAP stream collection runs on a dedicated daemon 
thread so stalled Cloud
+     * MetaService RPCs never delay IVM metric publication.
+     */
+    void sampleAsyncStream(long nowNanos, LongSupplier wallClockMs, 
LongSupplier nanoClock) {
+        SamplingState current = state;
+        if (!isActive()) {
+            clearState(current);
+            return;
+        }
+        long interval = TimeUnit.SECONDS.toNanos(Math.max(1, 
Config.changelog_monitor_interval_seconds));
+        if (!current.ivmHasRun || nowNanos - current.lastIvmRoundNanos >= 
interval) {
+            current.ivmHasRun = true;
+            current.lastIvmRoundNanos = nowNanos;
+            collectAndPublishIvm(current, wallClockMs);
+        }
+        if ((!current.streamHasRun || nowNanos - current.lastStreamRoundNanos 
>= interval)
+                && current.streamInFlight.compareAndSet(false, true)) {
+            current.streamHasRun = true;
+            current.lastStreamRoundNanos = nowNanos;
+            streamExecutor.execute(() -> {
+                try {
+                    if (current != state || !isActive()) {
+                        return;
+                    }
+                    collectAndPublishStream(current, wallClockMs, nanoClock);
+                } finally {
+                    current.streamInFlight.set(false);
+                }
+            });
+        }
     }
 
-    ChangelogMonitorSnapshot collect() {
-        List<ChangelogMonitorSnapshot.IvmRefresh> refreshes = new 
ArrayList<>();
+    private void clearState(SamplingState current) {
+        synchronized (current.publishLock) {
+            current.snapshot = null;
+            current.ivmHasRun = false;
+            current.streamHasRun = false;
+            current.pendingAgeTracker.clear();
+            current.lastIvmRefreshes = Collections.emptyList();
+            current.lastStreamHealths = Collections.emptyMap();
+        }
+    }
+
+    private void collectAndPublishIvm(SamplingState current, LongSupplier 
wallClockMs) {
+        try {
+            List<ChangelogMonitorSnapshot.IvmRefresh> collected = 
collectIvmRefreshes();
+            synchronized (current.publishLock) {
+                if (current != state) {
+                    return;
+                }
+                current.lastIvmRefreshes = collected;
+                current.snapshot = new ChangelogMonitorSnapshot(
+                        wallClockMs.getAsLong(), collected, new 
ArrayList<>(current.lastStreamHealths.values()));
+            }
+        } catch (RuntimeException e) {
+            LOG.warn("Failed to collect IVM refresh metrics; preserving prior 
IVM snapshot", e);
+        }
+    }
+
+    private void collectAndPublishStream(SamplingState current, LongSupplier 
wallClockMs, LongSupplier nanoClock) {
+        Map<Long, ChangelogMonitorSnapshot.StreamHealth> priorHealths;
+        synchronized (current.publishLock) {
+            if (current != state) {
+                return;
+            }
+            priorHealths = current.lastStreamHealths;
+        }
+        try {
+            List<ChangelogMonitorSnapshot.StreamHealth> streamHealths = 
streamCollector.collect(

Review Comment:
   [P2] Publish successful stream samples before unrelated slow work completes
   
   The collector timestamps each successful local stream (and each Cloud slice) 
when it is sampled, but this method publishes nothing until the entire round 
returns. With the default 45s expiry, a healthy stream sampled first followed 
by 100 streams each timing out on a 500ms metadata read lock has its otherwise 
valid sample already expired at publication; a stable traversal order repeats 
this every round. The metric stays unknown even though that stream's own reads 
always succeed. Serial Cloud chunks have the same problem. Publish completed 
streams/chunks incrementally or bound and schedule batches independently so 
slow unrelated samples cannot permanently prevent fresh observations. Do not 
simply timestamp the old result at publication.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,816 @@
+// 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.Database;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.Partition;
+import org.apache.doris.catalog.Table;
+import org.apache.doris.changelog.ChangelogMonitor;
+import org.apache.doris.changelog.ChangelogMonitorSnapshot;
+import org.apache.doris.changelog.ChangelogMonitorSnapshot.PartitionHealth;
+import org.apache.doris.changelog.ChangelogMonitorSnapshot.StreamHealth;
+import org.apache.doris.cloud.proto.Cloud;
+import org.apache.doris.cloud.rpc.CloudTableStreamReadStateHelper;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.Pair;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.util.MetaLockUtils;
+import org.apache.doris.rpc.RpcException;
+import org.apache.doris.transaction.GlobalTransactionMgrIface;
+import org.apache.doris.tso.TSOService;
+import org.apache.doris.tso.TSOTimestamp;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.function.LongSupplier;
+
+/**
+ * Batch-samples registered OLAP table streams for {@link 
org.apache.doris.changelog.ChangelogMonitor}.
+ *
+ * <p>Table read locks are always acquired in ascending {@code Table::getId} 
order with a bounded timeout
+ * so background monitoring can never deadlock against multi-table write-lock 
paths such as {@code DROP DATABASE}.
+ * In cloud mode, partition identities are copied under short read locks and 
authoritative states are fetched
+ * in bounded lock-free batch RPCs (chunked across streams and within wide 
streams), isolating per-stream logic
+ * errors without amplifying MetaService transport/timeout, server-side 
rate-limit, or FDB transaction outages.
+ */
+public final class OlapStreamMonitorCollector {
+    private static final Logger LOG = 
LogManager.getLogger(OlapStreamMonitorCollector.class);
+    static final long LOCK_TIMEOUT_MS = 500L;
+    private static final long MAX_FALLBACK_BUDGET_MS = 10_000L;
+
+    private static final Set<Cloud.MetaServiceCode> SERVICE_OUTAGE_CODES = 
EnumSet.of(
+            Cloud.MetaServiceCode.MAX_QPS_LIMIT,
+            Cloud.MetaServiceCode.MS_TOO_BUSY,
+            Cloud.MetaServiceCode.KV_TXN_CREATE_ERR,
+            Cloud.MetaServiceCode.KV_TXN_GET_ERR,
+            Cloud.MetaServiceCode.KV_TXN_COMMIT_ERR,
+            Cloud.MetaServiceCode.KV_TXN_CONFLICT,
+            Cloud.MetaServiceCode.KV_TXN_STORE_GET_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_STORE_COMMIT_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_STORE_CREATE_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_TOO_OLD,
+            Cloud.MetaServiceCode.KV_TXN_MAYBE_COMMITTED,
+            Cloud.MetaServiceCode.KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES);
+
+    private OlapStreamMonitorCollector() {
+    }
+
+    @FunctionalInterface
+    public interface CloudStateFetcher {
+        Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> fetch(
+                Map<Cloud.TableStreamIdentityPB, Set<Long>> 
requestedPartitions) throws UserException;
+    }
+
+    public static List<StreamHealth> collect(Env env, LongSupplier 
wallClockMs, LongSupplier nanoClock,
+            StreamPendingAgeTracker tracker, Map<Long, StreamHealth> 
previousByStreamId) {
+        return collect(env, wallClockMs, nanoClock, tracker, 
previousByStreamId,
+                CloudTableStreamReadStateHelper::getReadStates);
+    }
+
+    public static List<StreamHealth> collect(Env env, long sampleTimeMs, 
StreamPendingAgeTracker tracker,
+            Map<Long, StreamHealth> previousByStreamId, CloudStateFetcher 
cloudFetcher) {
+        long sampleTimeNanos = TimeUnit.MILLISECONDS.toNanos(sampleTimeMs);
+        return collect(env, () -> sampleTimeMs, () -> sampleTimeNanos, 
tracker, previousByStreamId, cloudFetcher);
+    }
+
+    public static List<StreamHealth> collect(Env env, LongSupplier 
wallClockMs, LongSupplier nanoClock,
+            StreamPendingAgeTracker tracker, Map<Long, StreamHealth> 
previousByStreamId,
+            CloudStateFetcher cloudFetcher) {
+        TableStreamManager manager = env.getTableStreamManager();
+        if (manager == null) {
+            return List.of();
+        }
+        Map<Long, Set<Long>> dbStreamMap = manager.copyDbStreamMap();
+        if (dbStreamMap.isEmpty()) {
+            tracker.clear();
+            return List.of();
+        }
+        StreamPendingAgeTracker.Round ageRound = tracker.beginRound();
+        List<StreamHealth> results = Config.isCloudMode()
+                ? collectCloud(env, dbStreamMap, wallClockMs, nanoClock, 
ageRound, previousByStreamId, cloudFetcher)
+                : collectLocal(env, dbStreamMap, wallClockMs, nanoClock, 
ageRound, previousByStreamId);
+        ageRound.commit();
+        return results;
+    }
+
+    public static Long getReferenceTso(Env env) {
+        TSOService tsoService = env.getTSOService();
+        if (tsoService == null) {
+            return null;
+        }
+        TSOService.TSOStatusSnapshot status = tsoService.getStatusSnapshot();
+        return status != null && status.isInitialized() ? 
status.getCurrentTso() : null;
+    }
+
+    /**
+     * Capture per-base-table live safe read TSO watermarks from {@link 
TSOService} before a Cloud MetaService
+     * read RPC, accounting for all in-flight Cloud commits registered in 
{@code TSOTransactionTracker}.
+     */
+    private static Map<Pair<Long, Long>, Long> getSafePreRefTsos(
+            Env env, Set<Cloud.TableStreamIdentityPB> identities) {
+        TSOService tsoService = env.getTSOService();
+        if (tsoService == null || identities.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        Set<Pair<Long, Long>> dbTables = new HashSet<>(identities.size() * 2);
+        for (Cloud.TableStreamIdentityPB id : identities) {
+            dbTables.add(Pair.of(id.getBaseDbId(), id.getBaseTableId()));
+        }
+        Map<Pair<Long, Long>, Long> tsos = 
tsoService.getLiveCommittedTsos(dbTables);
+        return tsos == null ? Collections.emptyMap() : tsos;
+    }
+
+    /** Extract TSO physical time in ms, or 0 when TSO is 
uninitialized/non-positive. */
+    static long extractTsoPhysicalTimeMs(Long tso) {
+        if (tso == null || tso <= 0) {
+            return 0L;
+        }
+        long physMs = TSOTimestamp.extractPhysicalTime(tso);
+        return physMs > 0 ? physMs : 0L;
+    }
+
+    /** Return reference time in the TSO physical-time domain when 
initialized, falling back to wall clock. */
+    public static long resolveReferenceTimeMs(Long referenceTso, long 
fallbackWallMs) {
+        long physMs = extractTsoPhysicalTimeMs(referenceTso);
+        return physMs > 0 ? physMs : fallbackWallMs;
+    }
+
+    static Long calculateCutoffTso(boolean hasChangelogTtl, long 
changelogTtlSeconds, Long referenceTso) {
+        if (!hasChangelogTtl || referenceTso == null || referenceTso <= 0) {
+            return null;
+        }
+        return TSOTimestamp.calculateCutoff(referenceTso, changelogTtlSeconds);
+    }
+
+    /** Order table locks strictly by ascending Table ID to match 
MetaLockUtils / InternalCatalog. */
+    static List<Table> orderTablesById(OlapTableStream stream, OlapTable 
baseTable) {
+        if (baseTable == null) {
+            return List.of(stream);
+        }
+        return baseTable.getId() < stream.getId() ? List.of(baseTable, stream) 
: List.of(stream, baseTable);
+    }
+
+    /**
+     * Check whether {@code baseTableId} currently has any COMMITTED 
(unpublished) transaction in shared-nothing
+     * mode via the O(1) lock-consistent index on {@code 
DatabaseTransactionMgr}. Must be called while holding
+     * {@code baseTable}'s read lock, matching canonical {@code Table.rwLock 
-> DatabaseTransactionMgr.transactionLock}.
+     */
+    private static boolean hasUnpublishedCommittedTxn(Env env, long baseDbId, 
long baseTableId) {
+        GlobalTransactionMgrIface txnMgr = env.getGlobalTransactionMgr();
+        if (txnMgr == null) {
+            return false;
+        }
+        try {
+            return txnMgr.hasCommittedTxnForTable(baseDbId, baseTableId);
+        } catch (AnalysisException e) {
+            // Database has no transaction manager yet -> no committed 
transactions exist.
+            return false;
+        }
+    }
+
+    private static List<StreamHealth> collectLocal(Env env, Map<Long, 
Set<Long>> dbStreamMap,
+            LongSupplier wallClockMs, LongSupplier nanoClock, 
StreamPendingAgeTracker.Round ageRound,
+            Map<Long, StreamHealth> previousByStreamId) {
+        List<StreamHealth> results = new ArrayList<>();
+        for (Map.Entry<Long, Set<Long>> entry : dbStreamMap.entrySet()) {
+            Optional<Database> dbOpt = 
env.getInternalCatalog().getDb(entry.getKey());
+            if (dbOpt.isEmpty()) {
+                continue;
+            }
+            Database db = dbOpt.get();
+            String dbName = db.getFullName();
+            for (Long tableId : entry.getValue()) {
+                Optional<Table> tableOpt = db.getTable(tableId);
+                if (tableOpt.isEmpty() || !(tableOpt.get() instanceof 
OlapTableStream stream)) {
+                    continue;
+                }
+                StreamHealth health = sampleLocalStream(env, db.getId(), 
dbName, stream, wallClockMs, nanoClock,
+                        ageRound, previousByStreamId);
+                if (health != null) {
+                    results.add(health);
+                }
+            }
+        }
+        return results;
+    }
+
+    private static StreamHealth sampleLocalStream(Env env, long streamDbId, 
String dbName, OlapTableStream stream,
+            LongSupplier wallClockMs, LongSupplier nanoClock, 
StreamPendingAgeTracker.Round ageRound,
+            Map<Long, StreamHealth> previousByStreamId) {
+        // Resolve the immutable base table reference before locking so locks 
are acquired in ascending table-ID order.
+        OlapTable baseTable = stream.getBaseTableNullableQuiet();
+        List<Table> tablesToLock = orderTablesById(stream, baseTable);
+        if (!MetaLockUtils.tryReadLockTables(tablesToLock, LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (stream.isDropped) {
+                return null;
+            }
+            return handleTransientSampleFailure(dbName, stream.getName(), 
stream.getId(),
+                    previousByStreamId, ageRound);
+        }
+        String streamName;
+        long streamId;
+        StreamResumabilityChecker.Result streamLevelResult;
+        boolean hasChangelogTtl = false;
+        long changelogTtlSeconds = 0L;
+        long priorCleanupCutoffTso = 0L;
+        boolean rejectExpiredStart = true;
+        Long caughtUpRefTso = null;
+        List<RawPartitionInput> rawInputs = Collections.emptyList();
+        try {
+            if (stream.isDropped) {
+                return null;
+            }
+            streamName = stream.getName();
+            streamId = stream.getId();
+            OlapTable effectiveBase = (baseTable != null && 
!baseTable.isDropped) ? baseTable : null;
+            streamLevelResult = 
StreamResumabilityChecker.checkStreamLevel(stream, effectiveBase);
+            // Match Cloud short-circuit semantics when stream-level 
prerequisites already fail.
+            if (effectiveBase == null
+                    || streamLevelResult.status() == 
StreamResumabilityChecker.Status.CANNOT_RESUME) {
+                return new StreamHealth(dbName, streamName, streamId, true,
+                        wallClockMs.getAsLong(), nanoClock.getAsLong(), -1.0, 
streamLevelResult, Map.of());
+            }
+            hasChangelogTtl = effectiveBase.hasChangelogTtl();
+            if (hasChangelogTtl) {
+                changelogTtlSeconds = 
effectiveBase.getChangelogConfig().getTtlSeconds();
+                priorCleanupCutoffTso = 
effectiveBase.getChangelogConfig().getPriorCleanupCutoffTso();
+            }
+            rejectExpiredStart = 
StreamResumabilityChecker.rejectsExpiredStart(stream, effectiveBase);
+            List<RawPartitionInput> copied = new ArrayList<>();
+            boolean anyCaughtUp = false;
+            for (Partition partition : effectiveBase.getPartitions()) {
+                OlapTableStream.PartitionStreamState state = 
stream.getPartitionState(partition.getId());
+                boolean hasData = partition.hasData();
+                Long offset = state == null ? null : state.getOffset();
+                Long historicalTso = state == null ? null : 
state.getHistoricalTso();
+                long endTso = partition.getTso();
+                if (!anyCaughtUp && 
StreamPendingAgeTracker.isCaughtUp(hasData, offset, historicalTso, endTso)) {
+                    anyCaughtUp = true;
+                }
+                copied.add(new RawPartitionInput(
+                        partition.getId(),
+                        partition.getName(),
+                        hasData,
+                        offset,
+                        historicalTso,
+                        endTso,
+                        partition.getVisibleVersionTime()));
+            }
+            rawInputs = copied;
+            // Only query transaction manager and capture caughtUpRefTso when 
at least one partition is caught up.
+            // Under baseTable.readLock no new commitTSO can be allocated and 
no COMMITTED txn can publish; only when
+            // zero unpublished COMMITTED txns exist for baseTable does 
caughtUpRefTso strictly bound future writes.
+            if (anyCaughtUp) {
+                long baseDbId = stream.getBaseTableInfo() != null ? 
stream.getBaseTableInfo().getDbId() : streamDbId;
+                if (!hasUnpublishedCommittedTxn(env, baseDbId, 
effectiveBase.getId())) {
+                    caughtUpRefTso = getReferenceTso(env);
+                }
+            }
+        } finally {
+            MetaLockUtils.readUnlockTables(tablesToLock);
+        }
+        // Capture post-lock TSO reference and sample timestamps together 
right after unlocking so delayed streams
+        // are always evaluated against a current TTL cutoff matching their 
freshness timestamp.
+        Long postRefTso = getReferenceTso(env);
+        long postWallMs = wallClockMs.getAsLong();
+        long postNanos = nanoClock.getAsLong();
+        Long cutoffTso = calculateCutoffTso(hasChangelogTtl, 
changelogTtlSeconds, postRefTso);
+        long refTimeMs = resolveReferenceTimeMs(postRefTso, postWallMs);
+        long caughtUpTsoTimeMs = extractTsoPhysicalTimeMs(caughtUpRefTso);
+        List<PartitionEvalInput> evalInputs = new 
ArrayList<>(rawInputs.size());
+        for (RawPartitionInput raw : rawInputs) {
+            evalInputs.add(new PartitionEvalInput(raw.partitionId, 
raw.partitionName, raw.hasData, raw.offset,
+                    raw.historicalTso, raw.endTso, raw.fallbackVisibleTimeMs, 
cutoffTso, refTimeMs,
+                    caughtUpTsoTimeMs, postNanos));
+        }
+        return evaluatePartitions(dbName, streamName, streamId, 
streamLevelResult, hasChangelogTtl,
+                priorCleanupCutoffTso, rejectExpiredStart, evalInputs, 
postWallMs, postNanos, ageRound);
+    }
+
+    private static List<StreamHealth> collectCloud(Env env, Map<Long, 
Set<Long>> dbStreamMap,
+            LongSupplier wallClockMs, LongSupplier nanoClock, 
StreamPendingAgeTracker.Round ageRound,
+            Map<Long, StreamHealth> previousByStreamId, CloudStateFetcher 
cloudFetcher) {
+        List<StreamHealth> results = new ArrayList<>();
+        Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> cloudTargets = 
new LinkedHashMap<>();
+
+        for (Map.Entry<Long, Set<Long>> entry : dbStreamMap.entrySet()) {
+            Optional<Database> dbOpt = 
env.getInternalCatalog().getDb(entry.getKey());
+            if (dbOpt.isEmpty()) {
+                continue;
+            }
+            Database db = dbOpt.get();
+            String dbName = db.getFullName();
+            for (Long tableId : entry.getValue()) {
+                Optional<Table> tableOpt = db.getTable(tableId);
+                if (tableOpt.isEmpty() || !(tableOpt.get() instanceof 
OlapTableStream stream)) {
+                    continue;
+                }
+                OlapTable baseTable = stream.getBaseTableNullableQuiet();
+                List<Table> tablesToLock = orderTablesById(stream, baseTable);
+                if (!MetaLockUtils.tryReadLockTables(tablesToLock, 
LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+                    if (!stream.isDropped) {
+                        results.add(handleTransientSampleFailure(dbName, 
stream.getName(), stream.getId(),
+                                previousByStreamId, ageRound));
+                    }
+                    continue;
+                }
+                try {
+                    if (stream.isDropped) {
+                        continue;
+                    }
+                    String streamName = stream.getName();
+                    long streamId = stream.getId();
+                    OlapTable effectiveBase = (baseTable != null && 
!baseTable.isDropped) ? baseTable : null;
+                    StreamResumabilityChecker.Result streamLevel =
+                            StreamResumabilityChecker.checkStreamLevel(stream, 
effectiveBase);
+                    // Short-circuit streams already known locally to be 
unresumable so they never poison
+                    // healthy streams' MetaService batch RPCs or get masked 
on RPC failure.
+                    if (effectiveBase == null
+                            || streamLevel.status() == 
StreamResumabilityChecker.Status.CANNOT_RESUME) {
+                        results.add(new StreamHealth(dbName, streamName, 
streamId, true,
+                                wallClockMs.getAsLong(), 
nanoClock.getAsLong(), -1.0, streamLevel, Map.of()));
+                        continue;
+                    }
+                    boolean hasChangelogTtl = effectiveBase.hasChangelogTtl();
+                    long changelogTtlSeconds = hasChangelogTtl
+                            ? 
effectiveBase.getChangelogConfig().getTtlSeconds() : 0L;
+                    long priorCleanupCutoffTso = hasChangelogTtl
+                            ? 
effectiveBase.getChangelogConfig().getPriorCleanupCutoffTso() : 0L;
+                    boolean rejectExpiredStart = 
StreamResumabilityChecker.rejectsExpiredStart(stream, effectiveBase);
+                    Map<Long, String> partitionNames = new LinkedHashMap<>();
+                    for (Partition partition : effectiveBase.getPartitions()) {
+                        partitionNames.put(partition.getId(), 
partition.getName());
+                    }
+                    if (partitionNames.isEmpty()) {
+                        results.add(new StreamHealth(dbName, streamName, 
streamId, true,
+                                wallClockMs.getAsLong(), 
nanoClock.getAsLong(), 0.0, streamLevel, Map.of()));
+                        continue;
+                    }
+                    Cloud.TableStreamIdentityPB identity = 
Cloud.TableStreamIdentityPB.newBuilder()
+                            .setBaseDbId(stream.getBaseTableInfo().getDbId())
+                            
.setBaseTableId(stream.getBaseTableInfo().getTableId())
+                            .setStreamDbId(entry.getKey())
+                            .setStreamId(streamId)
+                            .build();
+                    cloudTargets.put(identity, new CloudStreamMetadata(dbName, 
streamName, streamId,
+                            streamLevel, hasChangelogTtl, changelogTtlSeconds, 
priorCleanupCutoffTso,
+                            rejectExpiredStart, partitionNames));
+                } finally {
+                    MetaLockUtils.readUnlockTables(tablesToLock);
+                }
+            }
+        }
+
+        if (cloudTargets.isEmpty()) {
+            return results;
+        }
+
+        Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetchedStates =
+                fetchCloudStatesChunked(env, cloudTargets, wallClockMs, 
nanoClock, cloudFetcher);
+
+        for (Map.Entry<Cloud.TableStreamIdentityPB, CloudStreamMetadata> entry 
: cloudTargets.entrySet()) {
+            CloudStreamMetadata meta = entry.getValue();
+            CloudFetchResult fetchResult = fetchedStates.get(entry.getKey());
+            if (fetchResult == null || fetchResult.partitionSamples == null) {
+                results.add(handleTransientSampleFailure(meta.dbName, 
meta.streamName, meta.streamId,
+                        previousByStreamId, ageRound));
+                continue;
+            }
+            List<PartitionEvalInput> evalInputs = new 
ArrayList<>(meta.partitionNames.size());
+            boolean incomplete = false;
+            for (Map.Entry<Long, String> partEntry : 
meta.partitionNames.entrySet()) {
+                PartitionFetchSample sample = 
fetchResult.partitionSamples.get(partEntry.getKey());
+                Cloud.TableStreamPartitionReadStatePB pb = sample == null ? 
null : sample.state;
+                if (pb == null || !pb.hasOffsetState() || !pb.hasEndTso() || 
!pb.hasVisibleVersion()) {
+                    incomplete = true;
+                    break;
+                }
+                boolean hasData = pb.getVisibleVersion() > 
Partition.PARTITION_INIT_VERSION;
+                Long offset = null;
+                Long historicalTso = null;
+                if (pb.getOffsetState()
+                        == 
Cloud.TableStreamOffsetStatePB.TABLE_STREAM_OFFSET_INITIAL_SNAPSHOT_PENDING) {
+                    if (!pb.hasOffsetTso()) {
+                        incomplete = true;
+                        break;
+                    }
+                    historicalTso = pb.getOffsetTso();
+                } else if (pb.getOffsetState() == 
Cloud.TableStreamOffsetStatePB.TABLE_STREAM_OFFSET_CONSUMED) {
+                    if (!pb.hasOffsetTso()) {
+                        incomplete = true;
+                        break;
+                    }
+                    offset = pb.getOffsetTso();
+                }
+                // Evaluate each partition using its own slice's TSOs: pre-RPC 
TSO bounds caught-up time
+                // before MetaService read latency, while post-RPC TSO 
computes current age and TTL cutoff.
+                Long cutoffTso = calculateCutoffTso(meta.hasChangelogTtl, 
meta.changelogTtlSeconds, sample.postRefTso);

Review Comment:
   [P2] Include the FE metadata observation in Cloud sample freshness
   
   Cloud collection snapshots TTL/config and partition membership for all 
targets before starting any RPC. A later chunk can run far after its metadata 
was copied, yet its freshness clock comes from that chunk's pre-RPC timestamp. 
For example, snapshot TTL=120s at t=100s, then during the intervening waits 
ALTER publishes TTL=30s. A MIN_DELTA checkpoint at t=80s with pending 
end=t=95s, fetched at t=160s, is evaluated here with the old cutoff=t=40s 
rather than the current cutoff=t=130s. The result is freshly published as 
RESUMABLE despite the actual scan rejecting the expired start. An added 
partition can likewise be absent from a newly fresh result. Revalidate the 
config generation/partition set near the fetch or include the earlier metadata 
timestamp in freshness; preserving a current post-RPC TSO alone is insufficient.



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