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


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,780 @@
+// 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.UserException;
+import org.apache.doris.common.util.MetaLockUtils;
+import org.apache.doris.rpc.RpcException;
+import org.apache.doris.transaction.GlobalTransactionMgrIface;
+import org.apache.doris.transaction.TableCommitInfo;
+import org.apache.doris.transaction.TransactionState;
+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;
+    }
+
+    /** 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. Must be called while holding {@code baseTable}'s read lock, 
matching canonical
+     * {@code Table.rwLock -> DatabaseTransactionMgr.transactionLock} order.
+     */
+    private static boolean hasUnpublishedCommittedTxn(Env env, long baseDbId, 
long baseTableId) {
+        GlobalTransactionMgrIface txnMgr = env.getGlobalTransactionMgr();
+        if (txnMgr == null) {
+            return false;
+        }
+        try {
+            List<TransactionState> committedTxns = 
txnMgr.getCommittedTransactions(baseDbId);
+            if (committedTxns == null) {
+                return false;
+            }
+            for (TransactionState txn : committedTxns) {
+                List<Long> tableIds = txn.getTableIdList();
+                if (tableIds != null && tableIds.contains(baseTableId)) {
+                    return true;
+                }
+                List<TableCommitInfo> subInfos = 
txn.getSubTxnTableCommitInfos();

Review Comment:
   [P2] Guard ordinary transactions before reading subtransaction info
   
   For a stream on table B, an ordinary COMMITTED transaction on unrelated 
table A falls through the table-ID check above and reaches this accessor. 
Ordinary `TransactionState` constructors leave `subTxnIds` null, and 
`getSubTxnTableCommitInfos()` iterates it directly 
(`TransactionState.java:867–875`), so this throws an NPE. The exception escapes 
the collector and `ChangelogMonitor.collect()` retains the previous health 
snapshot for every stream; a publishing backlog on A can therefore freeze all 
stream metrics until they expire to unknown, or prevent initial metrics from 
appearing. Follow the existing caller contract by checking whether the 
transaction has subtransactions before invoking this accessor. Please cover an 
unrelated-table ordinary transaction with a real `TransactionState`; the 
current matching-table Mockito case bypasses this branch.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,780 @@
+// 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.UserException;
+import org.apache.doris.common.util.MetaLockUtils;
+import org.apache.doris.rpc.RpcException;
+import org.apache.doris.transaction.GlobalTransactionMgrIface;
+import org.apache.doris.transaction.TableCommitInfo;
+import org.apache.doris.transaction.TransactionState;
+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;
+    }
+
+    /** 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. Must be called while holding {@code baseTable}'s read lock, 
matching canonical
+     * {@code Table.rwLock -> DatabaseTransactionMgr.transactionLock} order.
+     */
+    private static boolean hasUnpublishedCommittedTxn(Env env, long baseDbId, 
long baseTableId) {
+        GlobalTransactionMgrIface txnMgr = env.getGlobalTransactionMgr();
+        if (txnMgr == null) {
+            return false;
+        }
+        try {
+            List<TransactionState> committedTxns = 
txnMgr.getCommittedTransactions(baseDbId);

Review Comment:
   [P2] Avoid rescanning all database transactions for every stream
   
   `getCommittedTransactions()` delegates to 
`DatabaseTransactionMgr.getCommittedTxnList()`, which scans every running 
transaction and sorts the committed ones under the database transaction read 
lock. `sampleLocalStream()` invokes it for every stream while holding both 
table read locks, even when all copied partitions are lagging and cannot use a 
caught-up anchor. This adds O(S × (R + C log C)) work per default 15-second 
round: 10,000 streams and the permitted 10,000 PREPARE transactions already 
require 100 million state visits with no committed transaction to find. The 
500ms lock timeout only bounds acquisition. Skip the check when no partition 
needs a caught-up bound, and use a lock-consistent per-table existence 
query/index rather than repeatedly materializing and sorting the entire 
database list; a stale once-per-round list would invalidate the visibility 
proof.



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