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


##########
fe/fe-core/src/test/java/org/apache/doris/catalog/stream/CloudTableStreamConsumptionTest.java:
##########
@@ -202,12 +219,43 @@ public void 
testConsumptionViewReadsAuthoritativeCloudOffsets() throws Exception
             Assertions.assertEquals("100", 
rows.get(0).getColumnValue().get(4).getStringVal());
             Assertions.assertEquals("30", 
rows.get(0).getColumnValue().get(5).getStringVal());
             Assertions.assertEquals(999, 
rows.get(0).getColumnValue().get(6).getLongVal());
+            Assertions.assertEquals(7, rows.get(0).getColumnValue().size());
 
-            result = 
MetadataGenerator.getSchemaTableData(newStreamIdConsumptionRequest(secondStream.getId()));
+            // Request with columns_name returns the extended monitoring 
columns as well.
+            TFetchSchemaTableDataRequest monitoringRequest = 
newConsumptionRequest("test_cloud_stream_consumption", "s1");
+            monitoringRequest.getSchemaTableParams().setColumnsName(List.of(
+                    "DB_NAME", "STREAM_NAME", "STREAM_ID", "UNIT", 
"CONSUMPTION_STATUS", "LAG",
+                    "LAST_CONSUMPTION_TIME", "PENDING_AGE_SECONDS", 
"CAN_RESUME", "UNRESUMABLE_REASON"));
+            TFetchSchemaTableDataResult monitoringResult = 
MetadataGenerator.getSchemaTableData(monitoringRequest);
+            Assertions.assertEquals(TStatusCode.OK, 
monitoringResult.getStatus().getStatusCode());
+            Assertions.assertEquals(1, monitoringResult.getDataBatchSize());
+            TRow monitoringRow = monitoringResult.getDataBatch().get(0);
+            Assertions.assertEquals(10, monitoringRow.getColumnValue().size());
+            // Cold lag without prior monitor snapshot reports unknown 
sentinel (-1.0).
+            Assertions.assertEquals(-1.0, 
monitoringRow.getColumnValue().get(7).getDoubleVal(), 1e-6);
+            // Synthetic offsetTso=100 predates the default 1-day 
changelog.ttl_seconds cutoff.
+            Assertions.assertEquals(0, 
monitoringRow.getColumnValue().get(8).getIntVal());
+            Assertions.assertEquals("TTL_EXPIRED", 
monitoringRow.getColumnValue().get(9).getStringVal());
+
+            TFetchSchemaTableDataRequest s2Request = 
newStreamIdConsumptionRequest(secondStream.getId());
+            s2Request.getSchemaTableParams().setColumnsName(List.of(
+                    "DB_NAME", "STREAM_NAME", "STREAM_ID", "UNIT", 
"CONSUMPTION_STATUS", "LAG",
+                    "LAST_CONSUMPTION_TIME", "PENDING_AGE_SECONDS", 
"CAN_RESUME", "UNRESUMABLE_REASON"));
+            result = MetadataGenerator.getSchemaTableData(s2Request);
             Assertions.assertEquals(TStatusCode.OK, 
result.getStatus().getStatusCode());
             Assertions.assertEquals(2, result.getDataBatchSize());
