yujun777 commented on code in PR #71199: URL: https://github.com/apache/doris/pull/71199#discussion_r4751402558
########## 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: Fixed in 080b8bb20a8. `StreamPendingAgeTracker` now records explicit caught-up observations and only anchors pending age from `endTso` when a partition transitions from caught-up to lagging on the same baseline (or from `historicalTso` on initial snapshots). On a cold start with existing lag or a partial offset advance without catching up, both `StreamPendingAgeTracker` and `OlapStreamMonitorCollector.evaluateLivePartition()` now report the unknown sentinel (`-1.0`) instead of understating backlog from the latest `endTso`. Anchors and elapsed-age comparisons also stay in the TSO physical-time domain without clamping to local wall clock. ########## fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java: ########## @@ -0,0 +1,540 @@ +// 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.Config; +import org.apache.doris.common.UserException; +import org.apache.doris.common.util.MetaLockUtils; +import org.apache.doris.rpc.RpcException; +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; +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, isolating per-stream logic errors without amplifying transport/timeout 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 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(); + } + Long referenceTso = getReferenceTso(env); + StreamPendingAgeTracker.Round ageRound = tracker.beginRound(); + List<StreamHealth> results = Config.isCloudMode() + ? collectCloud(env, dbStreamMap, referenceTso, wallClockMs, nanoClock, + ageRound, previousByStreamId, cloudFetcher) + : collectLocal(env, dbStreamMap, referenceTso, 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; + } + + /** 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); + } + + private static List<StreamHealth> collectLocal(Env env, Map<Long, Set<Long>> dbStreamMap, Long referenceTso, + LongSupplier wallClockMs, LongSupplier nanoClock, StreamPendingAgeTracker.Round ageRound, + Map<Long, StreamHealth> previousByStreamId) { + List<StreamHealth> results = new ArrayList<>(); + for (Map.Entry<Long, Set<Long>> entry : dbStreamMap.entrySet()) { + Optional<Database> dbOpt = env.getInternalCatalog().getDb(entry.getKey()); + if (dbOpt.isEmpty()) { + continue; + } + Database db = dbOpt.get(); + String dbName = db.getFullName(); + for (Long tableId : entry.getValue()) { + Optional<Table> tableOpt = db.getTable(tableId); + if (tableOpt.isEmpty() || !(tableOpt.get() instanceof OlapTableStream stream)) { + continue; + } + StreamHealth health = sampleLocalStream(dbName, stream, referenceTso, wallClockMs, nanoClock, + ageRound, previousByStreamId); + if (health != null) { + results.add(health); + } + } + } + return results; + } + + private static StreamHealth sampleLocalStream(String dbName, OlapTableStream stream, Long referenceTso, + LongSupplier wallClockMs, LongSupplier nanoClock, StreamPendingAgeTracker.Round ageRound, + Map<Long, StreamHealth> previousByStreamId) { + // Resolve the immutable base table reference before locking so locks are acquired in ascending table-ID order. + OlapTable baseTable = stream.getBaseTableNullableQuiet(); + List<Table> tablesToLock = orderTablesById(stream, baseTable); + if (!MetaLockUtils.tryReadLockTables(tablesToLock, LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + if (stream.isDropped) { + return null; + } + return handleTransientSampleFailure(dbName, stream.getName(), stream.getId(), + null, wallClockMs, nanoClock, previousByStreamId, ageRound); + } + String streamName; + long streamId; + long streamCreateTimeMs; + StreamResumabilityChecker.Result streamLevelResult; + boolean hasChangelogTtl = false; + Long cutoffTso = null; + List<LocalPartitionInput> partitionInputs = Collections.emptyList(); + try { + if (stream.isDropped) { + return null; + } + streamName = stream.getName(); + streamId = stream.getId(); + streamCreateTimeMs = stream.getCreateTime() > 0 ? stream.getCreateTime() * 1000L : 0L; + OlapTable effectiveBase = (baseTable != null && !baseTable.isDropped) ? baseTable : null; + streamLevelResult = StreamResumabilityChecker.checkStreamLevel(stream, effectiveBase); + if (effectiveBase == null) { + return new StreamHealth(dbName, streamName, streamId, true, + wallClockMs.getAsLong(), nanoClock.getAsLong(), -1.0, streamLevelResult, Map.of()); + } + hasChangelogTtl = effectiveBase.hasChangelogTtl(); + cutoffTso = StreamResumabilityChecker.calculateCutoffTso(effectiveBase, referenceTso); + List<LocalPartitionInput> copied = new ArrayList<>(); + for (Partition partition : effectiveBase.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 { + MetaLockUtils.readUnlockTables(tablesToLock); + } + return evaluatePartitions(dbName, streamName, streamId, streamCreateTimeMs, streamLevelResult, + hasChangelogTtl, cutoffTso, partitionInputs, wallClockMs.getAsLong(), nanoClock.getAsLong(), ageRound); + } + + private static List<StreamHealth> collectCloud(Env env, Map<Long, Set<Long>> dbStreamMap, Long referenceTso, + LongSupplier wallClockMs, LongSupplier nanoClock, StreamPendingAgeTracker.Round ageRound, + Map<Long, StreamHealth> previousByStreamId, CloudStateFetcher cloudFetcher) { + List<StreamHealth> results = new ArrayList<>(); + Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> cloudTargets = new LinkedHashMap<>(); + + for (Map.Entry<Long, Set<Long>> entry : dbStreamMap.entrySet()) { + Optional<Database> dbOpt = env.getInternalCatalog().getDb(entry.getKey()); + if (dbOpt.isEmpty()) { + continue; + } + Database db = dbOpt.get(); + String dbName = db.getFullName(); + for (Long tableId : entry.getValue()) { + Optional<Table> tableOpt = db.getTable(tableId); + if (tableOpt.isEmpty() || !(tableOpt.get() instanceof OlapTableStream stream)) { + continue; + } + OlapTable baseTable = stream.getBaseTableNullableQuiet(); + List<Table> tablesToLock = orderTablesById(stream, baseTable); + if (!MetaLockUtils.tryReadLockTables(tablesToLock, LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + if (!stream.isDropped) { + results.add(handleTransientSampleFailure(dbName, stream.getName(), stream.getId(), + null, wallClockMs, nanoClock, previousByStreamId, ageRound)); + } + continue; + } + try { + if (stream.isDropped) { + continue; + } + String streamName = stream.getName(); + long streamId = stream.getId(); + long streamCreateTimeMs = stream.getCreateTime() > 0 ? stream.getCreateTime() * 1000L : 0L; + OlapTable effectiveBase = (baseTable != null && !baseTable.isDropped) ? baseTable : null; + StreamResumabilityChecker.Result streamLevel = + StreamResumabilityChecker.checkStreamLevel(stream, effectiveBase); + // Short-circuit streams already known locally to be unresumable so they never poison + // healthy streams' MetaService batch RPCs or get masked on RPC failure. + if (effectiveBase == null + || streamLevel.status() == StreamResumabilityChecker.Status.CANNOT_RESUME) { + results.add(new StreamHealth(dbName, streamName, streamId, true, + wallClockMs.getAsLong(), nanoClock.getAsLong(), -1.0, streamLevel, Map.of())); + continue; + } + boolean hasChangelogTtl = effectiveBase.hasChangelogTtl(); + Long cutoffTso = StreamResumabilityChecker.calculateCutoffTso(effectiveBase, referenceTso); + Map<Long, String> partitionNames = new LinkedHashMap<>(); + for (Partition partition : effectiveBase.getPartitions()) { + partitionNames.put(partition.getId(), partition.getName()); + } + if (partitionNames.isEmpty()) { + results.add(new StreamHealth(dbName, streamName, streamId, true, + wallClockMs.getAsLong(), nanoClock.getAsLong(), 0.0, streamLevel, Map.of())); + continue; + } + Cloud.TableStreamIdentityPB identity = Cloud.TableStreamIdentityPB.newBuilder() + .setBaseDbId(stream.getBaseTableInfo().getDbId()) + .setBaseTableId(stream.getBaseTableInfo().getTableId()) + .setStreamDbId(entry.getKey()) + .setStreamId(streamId) + .build(); + cloudTargets.put(identity, new CloudStreamMetadata(dbName, streamName, streamId, + streamCreateTimeMs, streamLevel, hasChangelogTtl, cutoffTso, partitionNames)); + } finally { + MetaLockUtils.readUnlockTables(tablesToLock); + } + } + } + + if (cloudTargets.isEmpty()) { + return results; + } + + Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetchedStates = + fetchCloudStatesChunked(cloudTargets, wallClockMs, nanoClock, cloudFetcher); + + for (Map.Entry<Cloud.TableStreamIdentityPB, CloudStreamMetadata> entry : cloudTargets.entrySet()) { + CloudStreamMetadata meta = entry.getValue(); + CloudFetchResult fetchResult = fetchedStates.get(entry.getKey()); + if (fetchResult == null || fetchResult.partitionStates == null) { + results.add(handleTransientSampleFailure(meta.dbName, meta.streamName, meta.streamId, + meta.streamLevelResult, wallClockMs, nanoClock, 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 = fetchResult.partitionStates.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(handleTransientSampleFailure(meta.dbName, meta.streamName, meta.streamId, + meta.streamLevelResult, wallClockMs, nanoClock, previousByStreamId, ageRound)); + continue; + } + results.add(evaluatePartitions(meta.dbName, meta.streamName, meta.streamId, meta.streamCreateTimeMs, + meta.streamLevelResult, meta.hasChangelogTtl, meta.cutoffTso, inputs, + fetchResult.sampleWallMs, fetchResult.sampleNanos, ageRound)); + } + return results; + } + + private static Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetchCloudStatesChunked( + Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> targets, + LongSupplier wallClockMs, LongSupplier nanoClock, CloudStateFetcher cloudFetcher) { + int maxPartitionsPerBatch = Math.max(1, Config.cloud_table_stream_create_partition_batch_size); + List<Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata>> chunks = new ArrayList<>(); + Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> currentChunk = new LinkedHashMap<>(); + int currentPartitions = 0; + for (Map.Entry<Cloud.TableStreamIdentityPB, CloudStreamMetadata> entry : targets.entrySet()) { + int partCount = entry.getValue().partitionNames.size(); + if (!currentChunk.isEmpty() && currentPartitions + partCount > maxPartitionsPerBatch) { + chunks.add(currentChunk); + currentChunk = new LinkedHashMap<>(); + currentPartitions = 0; + } + currentChunk.put(entry.getKey(), entry.getValue()); + currentPartitions += partCount; + } + if (!currentChunk.isEmpty()) { + chunks.add(currentChunk); + } + + long fallbackBudgetNanos = Math.min(TimeUnit.MILLISECONDS.toNanos(MAX_FALLBACK_BUDGET_MS), + Math.max(TimeUnit.SECONDS.toNanos(1), ChangelogMonitor.getSnapshotExpireNanos() / 3)); + long fallbackDeadlineNanos = nanoClock.getAsLong() + fallbackBudgetNanos; + + Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetched = new LinkedHashMap<>(targets.size() * 2); + for (Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> chunk : chunks) { + boolean transportFailed = fetchCloudChunk(chunk, wallClockMs, nanoClock, + fallbackDeadlineNanos, cloudFetcher, fetched); + if (transportFailed) { + // Stop issuing further RPCs this round when MetaService transport/timeout is failing. + break; + } + } + return fetched; + } + + /** Returns true when a MetaService transport/timeout/rate-limit error occurred. */ + private static boolean fetchCloudChunk(Map<Cloud.TableStreamIdentityPB, CloudStreamMetadata> chunk, + LongSupplier wallClockMs, LongSupplier nanoClock, long fallbackDeadlineNanos, + CloudStateFetcher cloudFetcher, Map<Cloud.TableStreamIdentityPB, CloudFetchResult> output) { + Map<Cloud.TableStreamIdentityPB, Set<Long>> batchRequest = new LinkedHashMap<>(); + chunk.forEach((identity, meta) -> batchRequest.put(identity, meta.partitionNames.keySet())); + try { + Map<Cloud.TableStreamIdentityPB, Map<Long, Cloud.TableStreamPartitionReadStatePB>> resp = + cloudFetcher.fetch(batchRequest); + long postWallMs = wallClockMs.getAsLong(); + long postNanos = nanoClock.getAsLong(); + if (resp != null) { + for (Map.Entry<Cloud.TableStreamIdentityPB, Map<Long, Cloud.TableStreamPartitionReadStatePB>> e + : resp.entrySet()) { + if (e.getValue() != null) { + output.put(e.getKey(), new CloudFetchResult(e.getValue(), postWallMs, postNanos)); + } + } + } + return false; + } catch (UserException | RuntimeException e) { + if (isTransportError(e)) { Review Comment: Fixed in 080b8bb20a8. `CloudTableStreamReadStateHelper.getReadStates()` now throws a structured `MetaServiceStatusException` preserving `Cloud.MetaServiceCode`, and `OlapStreamMonitorCollector.isServiceOutageError()` classifies `MAX_QPS_LIMIT`, `MS_TOO_BUSY`, and FDB `KV_TXN_*` statuses (as well as `RpcException`) as non-retryable outages that immediately stop per-stream fallback and remaining chunks. Also added wide single-stream partition slicing, fallback-only budget accounting, and unit tests for `MAX_QPS_LIMIT` and `KV_TXN_TOO_OLD`. -- 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]
