yujun777 commented on code in PR #71199: URL: https://github.com/apache/doris/pull/71199#discussion_r4755018967
########## 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: Fixed in b68cefe6a2a. Replaced the scan over getCommittedTransactions() / getSubTxnTableCommitInfos() with an exact per-table index (committedTxnIdsByTable / committedTableIdsByTxn) maintained in DatabaseTransactionMgr.unprotectUpdateInMemoryState(), reading subTxnIdToTableCommitInfo directly so ordinary transactions (subTxnIds == null) never NPE and publish-time subTxnIds mutation cannot cause CME. Added real TransactionState coverage in DatabaseTransactionMgrTest. ########## 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: Fixed in b68cefe6a2a. Added an O(1) lock-consistent hasCommittedTxnForTable(dbId, tableId) index in DatabaseTransactionMgr / GlobalTransactionMgr (zero scanning or sorting of running transactions), and sampleLocalStream() now skips the check completely whenever no copied partition is caught up. Added unit tests in DatabaseTransactionMgrTest and OlapStreamMonitorCollectorTest. ########## fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamPendingAgeTracker.java: ########## @@ -0,0 +1,132 @@ +// 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.tso.TSOTimestamp; + +import java.util.HashMap; +import java.util.Map; + +/** + * Lightweight in-memory per-(stream, partition) pending anchor tracker. + * + * <p>Keeps one anchor per lagging partition so continuous base-table writes do not mask backlog + * and idle-then-write partitions report the actual write age rather than the idle duration. + */ +public final class StreamPendingAgeTracker { + public record PendingAnchor(long baselineOffset, long oldestPendingTimeMs) { + } + + public record AgeMeasurement(double pendingAgeSeconds, long oldestPendingTimeMs) { + } + + // Outer key: streamId, inner key: partitionId. + private Map<Long, Map<Long, PendingAnchor>> anchorsByStream = new HashMap<>(); + + /** Begin building the next round's active anchor map; dropped or caught-up partitions are naturally GC'd. */ + public Round beginRound() { + return new Round(this, anchorsByStream); + } + + public void clear() { + anchorsByStream = new HashMap<>(); + } + + public static final class Round { + private final StreamPendingAgeTracker owner; + private final Map<Long, Map<Long, PendingAnchor>> previousAnchorsByStream; + private final Map<Long, Map<Long, PendingAnchor>> nextAnchorsByStream = new HashMap<>(); + + private Round(StreamPendingAgeTracker owner, Map<Long, Map<Long, PendingAnchor>> previousAnchorsByStream) { + this.owner = owner; + this.previousAnchorsByStream = previousAnchorsByStream; + } + + /** + * Compute the pending age of one partition and update its anchor for the next round. + */ + public AgeMeasurement recordPartition(long streamId, long partitionId, boolean hasData, + Long offset, Long historicalTso, long endTso, long fallbackVisibleTimeMs, long sampleTimeMs) { + if (isCaughtUp(hasData, offset, historicalTso, endTso)) { + return new AgeMeasurement(0.0, 0L); + } + long baseline = baselineKey(offset, historicalTso); + Map<Long, PendingAnchor> prevStreamAnchors = previousAnchorsByStream.get(streamId); + PendingAnchor previous = prevStreamAnchors == null ? null : prevStreamAnchors.get(partitionId); + long oldestPendingTimeMs; + if (previous != null && previous.baselineOffset() == baseline) { + oldestPendingTimeMs = previous.oldestPendingTimeMs(); + } else { + oldestPendingTimeMs = anchorTimeMs(historicalTso, endTso, fallbackVisibleTimeMs, sampleTimeMs); Review Comment: Updated Cloud mode as well in b68cefe6a2a: added TSOService.getLiveCommittedTsos() backed by TSOTransactionTracker.liveCommittedTsos() under TSOService.lock, and fetchCloudChunk() now uses per-table live safe read TSOs (oldestPendingTso - 1 when in-flight commits exist) as preRefTso so in-flight Cloud commits cannot understate pending age or falsely report RESUMABLE. Added tests in TSOTransactionTrackerTest and OlapStreamMonitorCollectorTest. -- 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]