-            Assertions.assertTrue(result.getDataBatch().stream()
+            List<TRow> s2Rows = new ArrayList<>(result.getDataBatch());
+            s2Rows.sort(Comparator.comparing(row -> 
row.getColumnValue().get(3).getStringVal()));
+            Assertions.assertTrue(s2Rows.stream()
                     .allMatch(row -> row.getColumnValue().get(2).getLongVal() 
== secondStream.getId()));
+            // p1 is INITIAL_SNAPSHOT_PENDING with a 15s-old real TSO -> 
strictly positive pending age, RESUMABLE.
+            
Assertions.assertTrue(s2Rows.get(0).getColumnValue().get(7).getDoubleVal() > 
0.0);
+            Assertions.assertEquals(1, 
s2Rows.get(0).getColumnValue().get(8).getIntVal());

Review Comment:
   Fixed in 5c5fb41b4d3: updated all three `CAN_RESUME` assertions in 
`CloudTableStreamConsumptionTest` to assert `isSetLongVal()` and read 
`getLongVal()`, and ran `CloudTableStreamConsumptionTest` locally (1/1 passed).



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/OlapStreamMonitorCollector.java:
##########
@@ -0,0 +1,624 @@
+// 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.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.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.function.LongSupplier;
+
+/**
+ * Batch-samples registered OLAP table streams for {@link 
org.apache.doris.changelog.ChangelogMonitor}.
+ *
+ * <p>Table read locks are always acquired in ascending {@code Table::getId} 
order with a bounded timeout
+ * so background monitoring can never deadlock against multi-table write-lock 
paths such as {@code DROP DATABASE}.
+ * In cloud mode, partition identities are copied under short read locks and 
authoritative states are fetched
+ * in bounded lock-free batch RPCs (chunked across streams and within wide 
streams), isolating per-stream logic
+ * errors without amplifying MetaService transport/timeout, server-side 
rate-limit, or FDB transaction outages.
+ */
+public final class OlapStreamMonitorCollector {
+    private static final Logger LOG = 
LogManager.getLogger(OlapStreamMonitorCollector.class);
+    static final long LOCK_TIMEOUT_MS = 500L;
+    private static final long MAX_FALLBACK_BUDGET_MS = 10_000L;
+
+    private static final Set<Cloud.MetaServiceCode> SERVICE_OUTAGE_CODES = 
EnumSet.of(
+            Cloud.MetaServiceCode.MAX_QPS_LIMIT,
+            Cloud.MetaServiceCode.MS_TOO_BUSY,
+            Cloud.MetaServiceCode.KV_TXN_CREATE_ERR,
+            Cloud.MetaServiceCode.KV_TXN_GET_ERR,
+            Cloud.MetaServiceCode.KV_TXN_COMMIT_ERR,
+            Cloud.MetaServiceCode.KV_TXN_CONFLICT,
+            Cloud.MetaServiceCode.KV_TXN_STORE_GET_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_STORE_COMMIT_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_STORE_CREATE_RETRYABLE,
+            Cloud.MetaServiceCode.KV_TXN_TOO_OLD,
+            Cloud.MetaServiceCode.KV_TXN_MAYBE_COMMITTED,
+            Cloud.MetaServiceCode.KV_TXN_CONFLICT_RETRY_EXCEEDED_MAX_TIMES);
+
+    private OlapStreamMonitorCollector() {
+    }
+
+    @FunctionalInterface
+    public interface CloudStateFetcher {
+        Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> fetch(
+                Map<Cloud.TableStreamIdentityPB, Set<Long>> 
requestedPartitions) throws UserException;
+    }
+
+    public static List<StreamHealth> collect(Env env, LongSupplier 
wallClockMs, LongSupplier nanoClock,
+            StreamPendingAgeTracker tracker, Map<Long, StreamHealth> 
previousByStreamId) {
+        return collect(env, wallClockMs, nanoClock, tracker, 
previousByStreamId,
+                CloudTableStreamReadStateHelper::getReadStates);
+    }
+
+    public static List<StreamHealth> collect(Env env, long sampleTimeMs, 
StreamPendingAgeTracker tracker,
+            Map<Long, StreamHealth> previousByStreamId, CloudStateFetcher 
cloudFetcher) {
+        long sampleTimeNanos = TimeUnit.MILLISECONDS.toNanos(sampleTimeMs);
+        return collect(env, () -> sampleTimeMs, () -> sampleTimeNanos, 
tracker, previousByStreamId, cloudFetcher);
+    }
+
+    public static List<StreamHealth> collect(Env env, LongSupplier 
wallClockMs, LongSupplier nanoClock,
+            StreamPendingAgeTracker tracker, Map<Long, StreamHealth> 
previousByStreamId,
+            CloudStateFetcher cloudFetcher) {
+        TableStreamManager manager = env.getTableStreamManager();
+        if (manager == null) {
+            return List.of();
+        }
+        Map<Long, Set<Long>> dbStreamMap = manager.copyDbStreamMap();
+        if (dbStreamMap.isEmpty()) {
+            tracker.clear();
+            return List.of();
+        }
+        Long referenceTso = getReferenceTso(env);

Review Comment:
   Closed the remaining local live-SQL and multi-slice Cloud paths in 
5c5fb41b4d3:
   - `TableStreamManager.fillLocalStreamConsumptionValuesMetadataResult()` now 
refreshes `referenceTso`, `referenceTimeMs`, `nowNanos`, and `monitorSnapshot` 
immediately after each stream releases its metadata read locks, and 
`LocalStreamConsumptionSnapshot.appendRows()` derives `cutoffTso` from that 
post-lock `referenceTso`.
   - Wide multi-slice Cloud streams now retain per-slice pre/post-RPC TSO and 
clock samples (`PartitionFetchSample`) instead of merging slices with 
`Math.max(referenceTso)`, and compute stream-level earliest-slice freshness via 
wrap-safe signed `nanoTime` subtraction.



##########
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:
   Closed the commit-before-visibility and Cloud RPC-latency gaps in 
5c5fb41b4d3:
   - **Local mode**: under `baseTable.readLock` (where no transaction can 
allocate a new `commitTSO` or publish a `COMMITTED` transaction), 
`OlapStreamMonitorCollector.sampleLocalStream()` checks 
`GlobalTransactionMgr.getCommittedTransactions()` for `baseTable` (matching 
canonical `Table -> DbTxnMgr/TSOService` lock order) and captures 
`caughtUpRefTso` only when zero unpublished `COMMITTED` transactions exist. If 
an unpublished transaction is present (or TSO is uninitialized), 
`caughtUpTsoTimeMs` is `0` so caught-up anchoring is suppressed rather than 
understating an unpublished TSO.
   - **Cloud mode**: `fetchCloudChunk()` captures `preRefTso`/`preNanos` before 
sending the MetaService RPC and uses `preRefTso` for `caughtUpTsoTimeMs` 
(strictly bounding commits before MetaService read latency) while using 
`postRefTso` for current age and TTL cutoffs.
   - Added unit tests in `OlapStreamMonitorCollectorTest` and 
`StreamPendingAgeTrackerTest` covering unpublished committed transactions, 
uninitialized TSO, and Cloud pre-RPC caught-up bounds.



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