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


##########
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:
   Fixed in 50f089bb6e0. MetaServiceImpl::advance_tso_fence now rejects 
requests with INVALID_ARGUMENT when config::enable_check_commit_tso_fence is 
false (covered in MetaServiceTest::TsoFenceIsMonotonicAndRejectsStaleCommit), 
so FE never records a Cloud keep-alive watermark unless commit-side fence 
enforcement is active.



##########
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:
   Fixed in 50f089bb6e0. Added per-table TSOService.getLiveCommittedTsos() 
backed by TSOTransactionTracker's pendingTsosByTable index. 
keepAliveIdleCloudPartitions() advances the MetaService fence at the global 
committedTso (blocking pre-failover old-leader commits without fencing 
legitimate in-flight commits on this leader) and then renews each stream using 
its own base table's live safe TSO so stalled commits on unrelated tables do 
not starve idle streams. Covered in 
StreamKeepAliveTest#testCloudPerTableSafeTsoAndBatchIsolationAndMinTtlGuard.



##########
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:
   Fixed in 50f089bb6e0. When a multi-stream Cloud getReadStates batch fails, 
keepAliveCloudBatch now isolates per stream (and refreshes a single stream's 
partition snapshot once if a partition was concurrently dropped) so concurrent 
DDL on one stream never skips healthy sibling streams. Covered in 
StreamKeepAliveTest#testCloudPerTableSafeTsoAndBatchIsolationAndMinTtlGuard.



##########
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:
   Fixed in 50f089bb6e0. Made the minimum supported TTL explicit 
(TableStreamManager.MIN_KEEP_ALIVE_TTL_SECONDS = 2) and documented in 
Config.stream_keepalive_interval_second that tables with changelog.ttl_seconds 
< 2 are below the 1s daemon granularity and skipped by keep-alive.



##########
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:
   Fixed in 50f089bb6e0. test_ivm_changelog_offset_expired.groovy now 
explicitly disables enable_stream_keepalive on the master FE for the duration 
of the suite (restoring it in finally) so the expiry regression is independent 
of the keep-alive daemon schedule.



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