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


##########
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:
   Fixed in 16edb51b2d4. `ChangelogMonitorSnapshot` now maintains an immutable 
`Map<Long, StreamHealth>` index so `findStreamHealth()` is O(1), 
`TableStreamManager` hoists `TSOService.getStatusSnapshot()` outside locks, and 
`OlapTableStream.snapshotLocalStreamConsumption()` copies only lightweight raw 
partition state under lock and runs `evaluateLivePartition()` after unlocking.



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