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


##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -284,16 +290,449 @@ 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.
+     */
+    // The keep-alive daemon has a 1-second minimum cadence and renews when 
less than half of
+    // changelog.ttl_seconds remains, so sub-2s TTLs cannot be reliably 
protected and are skipped.
+    static final long MIN_KEEP_ALIVE_TTL_SECONDS = 2L;
+    private static final long MAX_CLOUD_ISOLATION_BUDGET_NANOS = 
TimeUnit.SECONDS.toNanos(5);
+
+    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()
+                    || baseTable.getChangelogConfig().getTtlSeconds() < 
MIN_KEEP_ALIVE_TTL_SECONDS) {
+                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();
+        }
+        // Advance the MetaService TSO fence at the global committed TSO so 
every pre-failover
+        // old-leader commit is rejected without fencing legitimate in-flight 
commits on this leader.
+        long committedTso = tsoStatus.getCommittedTso();
+        long fenceTso;
+        try {
+            fenceTso = 
Env.getCurrentEnv().getGlobalTransactionMgr().advanceTsoFence(committedTso);
+        } catch (UserException e) {
+            LOG.warn("skip keeping stream offsets alive because MetaService 
cannot be fenced at tso {}",
+                    committedTso, e);
+            return Collections.emptyList();
+        }
+        Preconditions.checkState(fenceTso >= committedTso, "MetaService TSO 
fence must not regress");
+        // Compute per-base-table safe watermarks AFTER fencing so stalled 
commits on unrelated
+        // tables do not cap or starve idle streams on other base tables.
+        Set<Pair<Long, Long>> baseDbTables = new HashSet<>();
+        for (CloudKeepAliveSnapshot snapshot : snapshots) {
+            baseDbTables.add(Pair.of(snapshot.identity.getBaseDbId(), 
snapshot.identity.getBaseTableId()));
+        }
+        Map<Pair<Long, Long>, Long> liveCommittedTsos = 
tsoService.getLiveCommittedTsos(baseDbTables);
+        Map<Pair<Long, Long>, Long> perTableKeepAliveTsos = new 
HashMap<>(baseDbTables.size() * 2);
+        for (Pair<Long, Long> dbTable : baseDbTables) {
+            Long tableSafeTso = liveCommittedTsos == null ? null : 
liveCommittedTsos.get(dbTable);
+            long safeTso = (tableSafeTso != null && tableSafeTso > 0)
+                    ? Math.max(committedTso, tableSafeTso) : committedTso;
+            perTableKeepAliveTsos.put(dbTable, safeTso);
+        }
+        List<EditLogItem> editLogItems = new ArrayList<>();
+        long[] isolationSpentNanos = {0L};
+        List<CloudKeepAliveSnapshot> batch = new ArrayList<>();
+        int partitionsInBatch = 0;
+        for (CloudKeepAliveSnapshot snapshot : snapshots) {
+            if (snapshot.partitionIds.size() > maxBatch) {
+                if (!batch.isEmpty()) {
+                    keepAliveCloudBatch(batch, perTableKeepAliveTsos, 
editLogItems, true, isolationSpentNanos);
+                    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)),
+                                perTableKeepAliveTsos, editLogItems, true, 
isolationSpentNanos);
+                        slice = new LinkedHashSet<>(maxBatch);
+                    }
+                }
+                if (!slice.isEmpty()) {
+                    
keepAliveCloudBatch(Collections.singletonList(snapshot.withPartitionIds(slice)),
+                            perTableKeepAliveTsos, editLogItems, true, 
isolationSpentNanos);
+                }
+                continue;
+            }
+            if (!batch.isEmpty() && partitionsInBatch + 
snapshot.partitionIds.size() > maxBatch) {
+                keepAliveCloudBatch(batch, perTableKeepAliveTsos, 
editLogItems, true, isolationSpentNanos);
+                batch = new ArrayList<>();
+                partitionsInBatch = 0;
+            }
+            batch.add(snapshot);
+            partitionsInBatch += snapshot.partitionIds.size();
+        }
+        if (!batch.isEmpty()) {
+            keepAliveCloudBatch(batch, perTableKeepAliveTsos, editLogItems, 
true, isolationSpentNanos);
+        }
+        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.getChangelogConfig().getTtlSeconds() < 
MIN_KEEP_ALIVE_TTL_SECONDS
+                    || 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 static boolean isIsolatableCloudReadFailure(UserException e) {
+        if (!(e instanceof 
CloudTableStreamReadStateHelper.MetaServiceStatusException statusEx)) {
+            return false;
+        }
+        Cloud.MetaServiceCode code = statusEx.getCode();
+        return code == Cloud.MetaServiceCode.INVALID_ARGUMENT
+                || code == Cloud.MetaServiceCode.VERSION_NOT_FOUND
+                || code == Cloud.MetaServiceCode.TABLET_NOT_FOUND;
+    }
+
+    private void keepAliveCloudBatch(List<CloudKeepAliveSnapshot> batch,
+            Map<Pair<Long, Long>, Long> perTableKeepAliveTsos,
+            List<EditLogItem> editLogItems, boolean allowRetry, long[] 
isolationSpentNanos) {
+        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);

