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


##########
cloud/src/meta-service/meta_service_txn.cpp:
##########
@@ -5024,6 +5024,11 @@ void 
MetaServiceImpl::advance_tso_fence(::google::protobuf::RpcController* contr
                                         AdvanceTsoFenceResponse* response,
                                         ::google::protobuf::Closure* done) {
     RPC_PREPROCESS(advance_tso_fence, get, put);
+    if (!config::enable_check_commit_tso_fence) {

Review Comment:
   [P1] Preserve Cloud TSO startup when fence checking is disabled. 
`TSOService.calibrateTimestamp()` already calls this RPC on every Cloud FE 
startup or promotion and marks the allocator initialized only after it 
succeeds. With `enable_check_commit_tso_fence=false`, the new 
`INVALID_ARGUMENT` leaves calibration retrying indefinitely, and 
`TransactionUtil.getCommitTSO()` rejects fresh changelog commits. This happens 
even with FE keep-alive disabled. Preserve the calibration contract while 
making the keep-alive proof explicit, or provide an upgrade path for 
deployments using the existing switch.



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/stream/TableStreamManager.java:
##########
@@ -284,16 +290,425 @@ 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;
+
+    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<>();
+        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);
+                    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);
+                        slice = new LinkedHashSet<>(maxBatch);
+                    }
+                }
+                if (!slice.isEmpty()) {
+                    
keepAliveCloudBatch(Collections.singletonList(snapshot.withPartitionIds(slice)),
+                            perTableKeepAliveTsos, editLogItems, true);
+                }
+                continue;
+            }
+            if (!batch.isEmpty() && partitionsInBatch + 
snapshot.partitionIds.size() > maxBatch) {
+                keepAliveCloudBatch(batch, perTableKeepAliveTsos, 
editLogItems, true);
+                batch = new ArrayList<>();
+                partitionsInBatch = 0;
+            }
+            batch.add(snapshot);
+            partitionsInBatch += snapshot.partitionIds.size();
+        }
+        if (!batch.isEmpty()) {
+            keepAliveCloudBatch(batch, perTableKeepAliveTsos, editLogItems, 
true);
+        }
+        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 void keepAliveCloudBatch(List<CloudKeepAliveSnapshot> batch,
+            Map<Pair<Long, Long>, Long> perTableKeepAliveTsos,
+            List<EditLogItem> editLogItems, boolean allowRetry) {
+        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) {
+            if (allowRetry && batch.size() > 1) {

Review Comment:
   [P2] Limit per-stream retries to binding-specific failures. 
`CloudTableStreamReadStateHelper` also turns a transport timeout or MetaService 
overload into `UserException`. If the fence succeeds and the batch read then 
times out, this branch can issue up to 10,000 serial single-stream calls, each 
with its own deadline and proxy retries. That keeps the only renewal daemon 
from reaching later batches, which can push healthy streams past their TTL. 
Preserve the failure category and bound the retry time per round.



##########
regression-test/suites/table_stream_p0/test_stream_keepalive.groovy:
##########
@@ -0,0 +1,135 @@
+// 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 = sql_return_maparray("ADMIN SHOW FRONTEND CONFIG LIKE 
'%stream_keepalive_interval_second'")

Review Comment:
   [P3] Save and restore the interval on the leader FE. `ADMIN SHOW FRONTEND 
CONFIG` reads the connected FE, while `ADMIN SET FRONTEND CONFIG` forwards this 
leader-only setting. If the suite connects to a follower with a different 
interval, `finally` writes the follower’s old value onto the leader. Use 
`master_sql_return_maparray` and `master_sql`, as the IVM expiry suite does.



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