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


##########
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:
   Addressed the remaining multi-write interval case and stale caught-up 
retention in 5724df473df:
   - `StreamPendingAgeTracker` now records `caughtUpTimeMs` (in TSO 
physical-time domain) and monotonic `caughtUpObservedNanos` on caught-up 
observations. On a fresh `caughtUp -> lagging` transition, pending age anchors 
at `min(caughtUpTimeMs, endTsoTimeMs)` instead of `endTsoTimeMs` (both in 
`StreamPendingAgeTracker.Round.recordPartition()` and 
`OlapStreamMonitorCollector.evaluateLivePartition()`), so observing caught-up 
at 100s followed by writes at 101s and 114s and sampling at 115s reports 15s 
rather than understating to 1s.
   - `provenOldestWriteTimeMs` (actual observed write TSO) is tracked 
separately for `StreamResumabilityChecker.checkPartition()` so the conservative 
age anchor never causes false `TTL_EXPIRED` reports.
   - Caught-up observations are dropped on failed rounds 
(`retainPreviousForStream`), round-level exceptions 
(`invalidateCaughtUpObservations`), retained snapshot copies 
(`clearCaughtUpForRetainedStream`), and gated by monotonic freshness 
(`isFreshAt(nowNanos, expireNanos)`) in both background tracking and live SQL.
   - Added unit tests in `StreamPendingAgeTrackerTest`, 
`OlapStreamMonitorCollectorTest`, and `ChangelogMonitorTest`.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamResumabilityChecker.java:
##########
@@ -0,0 +1,171 @@
+// 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.OlapTable;
+import org.apache.doris.changelog.ChangelogUtils;
+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();
+    }
+
+    /**
+     * Evaluate whether one partition checkpoint can resume completely without 
losing changes.
+     * Even for scan types that clip an expired start TSO instead of throwing, 
clipping means
+     * incomplete resumption and reports {@link Status#CANNOT_RESUME}.
+     */
+    public static Result checkPartition(boolean hasChangelogTtl, Long 
cutoffTso, boolean hasData,
+            Long offset, Long historicalTso, long endTso, long 
streamCreateTimeMs, long oldestPendingTimeMs) {
+        // Initial-snapshot partitions read the base table directly and do not 
depend on changelog retention.
+        if (historicalTso != null) {
+            return Result.resumable();
+        }
+        if (!hasData) {
+            return Result.resumable();
+        }
+        if (!hasChangelogTtl) {
+            return Result.resumable();
+        }
+        if (cutoffTso == null) {
+            return Result.unknown(Reason.TSO_UNINITIALIZED);
+        }
+        if (offset != null && offset >= 0) {
+            Long startTso = TSOTimestamp.toExclusiveBound(offset);
+            if (ChangelogUtils.isStartTsoExpired(startTso, cutoffTso)) {
+                return Result.cannotResume(Reason.TTL_EXPIRED);
+            }
+            return Result.resumable();
+        }
+        // Partition has data but no real consumption baseline (newly added or 
empty at stream creation).
+        if (endTso >= 0 && endTso <= cutoffTso) {
+            return Result.cannotResume(Reason.TTL_EXPIRED);
+        }
+        long cutoffMs = TSOTimestamp.extractPhysicalTime(cutoffTso);
+        if (oldestPendingTimeMs > 0) {
+            return oldestPendingTimeMs <= cutoffMs

Review Comment:
   Addressed the promoted-temporary-partition / recovered-partition case in 
5724df473df:
   - Restored the explicit `offset != null && offset == -1L` empty-at-creation 
sentinel guard in `StreamResumabilityChecker.checkPartition()` so partitions 
with missing offsets (`offset == null`, such as promoted temporary partitions 
from `REPLACE PARTITION` or restored partitions from `RECOVER PARTITION`) stay 
`UNKNOWN (NO_BASELINE_OFFSET)` even when the stream itself was created within 
`changelog.ttl_seconds`.
   - Updated `StreamResumabilityCheckerTest` to verify `offset == null` stays 
`NO_BASELINE_OFFSET` while explicit `offset == -1L` within TTL reports 
`RESUMABLE`.



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