From 120c34026ad46058e136617b1bb7388c7f58653d Mon Sep 17 00:00:00 2001 From: Jared Dobson <82131+jaredmdobson@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:09:16 -0700 Subject: [PATCH] [flink] Tolerate transient heartbeat failures in tiering enumerator One failed lakeTieringHeartbeat currently fails the whole tiering job, discarding the rounds in progress, although the error is retriable. Add the opt-in lake.tiering.heartbeat.failure-tolerance (default 0, unchanged behaviour). Within it, a retriable or timed-out heartbeat is skipped, the cached coordinator address is refreshed and unacknowledged reports are sent again by the next poll. After a coordinator epoch change, no new table is requested until rounds and reports of the previous epoch have drained. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01HWXvAgjCrkjob7rfuMyBma --- .../apache/fluss/config/ConfigOptions.java | 11 + .../enumerator/TieringSourceEnumerator.java | 128 ++++++++-- .../TieringSourceEnumeratorHeartbeatTest.java | 240 ++++++++++++++++++ .../tiered-storage/lakehouse-storage.md | 1 + 4 files changed, 357 insertions(+), 23 deletions(-) create mode 100644 fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumeratorHeartbeatTest.java diff --git a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java index e169e1517b3..3e2a3c7c9ca 100644 --- a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java +++ b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java @@ -3222,6 +3222,17 @@ public class ConfigOptions { + "Disabled by default. When enabled, mark-done uses the actual lake table's options " + "(e.g. 'partition.idle-time-to-done' on the Paimon table)."); + public static final ConfigOption LAKE_TIERING_HEARTBEAT_FAILURE_TOLERANCE = + key("lake.tiering.heartbeat.failure-tolerance") + .durationType() + .defaultValue(Duration.ZERO) + .withDescription( + "How long consecutive heartbeats from the tiering service to the coordinator may fail " + + "with retriable errors before the tiering job fails. Within this window a failed " + + "heartbeat is skipped, unacknowledged results are kept, and the next poll retries. " + + "The default of 0 fails the job on the first failed heartbeat. " + + "Registration at job startup is not covered."); + public static final ConfigOption LAKE_TIERING_IO_TMP_DIRS = key("lake.tiering.io.tmp.dirs") .stringType() diff --git a/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumerator.java b/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumerator.java index 3fd20a7a34c..08e6e4e58ea 100644 --- a/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumerator.java +++ b/fluss-flink/fluss-flink-common/src/main/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumerator.java @@ -27,6 +27,7 @@ import org.apache.fluss.client.tiering.TieringSplitGenerator; import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; +import org.apache.fluss.exception.RetriableException; import org.apache.fluss.flink.metrics.FlinkMetricRegistry; import org.apache.fluss.flink.tiering.event.FailedTieringEvent; import org.apache.fluss.flink.tiering.event.FinishedTieringEvent; @@ -51,6 +52,8 @@ import org.apache.fluss.rpc.metrics.ClientMetricGroup; import org.apache.fluss.utils.ExceptionUtils; import org.apache.fluss.utils.IOUtils; +import org.apache.fluss.utils.clock.Clock; +import org.apache.fluss.utils.clock.SystemClock; import org.apache.flink.api.connector.source.ReaderInfo; import org.apache.flink.api.connector.source.SourceEvent; @@ -75,11 +78,14 @@ import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import static org.apache.fluss.flink.tiering.source.enumerator.TieringSourceEnumerator.HeartBeatHelper.basicHeartBeat; @@ -132,7 +138,17 @@ public class TieringSourceEnumerator private Connection connection; private Admin flussAdmin; private TieringSplitGenerator splitGenerator; - private int flussCoordinatorEpoch; + private volatile int flussCoordinatorEpoch; + /** The coordinator changed while reports or rounds from the previous one were outstanding. */ + private volatile boolean drainingPreviousCoordinator = false; + + private final long heartbeatFailureToleranceNanos; + /** Clock time in nanoseconds of the first failure in the current streak, if any. */ + @Nullable private volatile Long firstHeartbeatFailureNanos; + + private Clock clock = SystemClock.getInstance(); + + private Runnable coordinatorMetadataRefresh = () -> {}; private volatile boolean isFailOvering = false; @@ -180,6 +196,10 @@ public TieringSourceEnumerator( ScheduledExecutorService timerService) { this.flussConf = flussConf; this.lakeTieringConfig = lakeTieringConfig; + this.heartbeatFailureToleranceNanos = + lakeTieringConfig + .get(ConfigOptions.LAKE_TIERING_HEARTBEAT_FAILURE_TOLERANCE) + .toNanos(); this.context = context; this.lakeTieringFactory = lakeTieringFactory; this.timerService = timerService; @@ -206,12 +226,20 @@ public void start() { new ClientMetricGroup(metricRegistry, "LakeTieringService"); this.rpcClient = RpcClient.create(flussConf, clientMetricGroup); MetadataUpdater metadataUpdater = new MetadataUpdater(flussConf, rpcClient); + // The coordinator address is cached, so refresh it in case the coordinator moved. + this.coordinatorMetadataRefresh = + () -> metadataUpdater.updatePhysicalTableMetadata(Collections.emptySet()); CoordinatorGateway gateway = GatewayClientProxy.createGatewayProxy( metadataUpdater::getCoordinatorServer, rpcClient, CoordinatorGateway.class); start(gateway, admin, new TieringSplitGenerator(admin)); } + @VisibleForTesting + void setClock(Clock clock) { + this.clock = clock; + } + @VisibleForTesting void start( CoordinatorGateway coordinatorGateway, @@ -465,7 +493,6 @@ private void assignSplits() { currentFailedTableEpochs, this.flussCoordinatorEpoch); - Tuple3 lakeTieringInfo = null; // report heartbeat with request table to fluss coordinator LOG.info( "currentFinishedTables: {}, currentFailedTableEpochs: {}, tieringTableEpochs: {}", @@ -473,37 +500,92 @@ private void assignSplits() { currentFailedTableEpochs, tieringTableEpochs); - if (pendingSplits.isEmpty() && !readersAwaitingSplit.isEmpty()) { - LakeTieringHeartbeatResponse heartbeatResponse = + boolean requestTable = + !drainingPreviousCoordinator + && pendingSplits.isEmpty() + && !readersAwaitingSplit.isEmpty(); + if (requestTable) { + heartBeatWithRequestNewTieringTable(tieringHeartbeatRequest); + } + LakeTieringHeartbeatResponse heartbeatResponse; + try { + heartbeatResponse = waitHeartbeatResponse( - coordinatorGateway.lakeTieringHeartbeat( - heartBeatWithRequestNewTieringTable(tieringHeartbeatRequest))); - if (heartbeatResponse.hasTieringTable()) { - PbLakeTieringTableInfo tieringTable = heartbeatResponse.getTieringTable(); - lakeTieringInfo = - Tuple3.of( - tieringTable.getTableId(), - tieringTable.getTieringEpoch(), - TablePath.of( - tieringTable.getTablePath().getDatabaseName(), - tieringTable.getTablePath().getTableName())); - tieringTableEpochs.put(lakeTieringInfo.f0, lakeTieringInfo.f1); - LOG.info("Tiering table {} has been requested.", lakeTieringInfo); - } else { - LOG.info("No available Tiering table found, will poll later."); - } - } else { - // report heartbeat to fluss coordinator - waitHeartbeatResponse(coordinatorGateway.lakeTieringHeartbeat(tieringHeartbeatRequest)); + coordinatorGateway.lakeTieringHeartbeat(tieringHeartbeatRequest)); + } catch (RuntimeException e) { + // Finished and failed tables are kept, so the next heartbeat reports them again. A + // table granted by a lost response is never tracked here, and the coordinator + // reassigns it once its heartbeat times out. + tolerateHeartbeatFailure(e); + return null; } + firstHeartbeatFailureNanos = null; // if come to here, we can remove currentFinishedTables/failedTableEpochs to avoid send // in next round currentFinishedTables.forEach(finishedTables::remove); currentFailedTableEpochs.forEach(failedTableEpochs::remove); + // The job may now outlive a coordinator change. Adopt the new coordinator epoch once + // nothing granted under the previous one is outstanding. + if (tieringTableEpochs.isEmpty() + && finishedTables.isEmpty() + && failedTableEpochs.isEmpty()) { + flussCoordinatorEpoch = heartbeatResponse.getCoordinatorEpoch(); + } + // Still different: a table granted now would be reported with the old epoch and be + // rejected. Leave it to time out, and request no more until the old reports drain. + drainingPreviousCoordinator = + flussCoordinatorEpoch != heartbeatResponse.getCoordinatorEpoch(); + + if (!requestTable || drainingPreviousCoordinator) { + return null; + } + if (!heartbeatResponse.hasTieringTable()) { + LOG.info("No available Tiering table found, will poll later."); + return null; + } + PbLakeTieringTableInfo tieringTable = heartbeatResponse.getTieringTable(); + Tuple3 lakeTieringInfo = + Tuple3.of( + tieringTable.getTableId(), + tieringTable.getTieringEpoch(), + TablePath.of( + tieringTable.getTablePath().getDatabaseName(), + tieringTable.getTablePath().getTableName())); + tieringTableEpochs.put(lakeTieringInfo.f0, lakeTieringInfo.f1); + LOG.info("Tiering table {} has been requested.", lakeTieringInfo); return lakeTieringInfo; } + /** Returns if the failed heartbeat can be left to the next poll, otherwise rethrows. */ + private synchronized void tolerateHeartbeatFailure(RuntimeException failure) { + if (heartbeatFailureToleranceNanos <= 0 || !isRetriable(failure)) { + throw failure; + } + long now = clock.nanoseconds(); + if (firstHeartbeatFailureNanos == null) { + firstHeartbeatFailureNanos = now; + } else if (now - firstHeartbeatFailureNanos >= heartbeatFailureToleranceNanos) { + throw failure; + } + LOG.warn("Heartbeat to the coordinator failed, will retry on the next poll.", failure); + try { + coordinatorMetadataRefresh.run(); + } catch (RuntimeException e) { + LOG.warn("Failed to refresh the coordinator metadata.", e); + } + } + + private static boolean isRetriable(Throwable failure) { + Throwable cause = failure; + while (cause instanceof FlinkRuntimeException + || cause instanceof ExecutionException + || cause instanceof CompletionException) { + cause = cause.getCause(); + } + return cause instanceof RetriableException || cause instanceof TimeoutException; + } + private void generateTieringSplits(Tuple3 tieringTable) throws FlinkRuntimeException { if (tieringTable == null) { diff --git a/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumeratorHeartbeatTest.java b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumeratorHeartbeatTest.java new file mode 100644 index 00000000000..bdfaad04897 --- /dev/null +++ b/fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumeratorHeartbeatTest.java @@ -0,0 +1,240 @@ +/* + * 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.fluss.flink.tiering.source.enumerator; + +import org.apache.fluss.client.admin.Admin; +import org.apache.fluss.client.tiering.TieringLogSplit; +import org.apache.fluss.client.tiering.TieringSplit; +import org.apache.fluss.client.tiering.TieringSplitGenerator; +import org.apache.fluss.config.ConfigOptions; +import org.apache.fluss.config.Configuration; +import org.apache.fluss.exception.NetworkException; +import org.apache.fluss.flink.sink.testutils.TestAdminAdapter; +import org.apache.fluss.flink.tiering.event.FailedTieringEvent; +import org.apache.fluss.flink.tiering.source.split.FlinkTieringSplit; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.metadata.TableInfo; +import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.gateway.CoordinatorGateway; +import org.apache.fluss.rpc.messages.LakeTieringHeartbeatRequest; +import org.apache.fluss.rpc.messages.LakeTieringHeartbeatResponse; +import org.apache.fluss.rpc.messages.PbHeartbeatReqForTable; +import org.apache.fluss.server.coordinator.TestCoordinatorGateway; +import org.apache.fluss.utils.clock.ManualClock; +import org.apache.fluss.utils.concurrent.FutureUtils; + +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import static org.apache.fluss.record.TestData.DATA1_TABLE_INFO; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Tests how {@link TieringSourceEnumerator} handles failed coordinator heartbeats. */ +class TieringSourceEnumeratorHeartbeatTest { + + private static final long TABLE_ID = 7L; + + private final ManualClock clock = new ManualClock(); + private boolean splitGenerationFails = true; + + private final Deque> responses = + new ArrayDeque<>(); + private final List requests = new ArrayList<>(); + + @Test + void testRetriableFailureKeepsUnacknowledgedReports() throws Exception { + try (FlussMockSplitEnumeratorContext context = + new FlussMockSplitEnumeratorContext<>(1)) { + TieringSourceEnumerator enumerator = startEnumerator(context, Duration.ofMinutes(1)); + + // Split generation fails, which leaves a report to deliver. + responses.add(CompletableFuture.completedFuture(grant(1))); + enumerator.handleSplitRequest(0, null); + + responses.add(networkFailure()); + enumerator.handleSplitRequest(0, null); + + // A new coordinator acknowledges the retried report and then grants a table. + LakeTieringHeartbeatResponse acknowledged = response(2); + acknowledged.addFailedTableResp().setTableId(TABLE_ID); + responses.add(CompletableFuture.completedFuture(acknowledged)); + enumerator.handleSplitRequest(0, null); + responses.add(CompletableFuture.completedFuture(grant(2))); + enumerator.handleSplitRequest(0, null); + responses.add(CompletableFuture.completedFuture(response(2))); + enumerator.handleSplitRequest(0, null); + + assertThat(requests.get(2).getFailedTablesList()).hasSize(1); + assertThat(requests.get(3).getFailedTablesList()).hasSize(1); + assertThat(requests.get(4).getFailedTablesList()).isEmpty(); + assertThat(requests.get(5).getFailedTableAt(0).getCoordinatorEpoch()).isEqualTo(2); + } + } + + @Test + void testFailsOnFirstRetriableFailureByDefault() throws Exception { + assertHeartbeatFails(Duration.ZERO, networkFailure()); + } + + @Test + void testNonRetriableFailureIsNotTolerated() throws Exception { + assertHeartbeatFails( + Duration.ofMinutes(1), + FutureUtils.completedExceptionally(new IllegalStateException("broken"))); + } + + @Test + void testFailsOnceToleranceElapses() throws Exception { + try (FlussMockSplitEnumeratorContext context = + new FlussMockSplitEnumeratorContext<>(1)) { + TieringSourceEnumerator enumerator = startEnumerator(context, Duration.ofMillis(1)); + responses.add(networkFailure()); + enumerator.handleSplitRequest(0, null); + + clock.advanceTime(Duration.ofMillis(1)); + responses.add(networkFailure()); + assertThatThrownBy(() -> enumerator.handleSplitRequest(0, null)) + .hasRootCauseInstanceOf(NetworkException.class); + } + } + + @Test + void testNoTableIsTrackedUnderThePreviousCoordinatorEpoch() throws Exception { + try (FlussMockSplitEnumeratorContext context = + new FlussMockSplitEnumeratorContext<>(1)) { + TieringSourceEnumerator enumerator = startEnumerator(context, Duration.ofMinutes(1)); + splitGenerationFails = false; + responses.add(CompletableFuture.completedFuture(grant(1))); + enumerator.handleSplitRequest(0, null); + + // The coordinator changes while that round is still running. + responses.add(CompletableFuture.completedFuture(grant(2, TABLE_ID + 1))); + enumerator.handleSplitRequest(0, null); + responses.add(CompletableFuture.completedFuture(response(2))); + enumerator.handleSplitRequest(0, null); + enumerator.handleSourceEvent(0, new FailedTieringEvent(TABLE_ID, "fenced")); + LakeTieringHeartbeatResponse drained = response(2); + drained.addFailedTableResp().setTableId(TABLE_ID); + responses.add(CompletableFuture.completedFuture(drained)); + enumerator.handleSplitRequest(0, null); + responses.add(CompletableFuture.completedFuture(response(2))); + enumerator.handleSplitRequest(0, null); + + assertThat(requests.get(3).hasRequestTable()).isFalse(); + assertThat(requests.get(3).getTieringTablesList()) + .extracting(PbHeartbeatReqForTable::getTableId) + .containsExactly(TABLE_ID); + assertThat(requests.get(5).isRequestTable()).isTrue(); + } + } + + private void assertHeartbeatFails( + Duration tolerance, CompletableFuture failure) + throws Exception { + try (FlussMockSplitEnumeratorContext context = + new FlussMockSplitEnumeratorContext<>(1)) { + TieringSourceEnumerator enumerator = startEnumerator(context, tolerance); + responses.add(failure); + assertThatThrownBy(() -> enumerator.handleSplitRequest(0, null)) + .hasMessageContaining("Failed to wait heartbeat response"); + } + } + + private TieringSourceEnumerator startEnumerator( + FlussMockSplitEnumeratorContext context, Duration tolerance) { + Configuration lakeTieringConfig = new Configuration(); + lakeTieringConfig.set(ConfigOptions.LAKE_TIERING_HEARTBEAT_FAILURE_TOLERANCE, tolerance); + TieringSourceEnumerator enumerator = + new TieringSourceEnumerator( + new Configuration(), lakeTieringConfig, context, null, 60_000L); + responses.add(CompletableFuture.completedFuture(response(1))); + enumerator.setClock(clock); + enumerator.start(scriptedGateway(), admin(), splitGenerator()); + context.registerSourceReader(0, 0, "localhost"); + return enumerator; + } + + private static Admin admin() { + return new TestAdminAdapter() { + @Override + public CompletableFuture getTableInfo(TablePath tablePath) { + return CompletableFuture.completedFuture(DATA1_TABLE_INFO); + } + }; + } + + private TieringSplitGenerator splitGenerator() { + return new TieringSplitGenerator(null) { + @Override + public List generateTableSplits(TableInfo tableInfo) { + if (splitGenerationFails) { + throw new IllegalStateException("split generation failed"); + } + return Collections.singletonList( + new TieringLogSplit( + tableInfo.getTablePath(), + new TableBucket(TABLE_ID, 0), + null, + 0L, + 1L)); + } + }; + } + + private CoordinatorGateway scriptedGateway() { + return new TestCoordinatorGateway() { + @Override + public CompletableFuture lakeTieringHeartbeat( + LakeTieringHeartbeatRequest request) { + requests.add(request); + return responses.remove(); + } + }; + } + + private static LakeTieringHeartbeatResponse response(int coordinatorEpoch) { + return new LakeTieringHeartbeatResponse().setCoordinatorEpoch(coordinatorEpoch); + } + + private static LakeTieringHeartbeatResponse grant(int coordinatorEpoch) { + return grant(coordinatorEpoch, TABLE_ID); + } + + private static LakeTieringHeartbeatResponse grant(int coordinatorEpoch, long tableId) { + LakeTieringHeartbeatResponse response = response(coordinatorEpoch); + response.setTieringTable() + .setTableId(tableId) + .setTieringEpoch(3L) + .setTablePath() + .setDatabaseName("db") + .setTableName("t"); + return response; + } + + private static CompletableFuture networkFailure() { + return FutureUtils.completedExceptionally(new NetworkException("coordinator disconnected")); + } +} diff --git a/website/docs/maintenance/tiered-storage/lakehouse-storage.md b/website/docs/maintenance/tiered-storage/lakehouse-storage.md index 87d08d3b998..1ddcee97c22 100644 --- a/website/docs/maintenance/tiered-storage/lakehouse-storage.md +++ b/website/docs/maintenance/tiered-storage/lakehouse-storage.md @@ -76,6 +76,7 @@ CREATE TABLE my_table ( |--------|------|---------|-------------| | `lake.tiering.auto-expire-snapshot` | Boolean | false | Auto-trigger snapshot expiration on commit, even if `table.datalake.auto-expire-snapshot` is false | | `lake.tiering.partition.mark-done.enabled` | Boolean | false | Enable [partition mark-done](../../streaming-lakehouse/tiering-service.md#partition-mark-done) using the actual lake table's options | +| `lake.tiering.heartbeat.failure-tolerance` | Duration | 0 | How long consecutive coordinator heartbeats may fail with retriable errors before the tiering job fails. `0` fails on the first error. Startup registration is not covered | | `lake.tiering.io.tmp.dirs` | String | Flink temporary directories | Local directories used for temporary I/O files. If not configured, a `fluss` child directory under each Flink temporary directory is used. Separate multiple directories with commas or the system path separator | | `lake.tiering.commit-thread-num` | Integer | 2 | Number of threads used to commit tables concurrently. Must be positive |