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


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,273 @@
+// 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.KeysType;
+import org.apache.doris.catalog.OlapTable;
+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 an internal IVM stream (whose unconsumed 
partitions read the base table directly). */
+    public static boolean isIvmStream(OlapTableStream stream) {
+        if (stream == null) {
+            return false;
+        }
+        String streamName = stream.getName();
+        return streamName != null && 
streamName.startsWith(IvmUtil.IVM_STREAM_PREFIX);

Review Comment:
   Fixed in 2e4d9d846f7. StreamResumabilityChecker.isIvmStream(stream, 
baseTable) now parses the MV ID and verifies actual IVM MTMV ownership and 
IvmUtil.streamName(mvId, baseTable.getFullQualifiers()) match in the database 
rather than matching the name prefix alone. Added unit test for an ordinary 
stream named __doris_ivm_stream_example.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/ChangelogConfig.java:
##########
@@ -162,6 +180,9 @@ public Map<String, String> toProperties() {
         if (configVersion != 0) {
             properties.put(CONFIG_VERSION, String.valueOf(configVersion));
         }
+        if (priorCleanupCutoffTso != 0) {

Review Comment:
   Fixed in 2e4d9d846f7. Stream, changelog, and IVM features are not yet 
externally released, so there are no pre-upgrade altered tables with missing 
cleanup-cutoff history. Removed the legacy unknown fallback in TableProperty so 
priorCleanupCutoffTso=0 consistently represents no prior TTL extension across 
replay and failover.



##########
fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java:
##########
@@ -4349,6 +4349,32 @@ private void updateChangelogConfig(Database db, 
OlapTable table, ChangelogConfig
                 throw new DdlException(
                         "Partitions changed during changelog configuration 
update; retry ALTER TABLE");
             }
+            if (oldConfig.isTtlEnabled() && newConfig.getTtlSeconds() > 
oldConfig.getTtlSeconds()) {
+                org.apache.doris.tso.TSOService tsoService = 
Env.getCurrentEnv().getTSOService();
+                org.apache.doris.tso.TSOService.TSOStatusSnapshot tsoStatus =
+                        tsoService == null ? null : 
tsoService.getStatusSnapshot();
+                long baseTso = 0L;
+                if (tsoStatus != null && tsoStatus.isInitialized() && 
tsoStatus.getCurrentTso() > 0) {
+                    baseTso = tsoStatus.getCurrentTso();
+                } else if (tsoStatus != null && 
tsoStatus.getWindowEndPhysicalTimeMs() > 0) {
+                    // Use the conservative replayed durable allocator window 
bound rather than an
+                    // unproven local wall clock before TSO calibration 
finishes.
+                    baseTso = org.apache.doris.tso.TSOTimestamp.composeRealTso(
+                            Math.max(System.currentTimeMillis(), 
tsoStatus.getWindowEndPhysicalTimeMs()), 0L);
+                }
+                if (baseTso > 0) {
+                    long oldCutoffTso = 
org.apache.doris.tso.TSOTimestamp.calculateCutoff(
+                            baseTso, oldConfig.getTtlSeconds());

Review Comment:
   Not changing SchemaChangeHandler replica-update protocol in this monitoring 
PR: updateChangelogConfig() already uses Doris's existing 
updatePartitionProperties() path for changelog TTL changes, and replica-clone 
convergence belongs to the changelog alter/clone subsystem rather than stream 
monitoring.



##########
be/src/information_schema/schema_table_stream_consumption_scanner.cpp:
##########
@@ -56,9 +63,35 @@ Status 
SchemaTableStreamConsumptionScanner::start(RuntimeState* state) {
     return Status::OK();
 }
 
+bool SchemaTableStreamConsumptionScanner::_needs_monitoring_columns() const {
+    if (_param == nullptr || _param->common_param == nullptr) {
+        return false;
+    }
+    const auto& required = _param->common_param->required_columns;
+    for (size_t i = kLegacyTableStreamConsumptionColumnCount;
+         i < _s_table_stream_consumption_columns.size(); ++i) {
+        if (required.contains(_s_table_stream_consumption_columns[i].name)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 TFetchSchemaTableDataRequest 
SchemaTableStreamConsumptionScanner::_build_fetch_request() const {
     TSchemaTableRequestParams schema_table_request_params;
-    if (_param->common_param->frontend_conjuncts) {
+    // Request the 10-column schema only when the query actually projects a 
monitoring column.
+    // Leaving columns_name unset for legacy-only queries keeps BE-before-FE 
rolling upgrades
+    // compatible with older Master FEs in a single RPC and lets new Master 
FEs skip monitoring work.
+    if (_needs_monitoring_columns()) {
+        std::vector<std::string> columns;
+        columns.reserve(_s_table_stream_consumption_columns.size());
+        for (const auto& column : _s_table_stream_consumption_columns) {
+            columns.emplace_back(column.name);
+        }
+        schema_table_request_params.__set_columns_name(columns);

Review Comment:
   Stream, changelog, and IVM are unreleased experimental features, so mixed-FE 
compatibility between an upgraded follower and an older master for 
information_schema.table_stream_consumption is out of scope.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -597,11 +638,18 @@ private CloudStreamConsumptionSnapshot 
selectUnits(StreamConsumptionSelector sel
             }
             return selectedPartitions.isEmpty()
                     ? null
-                    : new CloudStreamConsumptionSnapshot(dbName, streamName, 
streamId, selectedPartitions);
+                    : new CloudStreamConsumptionSnapshot(dbName, streamName, 
streamId,
+                            streamLevel, hasChangelogTtl, changelogTtlSeconds,
+                            priorCleanupCutoffTso, rejectExpiredStart, 
isIvmStream, mayFilterOutWrites,
+                            selectedPartitions);
         }
 
         private void fillRows(Map<Long, Cloud.TableStreamPartitionReadStatePB> 
partitionStates,
-                List<TRow> dataBatch) throws UserException {
+                List<TRow> dataBatch, boolean includeMonitoringColumns, Long 
referenceTso, long nowMs,
+                long nowNanos, long expireNanos, ChangelogMonitorSnapshot 
monitorSnapshot) throws UserException {
+            Long cutoffTso = includeMonitoringColumns
+                    ? 
OlapStreamMonitorCollector.calculateCutoffTso(hasChangelogTtl, 
changelogTtlSeconds, referenceTso)

Review Comment:
   Fixed in 2e4d9d846f7. CloudStreamConsumptionSnapshot now records 
changelogConfigVersion and revalidates it against 
baseTable.getChangelogConfig().getConfigVersion() after the MetaService offset 
RPC returns, reporting UNKNOWN (STATE_UNAVAILABLE) if the table's changelog 
config changed concurrently.



##########
fe/fe-core/src/main/java/org/apache/doris/changelog/ChangelogMonitor.java:
##########
@@ -21,76 +21,310 @@
 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;
 
+    @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()) {
+                        return;
+                    }
+                    collectAndPublishStream(current, wallClockMs, nanoClock);
+                } finally {
+                    current.streamInFlight.set(false);
+                }
+            });
+        }
+    }
+
+    private void clearState(SamplingState current) {
+        synchronized (current.publishLock) {
+            current.snapshot = null;
+            current.ivmHasRun = false;
+            current.streamHasRun = false;
+            current.pendingAgeTracker.clear();
+            current.lastIvmRefreshes = Collections.emptyList();
+            current.lastStreamHealths = Collections.emptyMap();
+        }
+    }
+
+    private void collectAndPublishIvm(SamplingState current, LongSupplier 
wallClockMs) {
+        try {
+            List<ChangelogMonitorSnapshot.IvmRefresh> collected = 
collectIvmRefreshes();
+            synchronized (current.publishLock) {
+                if (current != state) {
+                    return;
+                }
+                current.lastIvmRefreshes = collected;
+                current.snapshot = new ChangelogMonitorSnapshot(
+                        wallClockMs.getAsLong(), collected, new 
ArrayList<>(current.lastStreamHealths.values()));
+            }
+        } catch (RuntimeException e) {
+            LOG.warn("Failed to collect IVM refresh metrics; preserving prior 
IVM snapshot", e);
+        }
     }
 
-    ChangelogMonitorSnapshot collect() {
-        List<ChangelogMonitorSnapshot.IvmRefresh> refreshes = new 
ArrayList<>();
+    private void collectAndPublishStream(SamplingState current, LongSupplier 
wallClockMs, LongSupplier nanoClock) {
+        Map<Long, ChangelogMonitorSnapshot.StreamHealth> priorHealths;
+        synchronized (current.publishLock) {
+            if (current != state) {
+                return;
+            }
+            priorHealths = current.lastStreamHealths;
+        }
+        try {
+            List<ChangelogMonitorSnapshot.StreamHealth> streamHealths = 
streamCollector.collect(
+                    env, wallClockMs, nanoClock, current.pendingAgeTracker, 
priorHealths,
+                    sampled -> publishSingleStreamHealth(current, sampled, 
wallClockMs));
+            synchronized (current.publishLock) {
+                if (current != state) {
+                    return;
+                }
+                ChangelogMonitorSnapshot next = new ChangelogMonitorSnapshot(
+                        wallClockMs.getAsLong(), current.lastIvmRefreshes, 
streamHealths);
+                current.lastStreamHealths = next.streamHealthById();
+                current.snapshot = next;
+            }
+        } catch (RuntimeException e) {
+            LOG.warn("Failed to collect OLAP stream monitoring health; 
preserving prior stream snapshot", e);
+            handleStreamFailure(current);
+        }
+    }
+
+    private void publishSingleStreamHealth(SamplingState current,
+            ChangelogMonitorSnapshot.StreamHealth sampled, LongSupplier 
wallClockMs) {
+        synchronized (current.publishLock) {
+            if (current != state) {
+                return;
+            }
+            Map<Long, ChangelogMonitorSnapshot.StreamHealth> merged =
+                    new LinkedHashMap<>(current.lastStreamHealths);

Review Comment:
   Fixed in 2e4d9d846f7. ChangelogMonitor now buffers incrementally sampled 
StreamHealth entries and publishes in bounded batches (every 128 streams or 1s 
elapsed) rather than rebuilding the full snapshot on every individual stream, 
avoiding O(N^2) work on large clusters.



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