This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 0d1b940232 [flink] Refresh writer coordinator metadata after recovery
(#11152)
0d1b940232 is described below
commit 0d1b9402321972c18ba40530ce9d35f7a8d01cf2
Author: big face cat <[email protected]>
AuthorDate: Mon Nov 16 13:47:21 2026 +0800
[flink] Refresh writer coordinator metadata after recovery (#11152)
---
.../sink/coordinator/WriteOperatorCoordinator.java | 21 +-
.../flink/WriterCoordinatorRecoveryITCase.java | 283 ++++++++++++++++++++
.../coordinator/WriteOperatorCoordinatorTest.java | 286 +++++++++++++++++++++
3 files changed, 588 insertions(+), 2 deletions(-)
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java
index 3fe12cac2d..bc1e1b9efb 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinator.java
@@ -37,6 +37,7 @@ import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicLong;
import static
org.apache.paimon.flink.FlinkConnectorOptions.SINK_WRITER_COORDINATOR_CACHE_EXPIRE_AFTER_ACCESS;
import static
org.apache.paimon.flink.FlinkConnectorOptions.SINK_WRITER_COORDINATOR_CACHE_MEMORY;
@@ -51,6 +52,11 @@ public class WriteOperatorCoordinator implements
OperatorCoordinator, Coordinati
private final FileStoreTable table;
+ private final AtomicLong recoveryGeneration = new AtomicLong();
+
+ // Updated only on the request executor, after a successful metadata
refresh.
+ private long refreshedRecoveryGeneration;
+
private ThreadPoolExecutor executor;
private TableWriteCoordinator coordinator;
@@ -98,6 +104,11 @@ public class WriteOperatorCoordinator implements
OperatorCoordinator, Coordinati
executor.execute(
() -> {
try {
+ long generation = recoveryGeneration.get();
+ if (generation != refreshedRecoveryGeneration) {
+ coordinator.checkpoint();
+ refreshedRecoveryGeneration = generation;
+ }
CoordinationResponse response;
if (request instanceof PagedCoordinationRequest) {
response =
coordinator.scan((PagedCoordinationRequest) request);
@@ -138,10 +149,16 @@ public class WriteOperatorCoordinator implements
OperatorCoordinator, Coordinati
public void notifyCheckpointComplete(long checkpointId) {}
@Override
- public void resetToCheckpoint(long checkpointId, byte[] checkpointData) {}
+ public void resetToCheckpoint(long checkpointId, byte[] checkpointData) {
+ // The checkpoint's snapshot may have been committed after the cached
view was refreshed.
+ // Defer I/O to the request executor; this callback can also run
before start().
+ recoveryGeneration.incrementAndGet();
+ }
@Override
- public void subtaskReset(int subtask, long checkpointId) {}
+ public void subtaskReset(int subtask, long checkpointId) {
+ recoveryGeneration.incrementAndGet();
+ }
@Override
public void executionAttemptFailed(int subtask, int attemptNumber,
Throwable reason) {}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/WriterCoordinatorRecoveryITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/WriterCoordinatorRecoveryITCase.java
new file mode 100644
index 0000000000..085aa38ced
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/WriterCoordinatorRecoveryITCase.java
@@ -0,0 +1,283 @@
+/*
+ * 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.paimon.flink;
+
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.flink.sink.FixedBucketSink;
+import org.apache.paimon.flink.source.AbstractNonCoordinatedSource;
+import org.apache.paimon.flink.source.AbstractNonCoordinatedSourceReader;
+import org.apache.paimon.flink.source.SimpleSourceSplit;
+import org.apache.paimon.flink.util.AbstractTestBase;
+import org.apache.paimon.flink.utils.InternalTypeInfo;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.predicate.PredicateBuilder;
+import org.apache.paimon.reader.RecordReaderIterator;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.sink.StreamWriteBuilder;
+import org.apache.paimon.table.source.ReadBuilder;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowKind;
+
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.api.connector.source.Boundedness;
+import org.apache.flink.api.connector.source.ReaderOutput;
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.SourceReaderContext;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.RestartStrategyOptions;
+import org.apache.flink.core.io.InputStatus;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.minicluster.MiniCluster;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.test.junit5.InjectMiniCluster;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests writer metadata restoration after a task failure in a running Flink
job. */
+public class WriterCoordinatorRecoveryITCase extends AbstractTestBase {
+
+ private static final Map<String, SourceControl> CONTROLS = new
ConcurrentHashMap<>();
+
+ @ParameterizedTest(name = "writerCoordinator = {0}")
+ @ValueSource(booleans = {true, false})
+ @Timeout(180)
+ public void testReplayedUpdateAfterCheckpointRecovery(
+ boolean writerCoordinator, @InjectMiniCluster MiniCluster
miniCluster)
+ throws Exception {
+ FileStoreTable table = createTable(writerCoordinator);
+ StreamWriteBuilder builder = table.newStreamWriteBuilder();
+ try (StreamTableWrite write = builder.newWrite();
+ StreamTableCommit commit = builder.newCommit()) {
+ write.write(GenericRow.of(1L, 3));
+ commit.commit(0, write.prepareCommit(false, 0));
+ }
+
+ String sourceId = UUID.randomUUID().toString();
+ SourceControl control = new SourceControl();
+ Configuration configuration = new Configuration();
+ configuration.set(RestartStrategyOptions.RESTART_STRATEGY,
"fixed-delay");
+
configuration.set(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_ATTEMPTS,
1);
+
configuration.set(RestartStrategyOptions.RESTART_STRATEGY_FIXED_DELAY_DELAY,
Duration.ZERO);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(configuration);
+ env.setParallelism(1);
+ // Only the two explicitly triggered checkpoints may refresh the
coordinator's cache.
+ env.enableCheckpointing(TimeUnit.HOURS.toMillis(1));
+ DataStream<InternalRow> source =
+ env.fromSource(
+ new ReplayingSource(sourceId),
+ WatermarkStrategy.noWatermarks(),
+ "replaying-source",
+ InternalTypeInfo.fromRowType(table.rowType()));
+ new FixedBucketSink(table, null).sinkFrom(source);
+ JobGraph jobGraph = env.getStreamGraph().getJobGraph();
+ // collect() must return only after the writer has processed each
replayed record, before
+ // checkpoint 2 refreshes the coordinator. A shuffle would make that
ordering racy.
+ assertThat(jobGraph.getVertices())
+ .anySatisfy(
+ vertex ->
+ assertThat(vertex.getName())
+ .contains("replaying-source",
"Writer"));
+ boolean submitted = false;
+ CONTROLS.put(sourceId, control);
+ try {
+ miniCluster.submitJob(jobGraph).get(60, TimeUnit.SECONDS);
+ submitted = true;
+ control.initialRowsWritten.get(60, TimeUnit.SECONDS);
+ miniCluster.triggerCheckpoint(jobGraph.getJobID()).get(60,
TimeUnit.SECONDS);
+ awaitSnapshot(table, 2);
+ assertVersion(table, 4);
+
+ // The first attempt writes the change without checkpointing it
and then fails. The
+ // same source restores position 21 and replays it while the
coordinator stays alive.
+ control.failSource.complete(null);
+ assertThat(control.restoredPosition.get(60,
TimeUnit.SECONDS)).isEqualTo(21);
+ control.replayedRowsWritten.get(60, TimeUnit.SECONDS);
+ miniCluster.triggerCheckpoint(jobGraph.getJobID()).get(60,
TimeUnit.SECONDS);
+ awaitSnapshot(table, 3);
+ assertVersion(table, 5);
+ } finally {
+ try {
+ if (submitted) {
+ miniCluster.cancelJob(jobGraph.getJobID()).get(30,
TimeUnit.SECONDS);
+ }
+ } finally {
+ CONTROLS.remove(sourceId);
+ }
+ }
+ }
+
+ private FileStoreTable createTable(boolean writerCoordinator) throws
Exception {
+ Path path = new Path(getTempDirPath());
+ Schema schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.BIGINT())
+ .column("version", DataTypes.INT())
+ .primaryKey("id")
+ .option("bucket", "1")
+ .option("bucket-key", "id")
+ .option("merge-engine", "deduplicate")
+ .option("write-only", "true")
+ .option("changelog-producer", "none")
+ .option("file.format", "parquet")
+ .option(
+ "sink.writer-coordinator.enabled",
+ String.valueOf(writerCoordinator))
+ .build();
+ new FileSystemSchemaManager(LocalFileIO.create(),
path).createTable(schema);
+ return FileStoreTableFactory.create(LocalFileIO.create(), path);
+ }
+
+ private static void awaitSnapshot(FileStoreTable table, long snapshotId)
throws Exception {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60);
+ while (System.nanoTime() < deadline) {
+ Long latest = table.snapshotManager().latestSnapshotId();
+ if (latest != null && latest >= snapshotId) {
+ assertThat(latest).isEqualTo(snapshotId);
+ return;
+ }
+ Thread.sleep(10);
+ }
+ throw new AssertionError("Snapshot " + snapshotId + " was not
committed");
+ }
+
+ private static void assertVersion(FileStoreTable table, int expected)
throws Exception {
+ ReadBuilder read =
+ table.newReadBuilder()
+ .withFilter(new
PredicateBuilder(table.rowType()).equal(0, 1L));
+ try (RecordReaderIterator<InternalRow> rows =
+ new
RecordReaderIterator<>(read.newRead().createReader(read.newScan().plan()))) {
+ int matchingRows = 0;
+ while (rows.hasNext()) {
+ InternalRow row = rows.next();
+ if (row.getLong(0) == 1L) {
+ assertThat(row.getInt(1)).isEqualTo(expected);
+ matchingRows++;
+ }
+ }
+ assertThat(matchingRows).isEqualTo(1);
+ }
+ }
+
+ private static class SourceControl {
+ private final CompletableFuture<Void> initialRowsWritten = new
CompletableFuture<>();
+ private final CompletableFuture<Void> failSource = new
CompletableFuture<>();
+ private final CompletableFuture<Integer> restoredPosition = new
CompletableFuture<>();
+ private final CompletableFuture<Void> replayedRowsWritten = new
CompletableFuture<>();
+ }
+
+ private static class ReplayingSource extends
AbstractNonCoordinatedSource<InternalRow> {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceId;
+
+ private ReplayingSource(String sourceId) {
+ this.sourceId = sourceId;
+ }
+
+ @Override
+ public Boundedness getBoundedness() {
+ return Boundedness.CONTINUOUS_UNBOUNDED;
+ }
+
+ @Override
+ public SourceReader<InternalRow, SimpleSourceSplit> createReader(
+ SourceReaderContext readerContext) {
+ return new ReplayingReader(CONTROLS.get(sourceId));
+ }
+ }
+
+ private static class ReplayingReader extends
AbstractNonCoordinatedSourceReader<InternalRow> {
+
+ private final SourceControl control;
+ private final CompletableFuture<Void> idle = new CompletableFuture<>();
+ private int position;
+ private boolean restored;
+
+ private ReplayingReader(SourceControl control) {
+ this.control = control;
+ }
+
+ @Override
+ public InputStatus pollNext(ReaderOutput<InternalRow> output) {
+ if (position == 0) {
+ // Make the committed row's sequence number greater than any
replay initialized
+ // from the stale snapshot containing only version 3.
+ for (long id = 2; id <= 21; id++) {
+ output.collect(GenericRow.of(id, 0));
+ }
+ output.collect(GenericRow.of(1L, 4));
+ position = 21;
+ control.initialRowsWritten.complete(null);
+ } else if (position == 21 && control.failSource.isDone()) {
+ output.collect(GenericRow.ofKind(RowKind.DELETE, 1L, 4));
+ output.collect(GenericRow.of(1L, 5));
+ position = 23;
+ if (!restored) {
+ throw new RuntimeException("Injected source failure before
checkpoint");
+ }
+ control.replayedRowsWritten.complete(null);
+ }
+ return InputStatus.NOTHING_AVAILABLE;
+ }
+
+ @Override
+ public CompletableFuture<Void> isAvailable() {
+ if (position == 0) {
+ return CompletableFuture.completedFuture(null);
+ }
+ return position == 21 ? control.failSource : idle;
+ }
+
+ @Override
+ public List<SimpleSourceSplit> snapshotState(long checkpointId) {
+ return Collections.singletonList(
+ new SimpleSourceSplit("position",
String.valueOf(position)));
+ }
+
+ @Override
+ public void addSplits(List<SimpleSourceSplit> splits) {
+ assertThat(splits).hasSize(1);
+ position = Integer.parseInt(splits.get(0).value());
+ restored = true;
+ control.restoredPosition.complete(position);
+ }
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java
new file mode 100644
index 0000000000..3b84a00b84
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/coordinator/WriteOperatorCoordinatorTest.java
@@ -0,0 +1,286 @@
+/*
+ * 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.paimon.flink.sink.coordinator;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.TableTestBase;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.sink.StreamWriteBuilder;
+import org.apache.paimon.types.DataTypes;
+
+import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
+import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.paimon.data.BinaryRow.EMPTY_ROW;
+import static
org.apache.paimon.flink.FlinkConnectorOptions.SINK_WRITER_COORDINATOR_PAGE_SIZE;
+import static org.apache.paimon.utils.InstantiationUtil.deserializeObject;
+import static org.apache.paimon.utils.InstantiationUtil.serializeObject;
+import static org.apache.paimon.utils.SerializationUtils.serializeBinaryRow;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+
+/** Tests for refreshing writer metadata after coordinator recovery. */
+@Timeout(60)
+class WriteOperatorCoordinatorTest extends TableTestBase {
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testRecoveryRefreshesFilesAndLatestIdentifier(boolean globalRecovery)
throws Exception {
+ FileStoreTable table = createTable(1024 * 1024);
+ commit(table, 1, GenericRow.of(1L, 3));
+
+ try (WriteOperatorCoordinator coordinator = new
WriteOperatorCoordinator(table)) {
+ coordinator.start();
+ CompletableFuture<byte[]> checkpoint = new CompletableFuture<>();
+ coordinator.checkpointCoordinator(2, checkpoint);
+ checkpoint.get(30, TimeUnit.SECONDS);
+ assertThat(latestIdentifier(coordinator)).isEqualTo(1);
+
+ // The checkpoint refresh precedes publication of its table
snapshot.
+ InternalRow[] rows = new InternalRow[21];
+ for (int i = 0; i < 20; i++) {
+ rows[i] = GenericRow.of((long) i + 2, 1);
+ }
+ rows[20] = GenericRow.of(1L, 4);
+ commit(table, 2, rows);
+ assertThat(scan(coordinator).snapshot().id()).isEqualTo(1);
+ assertThat(latestIdentifier(coordinator)).isEqualTo(1);
+
+ if (globalRecovery) {
+ coordinator.resetToCheckpoint(2, checkpoint.get());
+ } else {
+ coordinator.subtaskReset(0, 2);
+ }
+
+ // No subsequent checkpoint should be needed to initialize the
recovered writer.
+ ScanCoordinationResponse restored = scan(coordinator);
+ assertThat(restored.snapshot().id()).isEqualTo(2);
+ assertThat(restored.extractDataFiles()).hasSize(2);
+ assertThat(
+ restored.extractDataFiles().stream()
+ .mapToLong(DataFileMeta::maxSequenceNumber)
+ .max()
+ .getAsLong())
+ .isEqualTo(21);
+ assertThat(latestIdentifier(coordinator)).isEqualTo(2);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testResetBeforeStart(boolean restoredCheckpoint) throws Exception {
+ FileStoreTable table = createTable(1024 * 1024);
+ commit(table, 1, GenericRow.of(1L, 3));
+
+ try (WriteOperatorCoordinator coordinator = new
WriteOperatorCoordinator(table)) {
+ coordinator.resetToCheckpoint(
+ restoredCheckpoint ? 1 : -1, restoredCheckpoint ? new
byte[0] : null);
+ coordinator.start();
+ assertThat(scan(coordinator).snapshot().id()).isEqualTo(1);
+ assertThat(latestIdentifier(coordinator)).isEqualTo(1);
+ }
+ }
+
+ @Test
+ void testSubtaskResetPreservesInFlightPages() throws Exception {
+ FileStoreTable table = createTable(128);
+ commit(table, 1, GenericRow.of(1L, 3));
+
+ try (WriteOperatorCoordinator coordinator = new
WriteOperatorCoordinator(table)) {
+ coordinator.start();
+ byte[] content = scanRequest();
+ String requestId = UUID.randomUUID().toString();
+ PagedCoordinationResponse firstPage =
+ request(coordinator, new PagedCoordinationRequest(content,
requestId, null));
+ assertThat(firstPage.nextPageToken()).isNotNull();
+
+ commit(table, 2, GenericRow.of(1L, 4));
+ coordinator.subtaskReset(0, 2);
+ assertThat(scan(coordinator).snapshot().id()).isEqualTo(2);
+
+ // An unaffected subtask may still be consuming a response from
before the reset.
+ ScanCoordinationResponse previous =
+ collectPages(coordinator, content, requestId, firstPage);
+ assertThat(previous.snapshot().id()).isEqualTo(1);
+ assertThat(previous.extractDataFiles()).hasSize(1);
+ }
+ }
+
+ @Test
+ void testFailedRefreshIsRetried() throws Exception {
+ FileStoreTable table = createTable(1024 * 1024);
+ commit(table, 1, GenericRow.of(1L, 3));
+ FileStoreTable coordinatorTable = spy(table);
+
+ try (WriteOperatorCoordinator coordinator =
+ new WriteOperatorCoordinator(coordinatorTable)) {
+ coordinator.start();
+ commit(table, 2, GenericRow.of(1L, 4));
+ doThrow(new RuntimeException("Expected refresh failure"))
+ .doReturn(table.latestSnapshot())
+ .when(coordinatorTable)
+ .latestSnapshot();
+ coordinator.subtaskReset(0, 2);
+
+ assertThatThrownBy(() -> scan(coordinator))
+ .hasRootCauseMessage("Expected refresh failure");
+ assertThat(scan(coordinator).snapshot().id()).isEqualTo(2);
+ }
+ }
+
+ @Test
+ void testResetDuringRefreshIsNotLost() throws Exception {
+ FileStoreTable table = createTable(1024 * 1024);
+ commit(table, 1, GenericRow.of(1L, 3));
+ FileStoreTable coordinatorTable = spy(table);
+ CountDownLatch refreshing = new CountDownLatch(1);
+ CountDownLatch continueRefresh = new CountDownLatch(1);
+
+ try (WriteOperatorCoordinator coordinator =
+ new WriteOperatorCoordinator(coordinatorTable)) {
+ coordinator.start();
+ commit(table, 2, GenericRow.of(1L, 4));
+ Optional<Snapshot> snapshotBeforeReset = table.latestSnapshot();
+ AtomicBoolean firstRefresh = new AtomicBoolean(true);
+ doAnswer(
+ invocation -> {
+ if (firstRefresh.getAndSet(false)) {
+ refreshing.countDown();
+ if (!continueRefresh.await(30,
TimeUnit.SECONDS)) {
+ throw new
IllegalStateException("Refresh was not released");
+ }
+ return snapshotBeforeReset;
+ }
+ return invocation.callRealMethod();
+ })
+ .when(coordinatorTable)
+ .latestSnapshot();
+
+ coordinator.subtaskReset(0, 2);
+ CompletableFuture<CoordinationResponse> pending =
+ coordinator.handleCoordinationRequest(
+ new PagedCoordinationRequest(
+ scanRequest(),
UUID.randomUUID().toString(), null));
+ try {
+ assertThat(refreshing.await(30, TimeUnit.SECONDS)).isTrue();
+ commit(table, 3, GenericRow.of(1L, 5));
+ coordinator.subtaskReset(1, 3);
+ } finally {
+ continueRefresh.countDown();
+ }
+ pending.get(30, TimeUnit.SECONDS);
+
+ assertThat(scan(coordinator).snapshot().id()).isEqualTo(3);
+ }
+ }
+
+ private FileStoreTable createTable(int pageSize) throws Exception {
+ Schema schema =
+ Schema.newBuilder()
+ .column("id", DataTypes.BIGINT())
+ .column("version", DataTypes.INT())
+ .primaryKey("id")
+ .option(CoreOptions.BUCKET.key(), "1")
+ .option(CoreOptions.BUCKET_KEY.key(), "id")
+ .option(CoreOptions.WRITE_ONLY.key(), "true")
+ .option(SINK_WRITER_COORDINATOR_PAGE_SIZE.key(),
pageSize + " b")
+ .build();
+ catalog.createTable(identifier(), schema, false);
+ return getTableDefault();
+ }
+
+ private void commit(FileStoreTable table, long identifier, InternalRow...
rows)
+ throws Exception {
+ StreamWriteBuilder builder =
table.newStreamWriteBuilder().withCommitUser(commitUser);
+ try (StreamTableWrite write = builder.newWrite();
+ StreamTableCommit commit = builder.newCommit()) {
+ for (InternalRow row : rows) {
+ write.write(row);
+ }
+ commit.commit(identifier, write.prepareCommit(false, identifier));
+ }
+ }
+
+ private long latestIdentifier(WriteOperatorCoordinator coordinator) throws
Exception {
+ LatestIdentifierResponse response =
+ request(coordinator, new LatestIdentifierRequest(commitUser));
+ return response.latestIdentifier();
+ }
+
+ private ScanCoordinationResponse scan(WriteOperatorCoordinator
coordinator) throws Exception {
+ byte[] content = scanRequest();
+ String requestId = UUID.randomUUID().toString();
+ PagedCoordinationResponse firstPage =
+ request(coordinator, new PagedCoordinationRequest(content,
requestId, null));
+ return collectPages(coordinator, content, requestId, firstPage);
+ }
+
+ private ScanCoordinationResponse collectPages(
+ WriteOperatorCoordinator coordinator,
+ byte[] content,
+ String requestId,
+ PagedCoordinationResponse page)
+ throws Exception {
+ ByteArrayOutputStream result = new ByteArrayOutputStream();
+ while (true) {
+ result.write(page.content());
+ if (page.nextPageToken() == null) {
+ break;
+ }
+ page =
+ request(
+ coordinator,
+ new PagedCoordinationRequest(content, requestId,
page.nextPageToken()));
+ }
+ return deserializeObject(result.toByteArray(),
getClass().getClassLoader());
+ }
+
+ private byte[] scanRequest() throws Exception {
+ return serializeObject(
+ new ScanCoordinationRequest(serializeBinaryRow(EMPTY_ROW), 0,
false, false, false));
+ }
+
+ private <T extends CoordinationResponse> T request(
+ WriteOperatorCoordinator coordinator, CoordinationRequest request)
throws Exception {
+ return CoordinationResponseUtils.unwrap(
+ coordinator.handleCoordinationRequest(request).get(30,
TimeUnit.SECONDS));
+ }
+}