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


##########
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:
   [P2] Persist a known zero cleanup cutoff for altered tables
   
   A new table's first TTL shortening increments `configVersion` and leaves 
`priorCleanupCutoffTso=0`. The leader keeps zero in the cached config, but this 
method omits the marker from both the journal and the image. 
`TableProperty.buildBinlogConfig()` then interprets the absent marker and 
positive generation as legacy unknown. On failover or reload, a lagging 
checkpoint that is still within the current TTL changes from `RESUMABLE` to 
`UNKNOWN` even though no earlier retention extension occurred. Persist an 
explicit zero for a known clean history when the config has a generation, and 
check the result after replay.



##########
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:
   [P2] Verify replica TTL generations before recording a cleanup cutoff
   
   `updatePartitionProperties()` snapshots replica targets and releases the 
table lock before sending its updates. A shared-nothing changelog repair can 
add a replica after that snapshot, clone the source's old TTL header before the 
update reaches that source, and load the old header on the new replica. The 
final partition-ID check still passes. If a 30s TTL is extended at t=100s, this 
records a cutoff of t=70s, but the missed replica can compact at t=115s and 
remove a pending t=80s change after a t=75s checkpoint. The checker can then 
report `RESUMABLE` despite the missing change. Confirm the relevant replicas 
have adopted the extended policy before using a finite cutoff, or record 
unknown when replica coverage cannot be established.



##########
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:
   [P2] Avoid rebuilding the full snapshot for every stream sample
   
   Each callback copies the complete stream map while holding `publishLock`, 
then `ChangelogMonitorSnapshot` copies the list and rebuilds the full ID index. 
A steady-state round over 10,000 streams visits about 100 million entries in 
each of the two map rebuilds, plus the list copies. This can exhaust the 
default freshness window, and IVM publication also takes this lock. Keep 
incremental updates cheap by publishing a bounded batch at a time or 
materializing the full snapshot once for readers.



##########
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:
   [P2] Preserve wildcard queries while an older master serves upgraded FEs
   
   Even after all BEs are upgraded, `SELECT *` planned on an upgraded readable 
follower expands to ten slots, and this BE sends those names to the master FE. 
An older master still has only seven names in 
`MetadataGenerator.filterColumns()`, so it returns `INTERNAL_ERROR` on a 
nonempty result and the scanner returns that error. This can happen in the 
mixed-FE phase of a BE-first rollout. Gate wildcard expansion by cluster 
capability or provide a legacy/null fallback for this request, and cover the 
new follower/new BE/old master combination.



##########
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:
   [P2] Identify IVM-owned streams before applying the base-table fallback
   
   `CreateStreamInfo.validate()` accepts an ordinary stream named 
`__doris_ivm_stream_example`. Create that stream on a changelog-enabled 
duplicate-key table with an empty partition, then write to the partition and 
let the change expire. The diagnostic sees the prefix and the `-1` offset and 
returns `CAN_RESUME=1`. A normal `LogicalOlapTableStreamScan` for that stream 
goes through `makeIncrementalScanFromChangelog()` and clips the expired change 
because `StatementContext.isIvmMTMVRewrite()` is false. Derive IVM status from 
verified MV ownership or persisted stream metadata, and cover an ordinary 
stream with the prefix.



##########
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:
   [P2] Revalidate Cloud SQL's TTL metadata after the offset RPC
   
   `fillCloudStreamConsumptionValuesMetadataResult()` copies the TTL under the 
FE table lock, then fetches current offsets independently from MetaService. 
Suppose a MIN_DELTA stream is caught up at t=80s when the query copies a 120s 
TTL at t=100s. An ALTER lowers TTL to 30s at t=110s, then a write becomes 
visible at t=120s. If the offset RPC observes that write and returns at t=160s, 
this code uses the copied TTL and computes a cutoff of t=40s, so SQL says 
`CAN_RESUME=1`. The read would have rejected the checkpoint at every point when 
that write was pending. Revalidate the sampled TTL generation with the offset 
result and retry or report unknown if it changed.



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