Review Comment:
   [P2] Keep unrelated lazy publication from blocking idle stream renewal. 
These batches request every partition, including active ones. 
`get_table_stream_offset` (`meta_service_table_stream.cpp`) waits for all 
pending lazy transactions across the bindings and rereads the whole snapshot 
before returning; `TxnLazyCommitTask::wait` has no terminal timeout. Ordinary 
source writes with enough rowsets can take that path even without consuming a 
stream. A slow publication on table A can therefore delay or time out the read 
for caught-up table B, despite the new per-table TSO watermark. If B receives a 
change after its old watermark ages out, it is no longer eligible for renewal 
and the next strict read fails. Use a maintenance read that reports/skips 
pending partitions without draining unrelated publications, or otherwise 
isolate them with a bounded renewal deadline.



##########
regression-test/suites/table_stream_p0/test_stream_keepalive.groovy:
##########
@@ -0,0 +1,136 @@
+// 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.
+
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_stream_keepalive", "nonConcurrent") {
+    sql "SET enable_materialized_view_rewrite = false"
+    sql "SET enable_dml_materialized_view_rewrite = false"
+
+    def oldIntervalRows = master_sql_return_maparray(
+            "ADMIN SHOW FRONTEND CONFIG LIKE 
'%stream_keepalive_interval_second'")
+    String oldInterval = oldIntervalRows[0].Value.toString()
+
+    sql "DROP MATERIALIZED VIEW IF EXISTS stream_keepalive_mv"
+    sql "DROP STREAM IF EXISTS stream_keepalive_s"
+    sql "DROP TABLE IF EXISTS stream_keepalive_sink"
+    sql "DROP TABLE IF EXISTS stream_keepalive_base"
+
+    try {
+        master_sql "ADMIN SET FRONTEND CONFIG 
('stream_keepalive_interval_second' = '1')"
+
+        sql """
+            CREATE TABLE stream_keepalive_base (
+                dt DATE NOT NULL,
+                id BIGINT NOT NULL,
+                v INT
+            )
+            UNIQUE KEY(dt, id)
+            PARTITION BY RANGE(dt) (
+                PARTITION p1 VALUES [('2026-01-01'), ('2026-02-01')),
+                PARTITION p2 VALUES [('2026-02-01'), ('2026-03-01'))
+            )
+            DISTRIBUTED BY HASH(id) BUCKETS 1
+            PROPERTIES (
+                "replication_num" = "1",
+                "enable_unique_key_merge_on_write" = "true",
+                "changelog.enable" = "true",
+                "changelog.need_historical_value" = "true",
+                "changelog.ttl_seconds" = "6"
+            )
+        """
+        sql """
+            CREATE TABLE stream_keepalive_sink (
+                dt DATE NOT NULL,
+                id BIGINT NOT NULL,
+                v INT
+            )
+            DUPLICATE KEY(dt, id)
+            DISTRIBUTED BY HASH(id) BUCKETS 1
+            PROPERTIES ("replication_num" = "1")
+        """
+
+        sql """
+            INSERT INTO stream_keepalive_base VALUES
+                ('2026-01-10', 1, 10),
+                ('2026-02-10', 2, 20)
+        """
+        sql """
+            CREATE STREAM stream_keepalive_s ON TABLE stream_keepalive_base
+            PROPERTIES ("show_initial_rows" = "false")
+        """
+        sql """
+            CREATE MATERIALIZED VIEW stream_keepalive_mv
+            BUILD DEFERRED REFRESH INCREMENTAL ON MANUAL
+            PARTITION BY (dt)
+            DISTRIBUTED BY HASH(dt) BUCKETS 1
+            PROPERTIES ("replication_num" = "1")
+            AS SELECT dt, SUM(v) AS sum_v, COUNT(*) AS cnt
+               FROM stream_keepalive_base
+               GROUP BY dt
+        """
+
+        // Initial COMPLETE build establishes the IVM stream offsets on both 
partitions.
+        sql "REFRESH MATERIALIZED VIEW stream_keepalive_mv COMPLETE"
+        def waitForTask = { String prevTaskId ->
+            def taskResult
+            Awaitility.await().atMost(180, SECONDS).pollInterval(1, 
SECONDS).until({
+                taskResult = sql_return_maparray("""
+                    SELECT TaskId, Status, IvmRefreshMethod FROM 
tasks('type'='mv')
+                    WHERE MvDatabaseName = '${context.dbName}' AND MvName = 
'stream_keepalive_mv'
+                    ORDER BY CreateTime DESC, TaskId DESC LIMIT 1
+                """)
+                return !taskResult.isEmpty()
+                        && taskResult[0].TaskId.toString() != prevTaskId
+                        && taskResult[0].Status.toString() != 'PENDING'
+                        && taskResult[0].Status.toString() != 'RUNNING'
+            })
+            return taskResult[0]
+        }
+        def t0 = waitForTask(null)
+        assertEquals("SUCCESS", t0.Status.toString())
+
+        // Stay completely idle past changelog.ttl_seconds=6 so 
StreamKeepAliveDaemon renews the safe watermark.
+        sleep(8000)

Review Comment:
   [P3] Make the renewal regression independent of cluster config and 
scheduling. The suite only sets the interval, so it fails when the existing 
`enable_stream_keepalive` setting is false. The fixed sleep also assumes 
renewal has happened; after the new write, no further renewal can occur until 
consumption, and the 6s TTL leaves only a few seconds for the sink insert and 
asynchronously queued MV planning (the task wait allows 180s). A slow but 
correct cluster can fail the test. Save/enable/restore the flag on the master, 
wait for observable renewal, and leave sufficient retention margin for the 
post-write checks while still testing expiry of the original offset.



##########
fe/fe-common/src/main/java/org/apache/doris/common/Config.java:
##########
@@ -3401,6 +3401,23 @@ 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. In Cloud mode, 
MetaService must keep "
+            + "enable_check_commit_tso_fence enabled for keep-alive fencing to 
succeed.",
+            varType = VariableAnnotation.EXPERIMENTAL)
+    public static boolean enable_stream_keepalive = true;

Review Comment:
   [P1] Gate default-on keep-alive on fleet-wide fence enforcement. The three 
updated MetaService commit paths enforce the request flag, but a pre-upgrade MS 
still honors `config::enable_check_commit_tso_fence=false` (the base test 
explicitly permits a stale commit in that mode). During a rolling MS upgrade, a 
new FE can receive OK from `advance_tso_fence` while an older serving MS still 
bypasses commit-side enforcement. The response does not distinguish the two 
behaviors. An outstanding old-leader commit can then invalidate a recorded 
no-change watermark, and the planner may omit changes when it reads after that 
watermark. Default this feature off until the upgrade prerequisite is met, or 
gate it on all serving MS nodes guaranteeing enforcement. Also clarify that the 
legacy switch is ignored by updated MS nodes but must remain enabled on any 
older nodes before keep-alive is enabled.



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