hello-stephen commented on code in PR #71199: URL: https://github.com/apache/doris/pull/71199#discussion_r4793993116
########## fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java: ########## @@ -0,0 +1,303 @@ +// 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.ChangelogConfig; +import org.apache.doris.catalog.Database; +import org.apache.doris.catalog.DatabaseIf; +import org.apache.doris.catalog.KeysType; +import org.apache.doris.catalog.MTMV; +import org.apache.doris.catalog.OlapTable; +import org.apache.doris.catalog.Table; +import org.apache.doris.changelog.ChangelogUtils; +import org.apache.doris.mtmv.ivm.IvmUtil; +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(); + } + + /** + * Whether this stream is owned by an IVM materialized view (whose unconsumed partitions read + * the base table directly via {@code NormalizeOlapTableStreamScan.filterConsumedPartitionIds()}). + * Verifies actual MTMV ownership rather than matching the naming prefix alone. + */ + public static boolean isIvmStream(OlapTableStream stream, OlapTable baseTable) { + if (stream == null || baseTable == null) { + return false; + } + String streamName = stream.getName(); + if (streamName == null || !streamName.startsWith(IvmUtil.IVM_STREAM_PREFIX)) { + return false; + } + int idStart = IvmUtil.IVM_STREAM_PREFIX.length(); + int idEnd = streamName.indexOf('_', idStart); + if (idEnd <= idStart) { + return false; + } + long mvId; + try { + mvId = Long.parseLong(streamName.substring(idStart, idEnd)); + } catch (NumberFormatException e) { + return false; + } + DatabaseIf<?> db = stream.getDatabase(); + if (!(db instanceof Database internalDb)) { + return false; + } + Table candidate = internalDb.getTableNullable(mvId); + if (!(candidate instanceof MTMV mv) || !mv.isIvm()) { + return false; + } + return streamName.equals(IvmUtil.streamName(mvId, baseTable.getFullQualifiers())); Review Comment: [P2] Keep stream diagnostics available during a database rename `baseTable.getFullQualifiers()` looks up the database by the table's current name and dereferences the result. `InternalCatalog.renameDatabase()` updates each table's qualified database name before installing the new name in the catalog map, and it does so without taking the table locks held here. With an IVM view and its stream in one database and the base table in another, the MV lookup can succeed while the base database lookup returns null. That aborts the entire monitoring SQL request and can also abort a background sampling round. Resolve the base database through its stable ID or treat a temporarily unavailable qualifier as an unknown observation. ########## fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java: ########## @@ -21,76 +21,330 @@ import org.apache.doris.catalog.Env; import org.apache.doris.catalog.MTMV; import org.apache.doris.catalog.Table; +import org.apache.doris.catalog.stream.OlapStreamMonitorCollector; +import org.apache.doris.catalog.stream.StreamPendingAgeTracker; import org.apache.doris.common.Config; import org.apache.doris.common.util.MasterDaemon; 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.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.LongSupplier; -/** Samples IVM refresh summaries independently of the metrics scrape path. */ +/** Samples IVM refresh summaries and OLAP table streams independently of the metrics scrape path. */ public class ChangelogMonitor extends MasterDaemon { private static final Logger LOG = LogManager.getLogger(ChangelogMonitor.class); private static final long CHECK_INTERVAL_MS = 1000; + // Publish completed stream samples in bounded batches (or once per second) so large clusters + // avoid O(N^2) snapshot rebuilds while still publishing early healthy streams before slow work. + private static final int STREAM_PUBLISH_BATCH_SIZE = 128; + private static final long STREAM_PUBLISH_FLUSH_NANOS = TimeUnit.SECONDS.toNanos(1); + + @FunctionalInterface + interface StreamCollector { + List<ChangelogMonitorSnapshot.StreamHealth> collect(Env env, LongSupplier wallClockMs, + LongSupplier nanoClock, StreamPendingAgeTracker tracker, + Map<Long, ChangelogMonitorSnapshot.StreamHealth> previousByStreamId, + Consumer<ChangelogMonitorSnapshot.StreamHealth> onStreamSampled); + } private final Env env; + private final StreamCollector streamCollector; + private final ExecutorService streamExecutor; private volatile SamplingState state = new SamplingState(); private static class SamplingState { - private long lastRoundNanos; - private boolean hasRun; + private final Object publishLock = new Object(); + private long lastIvmRoundNanos; + private boolean ivmHasRun; + private long lastStreamRoundNanos; + private boolean streamHasRun; + private final AtomicBoolean streamInFlight = new AtomicBoolean(false); private volatile ChangelogMonitorSnapshot snapshot; + private final StreamPendingAgeTracker pendingAgeTracker = new StreamPendingAgeTracker(); + private List<ChangelogMonitorSnapshot.IvmRefresh> lastIvmRefreshes = Collections.emptyList(); + private Map<Long, ChangelogMonitorSnapshot.StreamHealth> lastStreamHealths = Collections.emptyMap(); } public ChangelogMonitor(Env env) { + this(env, OlapStreamMonitorCollector::collectIncremental); + } + + ChangelogMonitor(Env env, StreamCollector streamCollector) { super("changelog-monitor", CHECK_INTERVAL_MS); this.env = env; + this.streamCollector = streamCollector; + this.streamExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "changelog-monitor-stream-collector"); + t.setDaemon(true); + return t; + }); } @Override protected void runAfterCatalogReady() { - sample(System.nanoTime()); + sampleAsyncStream(System.nanoTime(), System::currentTimeMillis, System::nanoTime); + } + + void sample(long nowNanos) { + sample(nowNanos, System::currentTimeMillis, () -> nowNanos); + } + + void sample(long nowNanos, long nowWallMs) { + sample(nowNanos, () -> nowWallMs, () -> nowNanos); } - void sample(long now) { + /** Synchronous sampling used by deterministic unit tests. */ + void sample(long nowNanos, LongSupplier wallClockMs, LongSupplier nanoClock) { SamplingState current = state; if (!isActive()) { - current.snapshot = null; - current.hasRun = false; + clearState(current); return; } - long interval = TimeUnit.SECONDS.toNanos(Math.max(1, Config.changelog_monitor_interval_seconds)); - if (current.hasRun && now - current.lastRoundNanos < interval) { + if (current.ivmHasRun && nowNanos - current.lastIvmRoundNanos < interval) { return; } - current.hasRun = true; - current.lastRoundNanos = now; + current.ivmHasRun = true; + current.lastIvmRoundNanos = nowNanos; + current.streamHasRun = true; + current.lastStreamRoundNanos = nowNanos; try { - current.snapshot = collect(); + ChangelogMonitorSnapshot next = collect(current, wallClockMs, nanoClock); + if (next != null) { + synchronized (current.publishLock) { + if (current == state) { + current.lastIvmRefreshes = next.ivmRefreshes(); + current.lastStreamHealths = next.streamHealthById(); + current.snapshot = next; + } + } + } } catch (RuntimeException e) { LOG.warn("Failed to collect a changelog monitor snapshot", e); + handleStreamFailure(current); } } - private boolean isActive() { - return Config.enable_changelog_monitor && env.isMaster() && env.isReady(); + /** + * Daemon sampling path: IVM refresh summaries are collected and published synchronously on their + * own cadence, while OLAP stream collection runs on a dedicated daemon thread so stalled Cloud + * MetaService RPCs never delay IVM metric publication. + */ + void sampleAsyncStream(long nowNanos, LongSupplier wallClockMs, LongSupplier nanoClock) { + SamplingState current = state; + if (!isActive()) { + clearState(current); + return; + } + long interval = TimeUnit.SECONDS.toNanos(Math.max(1, Config.changelog_monitor_interval_seconds)); + if (!current.ivmHasRun || nowNanos - current.lastIvmRoundNanos >= interval) { + current.ivmHasRun = true; + current.lastIvmRoundNanos = nowNanos; + collectAndPublishIvm(current, wallClockMs); + } + if ((!current.streamHasRun || nowNanos - current.lastStreamRoundNanos >= interval) + && current.streamInFlight.compareAndSet(false, true)) { + current.streamHasRun = true; + current.lastStreamRoundNanos = nowNanos; + streamExecutor.execute(() -> { + try { + if (current != state || !isActive()) { Review Comment: [P2] Stop superseded stream collection rounds between requests Disabling the monitor replaces `SamplingState`, but a worker that already passed this check can still traverse every remaining stream and issue every remaining Cloud batch. If monitoring is re-enabled while one RPC is blocked, the new round queues behind all that obsolete work on the same executor. Check cancellation between streams and before subsequent MetaService requests so the old round stops after the in-flight operation and a fresh round can start. ########## fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java: ########## @@ -0,0 +1,857 @@ +// 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.Pair; +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.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.Consumer; +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, null); + } + + public static List<StreamHealth> collectIncremental(Env env, LongSupplier wallClockMs, LongSupplier nanoClock, + StreamPendingAgeTracker tracker, Map<Long, StreamHealth> previousByStreamId, + Consumer<StreamHealth> onStreamSampled) { + return collect(env, wallClockMs, nanoClock, tracker, previousByStreamId, + CloudTableStreamReadStateHelper::getReadStates, onStreamSampled); + } + + 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, null); + } + + public static List<StreamHealth> collect(Env env, LongSupplier wallClockMs, LongSupplier nanoClock, + StreamPendingAgeTracker tracker, Map<Long, StreamHealth> previousByStreamId, + CloudStateFetcher cloudFetcher) { + return collect(env, wallClockMs, nanoClock, tracker, previousByStreamId, cloudFetcher, null); + } + + public static List<StreamHealth> collect(Env env, LongSupplier wallClockMs, LongSupplier nanoClock, + StreamPendingAgeTracker tracker, Map<Long, StreamHealth> previousByStreamId, + CloudStateFetcher cloudFetcher, Consumer<StreamHealth> onStreamSampled) { + 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, onStreamSampled) + : collectLocal(env, dbStreamMap, wallClockMs, nanoClock, ageRound, previousByStreamId, + onStreamSampled); + 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; + } + + /** + * Capture per-base-table live safe read TSO watermarks from {@link TSOService} before a Cloud MetaService + * read RPC, accounting for all in-flight Cloud commits registered in {@code TSOTransactionTracker}. + */ + private static Map<Pair<Long, Long>, Long> getSafePreRefTsos( + Env env, Set<Cloud.TableStreamIdentityPB> identities) { + TSOService tsoService = env.getTSOService(); + if (tsoService == null || identities.isEmpty()) { + return Collections.emptyMap(); + } + Set<Pair<Long, Long>> dbTables = new HashSet<>(identities.size() * 2); + for (Cloud.TableStreamIdentityPB id : identities) { + dbTables.add(Pair.of(id.getBaseDbId(), id.getBaseTableId())); + } + Map<Pair<Long, Long>, Long> tsos = tsoService.getLiveCommittedTsos(dbTables); + return tsos == null ? Collections.emptyMap() : tsos; + } + + /** 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 via the O(1) lock-consistent index on {@code DatabaseTransactionMgr}. Must be called while holding + * {@code baseTable}'s read lock, matching canonical {@code Table.rwLock -> DatabaseTransactionMgr.transactionLock}. + */ + private static boolean hasUnpublishedCommittedTxn(Env env, long baseDbId, long baseTableId) { + GlobalTransactionMgrIface txnMgr = env.getGlobalTransactionMgr(); + if (txnMgr == null) { + return false; + } + try { + return txnMgr.hasCommittedTxnForTable(baseDbId, baseTableId); + } catch (AnalysisException e) { + // Database has no transaction manager yet -> no committed transactions exist. + return false; + } + } + + private static List<StreamHealth> collectLocal(Env env, Map<Long, Set<Long>> dbStreamMap, + LongSupplier wallClockMs, LongSupplier nanoClock, StreamPendingAgeTracker.Round ageRound, + Map<Long, StreamHealth> previousByStreamId, Consumer<StreamHealth> onStreamSampled) { + 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(env, db.getId(), dbName, stream, wallClockMs, nanoClock, + ageRound, previousByStreamId); + if (health != null) { + results.add(health); + if (onStreamSampled != null) { + onStreamSampled.accept(health); + } + } + } + } + return results; + } + + private static StreamHealth sampleLocalStream(Env env, long streamDbId, String dbName, OlapTableStream stream, + 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(), + previousByStreamId, ageRound); + } + String streamName; + long streamId; + StreamResumabilityChecker.Result streamLevelResult; + boolean hasChangelogTtl = false; + long changelogTtlSeconds = 0L; + long priorCleanupCutoffTso = 0L; + boolean rejectExpiredStart = true; + boolean isIvmStream = false; + boolean mayFilterOutWrites = false; + Long caughtUpRefTso = null; + List<RawPartitionInput> rawInputs = Collections.emptyList(); + try { + if (stream.isDropped) { + return null; + } + streamName = stream.getName(); + streamId = stream.getId(); + OlapTable effectiveBase = (baseTable != null && !baseTable.isDropped) ? baseTable : null; + streamLevelResult = StreamResumabilityChecker.checkStreamLevel(stream, effectiveBase); + // Match Cloud short-circuit semantics when stream-level prerequisites already fail. + if (effectiveBase == null + || streamLevelResult.status() == StreamResumabilityChecker.Status.CANNOT_RESUME) { + return new StreamHealth(dbName, streamName, streamId, true, + wallClockMs.getAsLong(), nanoClock.getAsLong(), -1.0, streamLevelResult, Map.of()); + } + hasChangelogTtl = effectiveBase.hasChangelogTtl(); + if (hasChangelogTtl) { + changelogTtlSeconds = effectiveBase.getChangelogConfig().getTtlSeconds(); + priorCleanupCutoffTso = effectiveBase.getChangelogConfig().getPriorCleanupCutoffTso(); + } + isIvmStream = StreamResumabilityChecker.isIvmStream(stream, effectiveBase); + rejectExpiredStart = StreamResumabilityChecker.rejectsExpiredStart(stream, effectiveBase); + mayFilterOutWrites = StreamResumabilityChecker.mayFilterOutWrites(stream, effectiveBase); + List<RawPartitionInput> copied = new ArrayList<>(); + boolean anyCaughtUp = false; + for (Partition partition : effectiveBase.getPartitions()) { + OlapTableStream.PartitionStreamState state = stream.getPartitionState(partition.getId()); + boolean hasData = partition.hasData(); + Long offset = state == null ? null : state.getOffset(); + Long historicalTso = state == null ? null : state.getHistoricalTso(); + long endTso = partition.getTso(); + if (!anyCaughtUp && StreamPendingAgeTracker.isCaughtUp(hasData, offset, historicalTso, endTso)) { + anyCaughtUp = true; + } + copied.add(new RawPartitionInput( + partition.getId(), + partition.getName(), + hasData, + offset, + historicalTso, + endTso, + partition.getVisibleVersionTime())); + } + rawInputs = copied; + // Only query transaction manager and capture caughtUpRefTso when at least one partition is caught up. + // Under baseTable.readLock no new commitTSO can be allocated and no COMMITTED txn can publish; only when + // zero unpublished COMMITTED txns exist for baseTable does caughtUpRefTso strictly bound future writes. + if (anyCaughtUp) { + long baseDbId = stream.getBaseTableInfo() != null ? stream.getBaseTableInfo().getDbId() : streamDbId; + if (!hasUnpublishedCommittedTxn(env, baseDbId, effectiveBase.getId())) { + caughtUpRefTso = getReferenceTso(env); + } + } + } finally { + MetaLockUtils.readUnlockTables(tablesToLock); + } + // Capture post-lock TSO reference and sample timestamps together right after unlocking so delayed streams + // are always evaluated against a current TTL cutoff matching their freshness timestamp. + Long postRefTso = getReferenceTso(env); + long postWallMs = wallClockMs.getAsLong(); + long postNanos = nanoClock.getAsLong(); + Long cutoffTso = calculateCutoffTso(hasChangelogTtl, changelogTtlSeconds, postRefTso); + long refTimeMs = resolveReferenceTimeMs(postRefTso, postWallMs); + long caughtUpTsoTimeMs = extractTsoPhysicalTimeMs(caughtUpRefTso); + List<PartitionEvalInput> evalInputs = new ArrayList<>(rawInputs.size()); + for (RawPartitionInput raw : rawInputs) { + evalInputs.add(new PartitionEvalInput(raw.partitionId, raw.partitionName, raw.hasData, raw.offset, + raw.historicalTso, raw.endTso, raw.fallbackVisibleTimeMs, cutoffTso, refTimeMs, + caughtUpTsoTimeMs, postNanos)); + } + return evaluatePartitions(dbName, streamName, streamId, streamLevelResult, hasChangelogTtl, + priorCleanupCutoffTso, rejectExpiredStart, isIvmStream, mayFilterOutWrites, + evalInputs, postWallMs, postNanos, ageRound); + } + + private static List<StreamHealth> collectCloud(Env env, Map<Long, Set<Long>> dbStreamMap, + LongSupplier wallClockMs, LongSupplier nanoClock, StreamPendingAgeTracker.Round ageRound, + Map<Long, StreamHealth> previousByStreamId, CloudStateFetcher cloudFetcher, + Consumer<StreamHealth> onStreamSampled) { + 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(), + previousByStreamId, ageRound)); + } + continue; + } + try { + if (stream.isDropped) { + continue; + } + String streamName = stream.getName(); + long streamId = stream.getId(); + 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 changelogTtlSeconds = hasChangelogTtl + ? effectiveBase.getChangelogConfig().getTtlSeconds() : 0L; + long priorCleanupCutoffTso = hasChangelogTtl + ? effectiveBase.getChangelogConfig().getPriorCleanupCutoffTso() : 0L; + boolean isIvmStream = StreamResumabilityChecker.isIvmStream(stream, effectiveBase); + boolean rejectExpiredStart = StreamResumabilityChecker.rejectsExpiredStart(stream, effectiveBase); + boolean mayFilterOutWrites = StreamResumabilityChecker.mayFilterOutWrites(stream, effectiveBase); + long metaSnapshotNanos = nanoClock.getAsLong(); + Map<Long, String> partitionNames = new LinkedHashMap<>(); + for (Partition partition : effectiveBase.getPartitions()) { + partitionNames.put(partition.getId(), partition.getName()); + } + if (partitionNames.isEmpty()) { + StreamHealth emptyHealth = new StreamHealth(dbName, streamName, streamId, true, + wallClockMs.getAsLong(), metaSnapshotNanos, 0.0, streamLevel, Map.of()); + results.add(emptyHealth); + if (onStreamSampled != null) { + onStreamSampled.accept(emptyHealth); + } + 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, + streamLevel, hasChangelogTtl, changelogTtlSeconds, priorCleanupCutoffTso, + rejectExpiredStart, isIvmStream, mayFilterOutWrites, metaSnapshotNanos, partitionNames)); + } finally { + MetaLockUtils.readUnlockTables(tablesToLock); + } + } + } + + if (cloudTargets.isEmpty()) { + return results; + } + + Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetchedStates = + fetchCloudStatesChunked(env, 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.partitionSamples == null) { + results.add(handleTransientSampleFailure(meta.dbName, meta.streamName, meta.streamId, + previousByStreamId, ageRound)); + continue; + } + List<PartitionEvalInput> evalInputs = new ArrayList<>(meta.partitionNames.size()); + boolean incomplete = false; + for (Map.Entry<Long, String> partEntry : meta.partitionNames.entrySet()) { + PartitionFetchSample sample = fetchResult.partitionSamples.get(partEntry.getKey()); + Cloud.TableStreamPartitionReadStatePB pb = sample == null ? null : sample.state; + 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(); + } + // Evaluate each partition using its own slice's TSOs: pre-RPC TSO bounds caught-up time + // before MetaService read latency, while post-RPC TSO computes current age and TTL cutoff. + Long cutoffTso = calculateCutoffTso(meta.hasChangelogTtl, meta.changelogTtlSeconds, sample.postRefTso); + long refTimeMs = resolveReferenceTimeMs(sample.postRefTso, sample.postWallMs); + long caughtUpTsoTimeMs = extractTsoPhysicalTimeMs(sample.preRefTso); + evalInputs.add(new PartitionEvalInput(partEntry.getKey(), partEntry.getValue(), hasData, + offset, historicalTso, pb.getEndTso(), 0L, cutoffTso, refTimeMs, + caughtUpTsoTimeMs, sample.preNanos)); + } + if (incomplete) { + results.add(handleTransientSampleFailure(meta.dbName, meta.streamName, meta.streamId, + previousByStreamId, ageRound)); + continue; + } + long freshnessNanos = Math.min(meta.metaSnapshotNanos, fetchResult.sampleNanos); + StreamHealth health = evaluatePartitions(meta.dbName, meta.streamName, meta.streamId, + meta.streamLevelResult, meta.hasChangelogTtl, meta.priorCleanupCutoffTso, + meta.rejectExpiredStart, meta.isIvmStream, meta.mayFilterOutWrites, evalInputs, + fetchResult.sampleWallMs, freshnessNanos, ageRound); + results.add(health); + if (onStreamSampled != null) { + onStreamSampled.accept(health); + } + } + return results; + } + + private static Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetchCloudStatesChunked( + Env env, 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, Set<Long>>> chunks = buildBoundedChunks(targets, maxPartitionsPerBatch); + + long fallbackBudgetNanos = Math.min(TimeUnit.MILLISECONDS.toNanos(MAX_FALLBACK_BUDGET_MS), + Math.max(TimeUnit.SECONDS.toNanos(1), ChangelogMonitor.getSnapshotExpireNanos() / 3)); + // Track elapsed time spent exclusively in per-stream fallback retries so healthy batch RPCs + // never consume the fallback budget. + long[] fallbackElapsedNanos = {0L}; + Set<Cloud.TableStreamIdentityPB> failedStreams = new HashSet<>(); + + Map<Cloud.TableStreamIdentityPB, CloudFetchResult> fetched = new LinkedHashMap<>(targets.size() * 2); + for (Map<Cloud.TableStreamIdentityPB, Set<Long>> chunk : chunks) { + // Skip remaining slices of a wide single stream whose earlier slice already failed. + if (chunk.size() == 1 && failedStreams.contains(chunk.keySet().iterator().next())) { + continue; + } + boolean stopRound = fetchCloudChunk(env, chunk, targets, wallClockMs, nanoClock, + fallbackBudgetNanos, fallbackElapsedNanos, failedStreams, cloudFetcher, fetched); + if (stopRound) { + break; Review Comment: [P2] Give later Cloud batches a chance after rate limiting When MetaService repeatedly accepts only the first few requests in a round before returning `MAX_QPS_LIMIT`, this break leaves the same suffix unqueried every time. The next round rebuilds its chunks from the same stream and partition order, so healthy streams in that suffix can remain unknown indefinitely. Preserve the stop on overload and resume or rotate the starting position in the next round. A two-round test with a fixed request allowance would exercise the starvation case. -- 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]
