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


##########
be/src/information_schema/schema_table_stream_consumption_scanner.cpp:
##########
@@ -58,6 +61,12 @@ Status 
SchemaTableStreamConsumptionScanner::start(RuntimeState* state) {
 
 TFetchSchemaTableDataRequest 
SchemaTableStreamConsumptionScanner::_build_fetch_request() const {
     TSchemaTableRequestParams schema_table_request_params;
+    std::vector<std::string> columns;
+    columns.reserve(_s_table_stream_consumption_columns.size());
+    for (const auto& column : _s_table_stream_consumption_columns) {
+        columns.emplace_back(column.name);
+    }
+    schema_table_request_params.__set_columns_name(columns);

Review Comment:
   [P2] Preserve legacy consumption queries against an older master FE
   
   This always requests all ten columns, even when SQL selects only existing 
columns. During a rolling upgrade with a new BE and an older master FE, the 
base FE's `TABLE_STREAM_CONSUMPTION_COLUMN_TO_INDEX` contains only seven names. 
Its `filterColumns()` gets a null index for `PENDING_AGE_SECONDS`, and the 
request returns `INTERNAL_ERROR` for any nonempty result. Thus even `SELECT 
DB_NAME FROM information_schema.table_stream_consumption` stops working. Add 
capability negotiation or a legacy request/row fallback; handling old BE 
requests on the new FE only covers the opposite upgrade combination.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,171 @@
+// 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 
streamCreateTimeMs, long oldestPendingTimeMs) {
+        // 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();
+        }
+        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();
+        }
+        // Partition has data but no real consumption baseline (newly added or 
empty at stream creation).
+        if (endTso >= 0 && endTso <= cutoffTso) {
+            return Result.cannotResume(Reason.TTL_EXPIRED);
+        }
+        long cutoffMs = TSOTimestamp.extractPhysicalTime(cutoffTso);
+        if (oldestPendingTimeMs > 0) {
+            return oldestPendingTimeMs <= cutoffMs

Review Comment:
   [P2] Require evidence of the first pending write before reporting resumable
   
   For a partition empty at stream creation, the offset is `-1`; later-added 
partitions may have no state. After monitor start/reset, both callers obtain 
`oldestPendingTimeMs` from `anchorTimeMs()`, which uses the latest `endTso`. 
With TTL 60 seconds, unconsumed writes at t=10 and t=80, and sampling at t=90, 
this branch reports resumable from the t=80 anchor. The actual user-stream scan 
converts the missing baseline to a null start and clips it at cutoff t=30, 
omitting the t=10 change. A recent last write cannot establish complete 
retention; preserve reliable first-pending-write evidence or report unknown 
instead of a false healthy status.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,411 @@
+// 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.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.Config;
+import org.apache.doris.common.UserException;
+import org.apache.doris.tso.TSOService;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Batch-samples registered OLAP table streams for {@link 
org.apache.doris.changelog.ChangelogMonitor}.
+ *
+ * <p>In shared-nothing mode, partition states are copied under short read 
locks. In cloud mode,
+ * partition identities are copied under short read locks and authoritative 
states are fetched in one
+ * lock-free batch RPC, falling back to per-stream RPCs on batch failure so 
one failing stream does
+ * not blind healthy streams.
+ */
+public final class OlapStreamMonitorCollector {
+    private static final Logger LOG = 
LogManager.getLogger(OlapStreamMonitorCollector.class);
+
+    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, long sampleTimeMs, 
StreamPendingAgeTracker tracker,
+            Map<Long, StreamHealth> previousByStreamId) {
+        return collect(env, sampleTimeMs, tracker, previousByStreamId, 
CloudTableStreamReadStateHelper::getReadStates);
+    }
+
+    public static List<StreamHealth> collect(Env env, long sampleTimeMs, 
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();
+        }
+        Long referenceTso = getReferenceTso(env);
+        StreamPendingAgeTracker.Round ageRound = tracker.beginRound();
+        List<StreamHealth> results = Config.isCloudMode()
+                ? collectCloud(env, dbStreamMap, referenceTso, sampleTimeMs, 
ageRound, previousByStreamId, cloudFetcher)
+                : collectLocal(env, dbStreamMap, referenceTso, sampleTimeMs, 
ageRound);
+        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;
+    }
+
+    private static List<StreamHealth> collectLocal(Env env, Map<Long, 
Set<Long>> dbStreamMap, Long referenceTso,
+            long sampleTimeMs, StreamPendingAgeTracker.Round ageRound) {
+        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(dbName, stream, 
referenceTso, sampleTimeMs, ageRound);
+                if (health != null) {
+                    results.add(health);
+                }
+            }
+        }
+        return results;
+    }
+
+    private static StreamHealth sampleLocalStream(String dbName, 
OlapTableStream stream, Long referenceTso,
+            long sampleTimeMs, StreamPendingAgeTracker.Round ageRound) {
+        if (!stream.readLockIfExist()) {
+            return null;
+        }
+        String streamName;
+        long streamId;
+        long streamCreateTimeMs;
+        StreamResumabilityChecker.Result streamLevelResult;
+        boolean hasChangelogTtl = false;
+        Long cutoffTso = null;
+        List<LocalPartitionInput> partitionInputs = Collections.emptyList();
+        try {
+            streamName = stream.getName();
+            streamId = stream.getId();
+            streamCreateTimeMs = stream.getCreateTime() > 0 ? 
stream.getCreateTime() * 1000L : 0L;
+            OlapTable baseTable = stream.getBaseTableNullable();
+            if (baseTable == null || !baseTable.readLockIfExist()) {
+                streamLevelResult = 
StreamResumabilityChecker.checkStreamLevel(stream, null);
+                return new StreamHealth(dbName, streamName, streamId, true, 
sampleTimeMs, -1.0,
+                        streamLevelResult, Map.of());
+            }
+            try {
+                streamLevelResult = 
StreamResumabilityChecker.checkStreamLevel(stream, baseTable);
+                hasChangelogTtl = baseTable.hasChangelogTtl();
+                cutoffTso = 
StreamResumabilityChecker.calculateCutoffTso(baseTable, referenceTso);
+                List<LocalPartitionInput> copied = new ArrayList<>();
+                for (Partition partition : baseTable.getPartitions()) {
+                    OlapTableStream.PartitionStreamState state = 
stream.getPartitionState(partition.getId());
+                    copied.add(new LocalPartitionInput(
+                            partition.getId(),
+                            partition.getName(),
+                            partition.hasData(),
+                            state == null ? null : state.getOffset(),
+                            state == null ? null : state.getHistoricalTso(),
+                            partition.getTso(),
+                            partition.getVisibleVersionTime()));
+                }
+                partitionInputs = copied;
+            } finally {
+                baseTable.readUnlock();
+            }
+        } finally {
+            stream.readUnlock();
+        }
+        return evaluatePartitions(dbName, streamName, streamId, 
streamCreateTimeMs, streamLevelResult,
+                hasChangelogTtl, cutoffTso, partitionInputs, sampleTimeMs, 
ageRound);
+    }
+
+    private static List<StreamHealth> collectCloud(Env env, Map<Long, 
Set<Long>> dbStreamMap, Long referenceTso,
+            long sampleTimeMs, 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;
+                }
+                if (!stream.readLockIfExist()) {
+                    continue;
+                }
+                try {
+                    String streamName = stream.getName();
+                    long streamId = stream.getId();
+                    long streamCreateTimeMs = stream.getCreateTime() > 0 ? 
stream.getCreateTime() * 1000L : 0L;
+                    OlapTable baseTable = stream.getBaseTableNullable();
+                    if (baseTable == null || !baseTable.readLockIfExist()) {
+                        StreamResumabilityChecker.Result streamLevel =
+                                
StreamResumabilityChecker.checkStreamLevel(stream, null);
+                        results.add(new StreamHealth(dbName, streamName, 
streamId, true, sampleTimeMs, -1.0,
+                                streamLevel, Map.of()));
+                        continue;
+                    }
+                    try {
+                        StreamResumabilityChecker.Result streamLevel =
+                                
StreamResumabilityChecker.checkStreamLevel(stream, baseTable);
+                        boolean hasChangelogTtl = baseTable.hasChangelogTtl();
+                        Long cutoffTso = 
StreamResumabilityChecker.calculateCutoffTso(baseTable, referenceTso);
+                        Map<Long, String> partitionNames = new 
LinkedHashMap<>();
+                        for (Partition partition : baseTable.getPartitions()) {
+                            partitionNames.put(partition.getId(), 
partition.getName());
+                        }
+                        if (partitionNames.isEmpty()) {
+                            results.add(new StreamHealth(dbName, streamName, 
streamId, true, sampleTimeMs, 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,
+                                streamCreateTimeMs, streamLevel, 
hasChangelogTtl, cutoffTso, partitionNames));
+                    } finally {
+                        baseTable.readUnlock();
+                    }
+                } finally {
+                    stream.readUnlock();
+                }
+            }
+        }
+
+        if (cloudTargets.isEmpty()) {
+            return results;
+        }
+
+        Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> fetchedStates =
+                fetchCloudStatesWithIsolation(cloudTargets, cloudFetcher);
+
+        for (Map.Entry<Cloud.TableStreamIdentityPB, CloudStreamMetadata> entry 
: cloudTargets.entrySet()) {
+            CloudStreamMetadata meta = entry.getValue();
+            Map<Long, Cloud.TableStreamPartitionReadStatePB> partStates = 
fetchedStates.get(entry.getKey());
+            if (partStates == null) {
+                results.add(handleCloudSampleFailure(meta, previousByStreamId, 
ageRound));
+                continue;
+            }
+            List<LocalPartitionInput> inputs = new 
ArrayList<>(meta.partitionNames.size());
+            boolean incomplete = false;
+            for (Map.Entry<Long, String> partEntry : 
meta.partitionNames.entrySet()) {
+                Cloud.TableStreamPartitionReadStatePB pb = 
partStates.get(partEntry.getKey());
+                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();
+                }
+                inputs.add(new LocalPartitionInput(partEntry.getKey(), 
partEntry.getValue(), hasData,
+                        offset, historicalTso, pb.getEndTso(), 0L));
+            }
+            if (incomplete) {
+                results.add(handleCloudSampleFailure(meta, previousByStreamId, 
ageRound));
+                continue;
+            }
+            results.add(evaluatePartitions(meta.dbName, meta.streamName, 
meta.streamId, meta.streamCreateTimeMs,
+                    meta.streamLevelResult, meta.hasChangelogTtl, 
meta.cutoffTso, inputs, sampleTimeMs, ageRound));
+        }
+        return results;
+    }
+
+    private static Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>>
+            fetchCloudStatesWithIsolation(Map<Cloud.TableStreamIdentityPB, 
CloudStreamMetadata> targets,
+                    CloudStateFetcher cloudFetcher) {
+        Map<Cloud.TableStreamIdentityPB, Set<Long>> batchRequest = new 
LinkedHashMap<>();
+        targets.forEach((identity, meta) -> batchRequest.put(identity, 
meta.partitionNames.keySet()));
+        try {
+            return cloudFetcher.fetch(batchRequest);
+        } catch (UserException | RuntimeException e) {
+            LOG.warn("Batch Cloud Table Stream monitoring RPC failed for {} 
streams; retrying individually",
+                    targets.size(), e);
+        }
+        if (targets.size() == 1) {
+            return Collections.emptyMap();
+        }
+        Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> partial =
+                new LinkedHashMap<>();
+        for (Map.Entry<Cloud.TableStreamIdentityPB, CloudStreamMetadata> entry 
: targets.entrySet()) {
+            try {
+                Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> single =
+                        cloudFetcher.fetch(Map.of(entry.getKey(), 
entry.getValue().partitionNames.keySet()));
+                Map<Long, Cloud.TableStreamPartitionReadStatePB> states = 
single.get(entry.getKey());
+                if (states != null) {
+                    partial.put(entry.getKey(), states);
+                }
+            } catch (UserException | RuntimeException e) {
+                LOG.warn("Cloud Table Stream monitoring RPC failed for stream 
{}.{} (id={})",
+                        entry.getValue().dbName, entry.getValue().streamName, 
entry.getValue().streamId, e);
+            }
+        }
+        return partial;
+    }
+
+    private static StreamHealth handleCloudSampleFailure(CloudStreamMetadata 
meta,
+            Map<Long, StreamHealth> previousByStreamId, 
StreamPendingAgeTracker.Round ageRound) {
+        ageRound.retainPreviousForStream(meta.streamId);
+        StreamHealth previous = previousByStreamId.get(meta.streamId);
+        if (previous != null && previous.sampledSuccessfully()) {
+            // Keep the last successful sample's timestamp intact so 
expiration checks use real sample time.
+            return new StreamHealth(meta.dbName, meta.streamName, 
meta.streamId, true, previous.sampleTimeMs(),
+                    previous.pendingAgeSeconds(), previous.resumeResult(), 
previous.partitions());
+        }
+        return new StreamHealth(meta.dbName, meta.streamName, meta.streamId, 
false, 0L, -1.0,
+                
StreamResumabilityChecker.Result.unknown(StreamResumabilityChecker.Reason.STATE_UNAVAILABLE),
+                Map.of());
+    }
+
+    private static StreamHealth evaluatePartitions(String dbName, String 
streamName, long streamId,
+            long streamCreateTimeMs, StreamResumabilityChecker.Result 
streamLevelResult,
+            boolean hasChangelogTtl, Long cutoffTso, List<LocalPartitionInput> 
partitionInputs,
+            long sampleTimeMs, StreamPendingAgeTracker.Round ageRound) {
+        Map<Long, PartitionHealth> partitionHealths = new 
LinkedHashMap<>(partitionInputs.size());
+        double maxPendingAge = 0.0;
+        boolean unknownAge = false;
+        StreamResumabilityChecker.Result overallResume = streamLevelResult;
+
+        for (LocalPartitionInput input : partitionInputs) {
+            StreamPendingAgeTracker.AgeMeasurement age = 
ageRound.recordPartition(streamId, input.partitionId,
+                    input.hasData, input.offset, input.historicalTso, 
input.endTso,
+                    input.fallbackVisibleTimeMs, sampleTimeMs);
+            if (age.pendingAgeSeconds() < 0) {
+                unknownAge = true;
+            } else if (!unknownAge) {
+                maxPendingAge = Math.max(maxPendingAge, 
age.pendingAgeSeconds());
+            }
+            StreamResumabilityChecker.Result partResume = 
streamLevelResult.status()
+                    == StreamResumabilityChecker.Status.CANNOT_RESUME
+                    ? streamLevelResult
+                    : 
StreamResumabilityChecker.checkPartition(hasChangelogTtl, cutoffTso, 
input.hasData,
+                            input.offset, input.historicalTso, input.endTso, 
streamCreateTimeMs,
+                            age.oldestPendingTimeMs());
+            overallResume = StreamResumabilityChecker.merge(overallResume, 
partResume);
+            long baselineKey = 
StreamPendingAgeTracker.baselineKey(input.offset, input.historicalTso);
+            partitionHealths.put(input.partitionId, new 
PartitionHealth(input.partitionId, input.partitionName,
+                    baselineKey, age.pendingAgeSeconds(), 
age.oldestPendingTimeMs(), partResume));
+        }
+
+        double streamPendingAge = unknownAge ? -1.0 : maxPendingAge;
+        return new StreamHealth(dbName, streamName, streamId, true, 
sampleTimeMs, streamPendingAge,
+                overallResume, partitionHealths);
+    }
+
+    public record LivePartitionDiagnostics(double pendingAgeSeconds, 
StreamResumabilityChecker.Result resumeResult) {
+    }
+
+    /** Compute live partition diagnostics for {@code 
information_schema.table_stream_consumption}. */
+    public static LivePartitionDiagnostics evaluateLivePartition(long 
streamId, long partitionId,
+            long streamCreateTimeMs, StreamResumabilityChecker.Result 
streamLevelResult,
+            boolean hasChangelogTtl, Long cutoffTso, boolean hasData, Long 
offset, Long historicalTso,
+            long endTso, long fallbackVisibleTimeMs, long nowMs, 
ChangelogMonitorSnapshot monitorSnapshot) {
+        double pendingAgeSeconds;
+        long oldestPendingTimeMs = 0L;
+        if (StreamPendingAgeTracker.isCaughtUp(hasData, offset, historicalTso, 
endTso)) {
+            pendingAgeSeconds = 0.0;
+        } else {
+            long baselineKey = StreamPendingAgeTracker.baselineKey(offset, 
historicalTso);
+            StreamHealth streamHealth = monitorSnapshot == null ? null : 
monitorSnapshot.findStreamHealth(streamId);

Review Comment:
   [P2] Index cached stream health before evaluating partitions
   
   `findStreamHealth()` linearly scans every entry in 
`snapshot.streamHealths()`, and this call runs for every lagging partition. New 
BE requests always enable these diagnostics, including queries projecting only 
the original columns. A full query over N streams with P lagging partitions 
each therefore adds O(N²P) work; 10,000 streams with 100 partitions entail 
roughly five billion stream-ID comparisons. The local path performs these 
searches while holding stream/base metadata read locks, delaying writers as 
well as the query. Build a stream-ID index in the immutable snapshot and use it 
for partition diagnostics.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,411 @@
+// 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.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.Config;
+import org.apache.doris.common.UserException;
+import org.apache.doris.tso.TSOService;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Batch-samples registered OLAP table streams for {@link 
org.apache.doris.changelog.ChangelogMonitor}.
+ *
+ * <p>In shared-nothing mode, partition states are copied under short read 
locks. In cloud mode,
+ * partition identities are copied under short read locks and authoritative 
states are fetched in one
+ * lock-free batch RPC, falling back to per-stream RPCs on batch failure so 
one failing stream does
+ * not blind healthy streams.
+ */
+public final class OlapStreamMonitorCollector {
+    private static final Logger LOG = 
LogManager.getLogger(OlapStreamMonitorCollector.class);
+
+    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, long sampleTimeMs, 
StreamPendingAgeTracker tracker,
+            Map<Long, StreamHealth> previousByStreamId) {
+        return collect(env, sampleTimeMs, tracker, previousByStreamId, 
CloudTableStreamReadStateHelper::getReadStates);
+    }
+
+    public static List<StreamHealth> collect(Env env, long sampleTimeMs, 
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();
+        }
+        Long referenceTso = getReferenceTso(env);
+        StreamPendingAgeTracker.Round ageRound = tracker.beginRound();
+        List<StreamHealth> results = Config.isCloudMode()
+                ? collectCloud(env, dbStreamMap, referenceTso, sampleTimeMs, 
ageRound, previousByStreamId, cloudFetcher)
+                : collectLocal(env, dbStreamMap, referenceTso, sampleTimeMs, 
ageRound);
+        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;
+    }
+
+    private static List<StreamHealth> collectLocal(Env env, Map<Long, 
Set<Long>> dbStreamMap, Long referenceTso,
+            long sampleTimeMs, StreamPendingAgeTracker.Round ageRound) {
+        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(dbName, stream, 
referenceTso, sampleTimeMs, ageRound);
+                if (health != null) {
+                    results.add(health);
+                }
+            }
+        }
+        return results;
+    }
+
+    private static StreamHealth sampleLocalStream(String dbName, 
OlapTableStream stream, Long referenceTso,
+            long sampleTimeMs, StreamPendingAgeTracker.Round ageRound) {
+        if (!stream.readLockIfExist()) {
+            return null;
+        }
+        String streamName;
+        long streamId;
+        long streamCreateTimeMs;
+        StreamResumabilityChecker.Result streamLevelResult;
+        boolean hasChangelogTtl = false;
+        Long cutoffTso = null;
+        List<LocalPartitionInput> partitionInputs = Collections.emptyList();
+        try {
+            streamName = stream.getName();
+            streamId = stream.getId();
+            streamCreateTimeMs = stream.getCreateTime() > 0 ? 
stream.getCreateTime() * 1000L : 0L;
+            OlapTable baseTable = stream.getBaseTableNullable();
+            if (baseTable == null || !baseTable.readLockIfExist()) {

Review Comment:
   [P2] Follow transaction lock order when sampling a stream
   
   The stream read lock is held while this waits for its base-table read lock. 
For a local `INSERT INTO B SELECT ... FROM S`, where S is a stream on B, 
`GlobalTransactionMgr.buildLockTableList()` orders B before S and commit 
acquires both write locks. The sampler can hold S-read, then commit acquire 
B-write and wait for S-write, while the sampler waits for B-read. Progress then 
requires the commit lock timeout, failing an otherwise valid insert and 
blocking B until that timeout. This PR introduces the cycle into 
default-enabled background sampling. Acquire the locks in consistent order or 
avoid holding the stream lock while waiting for the base lock; the cloud 
collector repeats this acquisition order too.



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