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


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -284,16 +290,374 @@ private Optional<EditLogItem> 
cleanupStalePartitionOffsets(OlapTableStream strea
         return Optional.of(editLogItem);
     }
 
+    /**
+     * Records a keep-alive TSO for idle caught-up partitions of an OLAP table 
stream in shared-nothing mode so
+     * their offsets do not expire under {@code changelog.ttl_seconds} while 
no writes arrive. A partition qualifies
+     * when the base table enables {@code changelog.ttl_seconds}, the stream 
has a real consumed offset past the
+     * initial snapshot, no committed or visible write exists after that 
offset, and its effective offset is older
+     * than half the TTL.
+     */
+    public Optional<EditLogItem> keepAliveIdlePartitions(OlapTableStream 
stream) {
+        if (!stream.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because stream read 
lock is busy", stream.getName());
+            }
+            return Optional.empty();
+        }
+        OlapTable baseTable;
+        Map<Long, Long> offsets;
+        Map<Long, Long> effectiveOffsets = new HashMap<>();
+        try {
+            if (stream.isDisabled() || stream.isStale()) {
+                return Optional.empty();
+            }
+            baseTable = stream.getBaseTableNullable();
+            if (baseTable == null) {
+                return Optional.empty();
+            }
+            offsets = stream.getConsumedPartitionOffsets();
+            offsets.forEach((partitionId, offset) -> 
effectiveOffsets.put(partitionId,
+                    OlapTableStream.effectiveOffset(offset, 
stream.getKeepAlive(partitionId))));
+        } finally {
+            stream.readUnlock();
+        }
+        if (offsets.isEmpty()) {
+            return Optional.empty();
+        }
+        while (DebugPointUtil.getDebugParamOrDefault(
+                
"TableStreamManager.keepAliveIdlePartitions.blockBeforeBaseTableLock", -1L) == 
stream.getId()) {
+            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+        }
+        if (!baseTable.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because base table {} 
read lock is busy",
+                        stream.getName(), baseTable.getName());
+            }
+            return Optional.empty();
+        }
+        Map<Long, Long> keptAlive = new HashMap<>();
+        long keepAliveTso;
+        EditLogItem editLogItem;
+        try {
+            if (baseTable.isDropped || !baseTable.hasChangelogTtl()) {
+                return Optional.empty();
+            }
+            TSOService tsoService = Env.getCurrentEnv().getTSOService();
+            TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null 
: tsoService.getStatusSnapshot();
+            if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCurrentTso() <= 0) {
+                return Optional.empty();
+            }
+            // Under baseTable.readLock no new commit can allocate a TSO, and 
nextVersion == visibleVersion + 1
+            // proves no COMMITTED (unpublished) txn exists on the partition. 
Every future commit gets TSO > currentTso.
+            keepAliveTso = tsoStatus.getCurrentTso();
+            long renewCutoffTso = keepAliveRenewCutoffTso(keepAliveTso,
+                    baseTable.getChangelogConfig().getTtlSeconds());
+            Set<Long> idle = new HashSet<>();
+            for (Map.Entry<Long, Long> entry : offsets.entrySet()) {
+                Partition partition = baseTable.getPartition(entry.getKey());
+                long effectiveOffset = effectiveOffsets.get(entry.getKey());
+                if (partition != null && effectiveOffset <= renewCutoffTso && 
effectiveOffset < keepAliveTso
+                        && partition.getTso() <= entry.getValue()
+                        && partition.getNextVersion() == 
partition.getVisibleVersion() + 1) {
+                    idle.add(entry.getKey());
+                }
+            }
+            if (idle.isEmpty()) {
+                return Optional.empty();
+            }
+            if (!stream.tryWriteLockIfExist(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("skip keeping stream {} alive because it is busy 
or dropped", stream.getName());
+                }
+                return Optional.empty();
+            }
+            try {
+                if (stream.isDisabled() || stream.isStale()) {
+                    return Optional.empty();
+                }
+                for (Long partitionId : idle) {
+                    if 
(offsets.get(partitionId).equals(stream.getPartitionOffset(partitionId))) {
+                        keptAlive.put(partitionId, offsets.get(partitionId));
+                    }
+                }
+                if (keptAlive.isEmpty()) {
+                    return Optional.empty();
+                }
+                stream.unprotectedKeepAlive(keptAlive, keepAliveTso);
+                editLogItem = 
Env.getCurrentEnv().getEditLog().logTableStreamCleanup(
+                        TableStreamCleanupInfo.ofKeepAlive(new 
TableStreamCleanupInfo.PartitionKeepAliveEntry(
+                                stream.getDatabase().getId(), stream.getId(), 
keptAlive, keepAliveTso)));
+            } finally {
+                stream.writeUnlock();
+            }
+        } finally {
+            baseTable.readUnlock();
+        }
+        LOG.info("kept {} idle partition offsets of stream {}.{} ({}) alive up 
to tso {}",
+                keptAlive.size(), stream.getDatabase().getFullName(), 
stream.getName(), stream.getId(),
+                keepAliveTso);
+        return Optional.of(editLogItem);
+    }
+
+    private static long keepAliveRenewCutoffTso(long referenceTso, long 
ttlSeconds) {
+        return TSOTimestamp.calculateCutoff(referenceTso, ttlSeconds / 2);
+    }
+
+    /**
+     * Cloud-mode counterpart of {@link 
#keepAliveIdlePartitions(OlapTableStream)}: fences MetaService once at the
+     * committed TSO watermark before reading stream offsets in bounded 
batches, proving no future commit can land
+     * with {@code commitTso <= keepAliveTso}.
+     */
+    public List<EditLogItem> 
keepAliveIdleCloudPartitions(List<OlapTableStream> streams) {
+        return keepAliveIdleCloudPartitions(streams, 
CLOUD_KEEP_ALIVE_BATCH_PARTITIONS);
+    }
+
+    @VisibleForTesting
+    List<EditLogItem> keepAliveIdleCloudPartitions(List<OlapTableStream> 
streams, int batchPartitions) {
+        int maxBatch = Math.max(1, batchPartitions);
+        List<CloudKeepAliveSnapshot> snapshots = new ArrayList<>();
+        for (OlapTableStream stream : streams) {
+            snapshotForCloudKeepAlive(stream).ifPresent(snapshots::add);
+        }
+        if (snapshots.isEmpty()) {
+            return Collections.emptyList();
+        }
+        TSOService tsoService = Env.getCurrentEnv().getTSOService();
+        TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null : 
tsoService.getStatusSnapshot();
+        if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCommittedTso() <= 0) {
+            LOG.info("skip keeping stream offsets alive because the committed 
TSO is not available");
+            return Collections.emptyList();
+        }
+        long keepAliveTso = tsoStatus.getCommittedTso();
+        long fenceTso;
+        try {
+            fenceTso = 
Env.getCurrentEnv().getGlobalTransactionMgr().advanceTsoFence(keepAliveTso);
+        } catch (UserException e) {
+            LOG.warn("skip keeping stream offsets alive because MetaService 
cannot be fenced at tso {}",
+                    keepAliveTso, e);
+            return Collections.emptyList();
+        }
+        Preconditions.checkState(fenceTso >= keepAliveTso, "MetaService TSO 
fence must not regress");

Review Comment:
   [P1] Require MetaService to enforce the fence before treating it as a safe 
watermark. `advance_tso_fence` succeeds when the mutable 
`enable_check_commit_tso_fence` setting is false, and 
`TsoFenceIsMonotonicAndRejectsStaleCommit` exercises a commit accepted at that 
fence. After FE failover, the new allocator starts beyond the old TSO window. 
If an old leader's commit RPC is still pending in MetaService, this daemon can 
read the partition as caught up at C and record K before that RPC commits at T, 
where C < T <= K. A later stream read ending at U > K starts at K + 1 and 
commits the real offset U, permanently omitting the change at T. Require 
commit-side enforcement for as long as a recorded watermark can affect reads.



##########
fe/fe-common/src/main/java/org/apache/doris/common/Config.java:
##########
@@ -3401,6 +3401,20 @@ public void handle(Field field, String value) throws 
Exception {
             varType = VariableAnnotation.EXPERIMENTAL)
     public static int table_stream_partition_offset_cleanup_interval_second = 
3600;
 
+    @ConfField(mutable = true, masterOnly = true, description = "Whether FE 
keeps the offsets of idle OLAP table "
+            + "stream partitions from expiring with changelog.ttl_seconds, by 
recording a proven safe watermark "
+            + "when a caught-up partition has no change after its offset. When 
disabled, no new keep-alive TSO is "
+            + "recorded, and already recorded ones still count.",
+            varType = VariableAnnotation.EXPERIMENTAL)
+    public static boolean enable_stream_keepalive = true;

Review Comment:
   [P3] Keep the existing expiry regression independent of the daemon schedule. 
In `test_ivm_changelog_offset_expired.groovy`, the first case shortens the TTL 
to one second while its stream is caught up, sleeps for 1.5 seconds, then 
writes and expects strict refresh to fail. A keep-alive round near the end of 
that sleep can record a recent watermark and let the refresh succeed. Disable 
renewal for that test case or write an unconsumed change before aging out the 
offset.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -284,16 +290,374 @@ private Optional<EditLogItem> 
cleanupStalePartitionOffsets(OlapTableStream strea
         return Optional.of(editLogItem);
     }
 
+    /**
+     * Records a keep-alive TSO for idle caught-up partitions of an OLAP table 
stream in shared-nothing mode so
+     * their offsets do not expire under {@code changelog.ttl_seconds} while 
no writes arrive. A partition qualifies
+     * when the base table enables {@code changelog.ttl_seconds}, the stream 
has a real consumed offset past the
+     * initial snapshot, no committed or visible write exists after that 
offset, and its effective offset is older
+     * than half the TTL.
+     */
+    public Optional<EditLogItem> keepAliveIdlePartitions(OlapTableStream 
stream) {
+        if (!stream.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because stream read 
lock is busy", stream.getName());
+            }
+            return Optional.empty();
+        }
+        OlapTable baseTable;
+        Map<Long, Long> offsets;
+        Map<Long, Long> effectiveOffsets = new HashMap<>();
+        try {
+            if (stream.isDisabled() || stream.isStale()) {
+                return Optional.empty();
+            }
+            baseTable = stream.getBaseTableNullable();
+            if (baseTable == null) {
+                return Optional.empty();
+            }
+            offsets = stream.getConsumedPartitionOffsets();
+            offsets.forEach((partitionId, offset) -> 
effectiveOffsets.put(partitionId,
+                    OlapTableStream.effectiveOffset(offset, 
stream.getKeepAlive(partitionId))));
+        } finally {
+            stream.readUnlock();
+        }
+        if (offsets.isEmpty()) {
+            return Optional.empty();
+        }
+        while (DebugPointUtil.getDebugParamOrDefault(
+                
"TableStreamManager.keepAliveIdlePartitions.blockBeforeBaseTableLock", -1L) == 
stream.getId()) {
+            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+        }
+        if (!baseTable.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because base table {} 
read lock is busy",
+                        stream.getName(), baseTable.getName());
+            }
+            return Optional.empty();
+        }
+        Map<Long, Long> keptAlive = new HashMap<>();
+        long keepAliveTso;
+        EditLogItem editLogItem;
+        try {
+            if (baseTable.isDropped || !baseTable.hasChangelogTtl()) {
+                return Optional.empty();
+            }
+            TSOService tsoService = Env.getCurrentEnv().getTSOService();
+            TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null 
: tsoService.getStatusSnapshot();
+            if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCurrentTso() <= 0) {
+                return Optional.empty();
+            }
+            // Under baseTable.readLock no new commit can allocate a TSO, and 
nextVersion == visibleVersion + 1
+            // proves no COMMITTED (unpublished) txn exists on the partition. 
Every future commit gets TSO > currentTso.
+            keepAliveTso = tsoStatus.getCurrentTso();
+            long renewCutoffTso = keepAliveRenewCutoffTso(keepAliveTso,
+                    baseTable.getChangelogConfig().getTtlSeconds());
+            Set<Long> idle = new HashSet<>();
+            for (Map.Entry<Long, Long> entry : offsets.entrySet()) {
+                Partition partition = baseTable.getPartition(entry.getKey());
+                long effectiveOffset = effectiveOffsets.get(entry.getKey());
+                if (partition != null && effectiveOffset <= renewCutoffTso && 
effectiveOffset < keepAliveTso
+                        && partition.getTso() <= entry.getValue()
+                        && partition.getNextVersion() == 
partition.getVisibleVersion() + 1) {
+                    idle.add(entry.getKey());
+                }
+            }
+            if (idle.isEmpty()) {
+                return Optional.empty();
+            }
+            if (!stream.tryWriteLockIfExist(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("skip keeping stream {} alive because it is busy 
or dropped", stream.getName());
+                }
+                return Optional.empty();
+            }
+            try {
+                if (stream.isDisabled() || stream.isStale()) {
+                    return Optional.empty();
+                }
+                for (Long partitionId : idle) {
+                    if 
(offsets.get(partitionId).equals(stream.getPartitionOffset(partitionId))) {
+                        keptAlive.put(partitionId, offsets.get(partitionId));
+                    }
+                }
+                if (keptAlive.isEmpty()) {
+                    return Optional.empty();
+                }
+                stream.unprotectedKeepAlive(keptAlive, keepAliveTso);
+                editLogItem = 
Env.getCurrentEnv().getEditLog().logTableStreamCleanup(
+                        TableStreamCleanupInfo.ofKeepAlive(new 
TableStreamCleanupInfo.PartitionKeepAliveEntry(
+                                stream.getDatabase().getId(), stream.getId(), 
keptAlive, keepAliveTso)));
+            } finally {
+                stream.writeUnlock();
+            }
+        } finally {
+            baseTable.readUnlock();
+        }
+        LOG.info("kept {} idle partition offsets of stream {}.{} ({}) alive up 
to tso {}",
+                keptAlive.size(), stream.getDatabase().getFullName(), 
stream.getName(), stream.getId(),
+                keepAliveTso);
+        return Optional.of(editLogItem);
+    }
+
+    private static long keepAliveRenewCutoffTso(long referenceTso, long 
ttlSeconds) {
+        return TSOTimestamp.calculateCutoff(referenceTso, ttlSeconds / 2);
+    }
+
+    /**
+     * Cloud-mode counterpart of {@link 
#keepAliveIdlePartitions(OlapTableStream)}: fences MetaService once at the
+     * committed TSO watermark before reading stream offsets in bounded 
batches, proving no future commit can land
+     * with {@code commitTso <= keepAliveTso}.
+     */
+    public List<EditLogItem> 
keepAliveIdleCloudPartitions(List<OlapTableStream> streams) {
+        return keepAliveIdleCloudPartitions(streams, 
CLOUD_KEEP_ALIVE_BATCH_PARTITIONS);
+    }
+
+    @VisibleForTesting
+    List<EditLogItem> keepAliveIdleCloudPartitions(List<OlapTableStream> 
streams, int batchPartitions) {
+        int maxBatch = Math.max(1, batchPartitions);
+        List<CloudKeepAliveSnapshot> snapshots = new ArrayList<>();
+        for (OlapTableStream stream : streams) {
+            snapshotForCloudKeepAlive(stream).ifPresent(snapshots::add);
+        }
+        if (snapshots.isEmpty()) {
+            return Collections.emptyList();
+        }
+        TSOService tsoService = Env.getCurrentEnv().getTSOService();
+        TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null : 
tsoService.getStatusSnapshot();
+        if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCommittedTso() <= 0) {
+            LOG.info("skip keeping stream offsets alive because the committed 
TSO is not available");
+            return Collections.emptyList();
+        }
+        long keepAliveTso = tsoStatus.getCommittedTso();
+        long fenceTso;
+        try {
+            fenceTso = 
Env.getCurrentEnv().getGlobalTransactionMgr().advanceTsoFence(keepAliveTso);
+        } catch (UserException e) {
+            LOG.warn("skip keeping stream offsets alive because MetaService 
cannot be fenced at tso {}",
+                    keepAliveTso, e);
+            return Collections.emptyList();
+        }
+        Preconditions.checkState(fenceTso >= keepAliveTso, "MetaService TSO 
fence must not regress");
+        List<EditLogItem> editLogItems = new ArrayList<>();
+        List<CloudKeepAliveSnapshot> batch = new ArrayList<>();
+        int partitionsInBatch = 0;
+        for (CloudKeepAliveSnapshot snapshot : snapshots) {
+            if (snapshot.partitionIds.size() > maxBatch) {
+                if (!batch.isEmpty()) {
+                    keepAliveCloudBatch(batch, keepAliveTso, editLogItems);
+                    batch = new ArrayList<>();
+                    partitionsInBatch = 0;
+                }
+                Set<Long> slice = new LinkedHashSet<>(maxBatch);
+                for (Long partitionId : snapshot.partitionIds) {
+                    slice.add(partitionId);
+                    if (slice.size() == maxBatch) {
+                        
keepAliveCloudBatch(Collections.singletonList(snapshot.withPartitionIds(slice)),
+                                keepAliveTso, editLogItems);
+                        slice = new LinkedHashSet<>(maxBatch);
+                    }
+                }
+                if (!slice.isEmpty()) {
+                    
keepAliveCloudBatch(Collections.singletonList(snapshot.withPartitionIds(slice)),
+                            keepAliveTso, editLogItems);
+                }
+                continue;
+            }
+            if (!batch.isEmpty() && partitionsInBatch + 
snapshot.partitionIds.size() > maxBatch) {
+                keepAliveCloudBatch(batch, keepAliveTso, editLogItems);
+                batch = new ArrayList<>();
+                partitionsInBatch = 0;
+            }
+            batch.add(snapshot);
+            partitionsInBatch += snapshot.partitionIds.size();
+        }
+        if (!batch.isEmpty()) {
+            keepAliveCloudBatch(batch, keepAliveTso, editLogItems);
+        }
+        return editLogItems;
+    }
+
+    private Optional<CloudKeepAliveSnapshot> 
snapshotForCloudKeepAlive(OlapTableStream stream) {
+        if (!stream.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because stream read 
lock is busy", stream.getName());
+            }
+            return Optional.empty();
+        }
+        OlapTable baseTable;
+        Map<Long, OlapTableStream.PartitionKeepAlive> keepAlives;
+        try {
+            if (stream.isDisabled() || stream.isStale()) {
+                return Optional.empty();
+            }
+            baseTable = stream.getBaseTableNullable();
+            if (baseTable == null) {
+                return Optional.empty();
+            }
+            keepAlives = stream.getKeepAlives();
+        } finally {
+            stream.readUnlock();
+        }
+        if (!baseTable.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because base table {} 
read lock is busy",
+                        stream.getName(), baseTable.getName());
+            }
+            return Optional.empty();
+        }
+        try {
+            if (baseTable.isDropped || !baseTable.hasChangelogTtl() || 
baseTable.getPartitionIds().isEmpty()) {
+                return Optional.empty();
+            }
+            Cloud.TableStreamIdentityPB identity = 
Cloud.TableStreamIdentityPB.newBuilder()
+                    .setBaseDbId(stream.getBaseTableInfo().getDbId())
+                    .setBaseTableId(stream.getBaseTableInfo().getTableId())
+                    .setStreamDbId(stream.getDatabase().getId())
+                    .setStreamId(stream.getId())
+                    .build();
+            return Optional.of(new CloudKeepAliveSnapshot(stream, identity,
+                    new LinkedHashSet<>(baseTable.getPartitionIds()), 
baseTable.getChangelogConfig().getTtlSeconds(),
+                    keepAlives));
+        } finally {
+            baseTable.readUnlock();
+        }
+    }
+
+    private void keepAliveCloudBatch(List<CloudKeepAliveSnapshot> batch, long 
keepAliveTso,
+            List<EditLogItem> editLogItems) {
+        while (batch.stream().anyMatch(snapshot -> snapshot.stream.getId() == 
DebugPointUtil.getDebugParamOrDefault(
+                
"TableStreamManager.keepAliveIdleCloudPartitions.blockBeforeReadStates", -1L))) 
{
+            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+        }
+        Map<Cloud.TableStreamIdentityPB, Set<Long>> requestedPartitions = new 
LinkedHashMap<>();
+        batch.forEach(snapshot -> requestedPartitions.put(snapshot.identity, 
snapshot.partitionIds));
+        Map<Cloud.TableStreamIdentityPB, Map<Long, 
Cloud.TableStreamPartitionReadStatePB>> readStates;
+        try {
+            readStates = 
CloudTableStreamReadStateHelper.getReadStates(requestedPartitions);
+        } catch (UserException e) {
+            LOG.warn("skip keeping {} streams alive because their Cloud read 
states are unavailable",
+                    batch.size(), e);
+            return;

Review Comment:
   [P2] Isolate invalidated cloud bindings so healthy streams can still renew. 
If one stream or partition is dropped between the FE snapshot and this RPC, 
MetaService rejects the entire request when that binding is being recycled or 
its version is missing. Returning here skips every other binding in the batch, 
potentially up to 10,000 partition entries. If those streams miss their renewal 
window, their next strict read can fail. Refresh and retry or split 
invalid-binding failures so concurrent DDL only skips the affected entries.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -284,16 +290,374 @@ private Optional<EditLogItem> 
cleanupStalePartitionOffsets(OlapTableStream strea
         return Optional.of(editLogItem);
     }
 
+    /**
+     * Records a keep-alive TSO for idle caught-up partitions of an OLAP table 
stream in shared-nothing mode so
+     * their offsets do not expire under {@code changelog.ttl_seconds} while 
no writes arrive. A partition qualifies
+     * when the base table enables {@code changelog.ttl_seconds}, the stream 
has a real consumed offset past the
+     * initial snapshot, no committed or visible write exists after that 
offset, and its effective offset is older
+     * than half the TTL.
+     */
+    public Optional<EditLogItem> keepAliveIdlePartitions(OlapTableStream 
stream) {
+        if (!stream.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because stream read 
lock is busy", stream.getName());
+            }
+            return Optional.empty();
+        }
+        OlapTable baseTable;
+        Map<Long, Long> offsets;
+        Map<Long, Long> effectiveOffsets = new HashMap<>();
+        try {
+            if (stream.isDisabled() || stream.isStale()) {
+                return Optional.empty();
+            }
+            baseTable = stream.getBaseTableNullable();
+            if (baseTable == null) {
+                return Optional.empty();
+            }
+            offsets = stream.getConsumedPartitionOffsets();
+            offsets.forEach((partitionId, offset) -> 
effectiveOffsets.put(partitionId,
+                    OlapTableStream.effectiveOffset(offset, 
stream.getKeepAlive(partitionId))));
+        } finally {
+            stream.readUnlock();
+        }
+        if (offsets.isEmpty()) {
+            return Optional.empty();
+        }
+        while (DebugPointUtil.getDebugParamOrDefault(
+                
"TableStreamManager.keepAliveIdlePartitions.blockBeforeBaseTableLock", -1L) == 
stream.getId()) {
+            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+        }
+        if (!baseTable.tryReadLock(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("skip keeping stream {} alive because base table {} 
read lock is busy",
+                        stream.getName(), baseTable.getName());
+            }
+            return Optional.empty();
+        }
+        Map<Long, Long> keptAlive = new HashMap<>();
+        long keepAliveTso;
+        EditLogItem editLogItem;
+        try {
+            if (baseTable.isDropped || !baseTable.hasChangelogTtl()) {
+                return Optional.empty();
+            }
+            TSOService tsoService = Env.getCurrentEnv().getTSOService();
+            TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null 
: tsoService.getStatusSnapshot();
+            if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCurrentTso() <= 0) {
+                return Optional.empty();
+            }
+            // Under baseTable.readLock no new commit can allocate a TSO, and 
nextVersion == visibleVersion + 1
+            // proves no COMMITTED (unpublished) txn exists on the partition. 
Every future commit gets TSO > currentTso.
+            keepAliveTso = tsoStatus.getCurrentTso();
+            long renewCutoffTso = keepAliveRenewCutoffTso(keepAliveTso,
+                    baseTable.getChangelogConfig().getTtlSeconds());
+            Set<Long> idle = new HashSet<>();
+            for (Map.Entry<Long, Long> entry : offsets.entrySet()) {
+                Partition partition = baseTable.getPartition(entry.getKey());
+                long effectiveOffset = effectiveOffsets.get(entry.getKey());
+                if (partition != null && effectiveOffset <= renewCutoffTso && 
effectiveOffset < keepAliveTso
+                        && partition.getTso() <= entry.getValue()
+                        && partition.getNextVersion() == 
partition.getVisibleVersion() + 1) {
+                    idle.add(entry.getKey());
+                }
+            }
+            if (idle.isEmpty()) {
+                return Optional.empty();
+            }
+            if (!stream.tryWriteLockIfExist(Table.TRY_LOCK_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("skip keeping stream {} alive because it is busy 
or dropped", stream.getName());
+                }
+                return Optional.empty();
+            }
+            try {
+                if (stream.isDisabled() || stream.isStale()) {
+                    return Optional.empty();
+                }
+                for (Long partitionId : idle) {
+                    if 
(offsets.get(partitionId).equals(stream.getPartitionOffset(partitionId))) {
+                        keptAlive.put(partitionId, offsets.get(partitionId));
+                    }
+                }
+                if (keptAlive.isEmpty()) {
+                    return Optional.empty();
+                }
+                stream.unprotectedKeepAlive(keptAlive, keepAliveTso);
+                editLogItem = 
Env.getCurrentEnv().getEditLog().logTableStreamCleanup(
+                        TableStreamCleanupInfo.ofKeepAlive(new 
TableStreamCleanupInfo.PartitionKeepAliveEntry(
+                                stream.getDatabase().getId(), stream.getId(), 
keptAlive, keepAliveTso)));
+            } finally {
+                stream.writeUnlock();
+            }
+        } finally {
+            baseTable.readUnlock();
+        }
+        LOG.info("kept {} idle partition offsets of stream {}.{} ({}) alive up 
to tso {}",
+                keptAlive.size(), stream.getDatabase().getFullName(), 
stream.getName(), stream.getId(),
+                keepAliveTso);
+        return Optional.of(editLogItem);
+    }
+
+    private static long keepAliveRenewCutoffTso(long referenceTso, long 
ttlSeconds) {
+        return TSOTimestamp.calculateCutoff(referenceTso, ttlSeconds / 2);
+    }
+
+    /**
+     * Cloud-mode counterpart of {@link 
#keepAliveIdlePartitions(OlapTableStream)}: fences MetaService once at the
+     * committed TSO watermark before reading stream offsets in bounded 
batches, proving no future commit can land
+     * with {@code commitTso <= keepAliveTso}.
+     */
+    public List<EditLogItem> 
keepAliveIdleCloudPartitions(List<OlapTableStream> streams) {
+        return keepAliveIdleCloudPartitions(streams, 
CLOUD_KEEP_ALIVE_BATCH_PARTITIONS);
+    }
+
+    @VisibleForTesting
+    List<EditLogItem> keepAliveIdleCloudPartitions(List<OlapTableStream> 
streams, int batchPartitions) {
+        int maxBatch = Math.max(1, batchPartitions);
+        List<CloudKeepAliveSnapshot> snapshots = new ArrayList<>();
+        for (OlapTableStream stream : streams) {
+            snapshotForCloudKeepAlive(stream).ifPresent(snapshots::add);
+        }
+        if (snapshots.isEmpty()) {
+            return Collections.emptyList();
+        }
+        TSOService tsoService = Env.getCurrentEnv().getTSOService();
+        TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null : 
tsoService.getStatusSnapshot();
+        if (tsoStatus == null || !tsoStatus.isInitialized() || 
tsoStatus.getCommittedTso() <= 0) {
+            LOG.info("skip keeping stream offsets alive because the committed 
TSO is not available");
+            return Collections.emptyList();
+        }
+        long keepAliveTso = tsoStatus.getCommittedTso();

Review Comment:
   [P2] Keep an unrelated pending commit from aging out a caught-up cloud 
stream. `TSOTransactionTracker.candidateCommittedTso` caps this global 
watermark at the oldest pending commit across all tables, while the planner 
calculates expiration from the advancing current TSO. If a commit RPC on a 
different changelog table stalls longer than a stream's configured TTL, later 
rounds cannot advance its watermark past that cap. A write to the stream's 
source before the first successful renewal makes it ineligible for renewal, so 
the next strict read fails even though the source was idle. Use a safe proof 
scoped to the source partitions and cover a stalled commit on an unrelated 
table.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/StreamKeepAliveDaemon.java:
##########
@@ -0,0 +1,108 @@
+// 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.Table;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.util.MasterDaemon;
+import org.apache.doris.persist.EditLog.EditLogItem;
+import org.apache.doris.tso.TSOService;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Keeps the offsets of idle caught-up partitions of OLAP table streams from 
expiring under
+ * {@code changelog.ttl_seconds}.
+ *
+ * <p>A stream's offset advances only when a consumer reads new changes, so an 
idle partition keeps its last
+ * consumed offset. Once idle longer than {@code changelog.ttl_seconds}, the 
next write would make a strict read
+ * treat the offset as expired even though no change occurred in the expired 
window. This daemon traverses all
+ * registered OLAP streams directly via {@link 
TableStreamManager#copyDbStreamMap()} and records a proven safe
+ * keep-alive watermark bound to the partition's current offset, without 
moving the offset or skipping any data.
+ */
+public class StreamKeepAliveDaemon extends MasterDaemon {
+    // Poll every second so dynamic changes to 
stream_keepalive_interval_second take effect immediately.
+    private static final long CHECK_INTERVAL_MS = 1000L;
+
+    // Only read and written by the daemon thread.
+    private long lastRoundMs = 0L;
+
+    public StreamKeepAliveDaemon() {
+        super("stream-keepalive", CHECK_INTERVAL_MS);
+    }
+
+    @Override
+    protected void runAfterCatalogReady() {
+        if (!Config.enable_table_stream || !Config.enable_stream_keepalive) {
+            return;
+        }
+        TSOService tsoService = Env.getCurrentEnv().getTSOService();
+        TSOService.TSOStatusSnapshot tsoStatus = tsoService == null ? null : 
tsoService.getStatusSnapshot();
+        if (tsoStatus == null || !tsoStatus.isInitialized()) {
+            return;
+        }
+        long now = System.currentTimeMillis();
+        long intervalMs = Math.max(1, Config.stream_keepalive_interval_second) 
* 1000L;

Review Comment:
   [P2] Make the minimum renewal cadence compatible with supported changelog 
TTLs. A table can set `changelog.ttl_seconds=1`, but the fastest setting here 
still sleeps at least a second between rounds, plus scan and journal time. A 
write can arrive after the latest watermark has expired and before the next 
check. The check then sees a lagging partition and cannot renew it, so a strict 
stream read can fail even with the fastest setting. Use a cadence below the 
TTLs being protected, or make the unsupported TTL range explicit and validate 
it.



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