From bcb2a5535b6a0dba38005b02395a51d613e181c2 Mon Sep 17 00:00:00 2001 From: Hongshun Wang Date: Thu, 19 Nov 2026 12:15:07 +0800 Subject: [PATCH 1/3] [FLINK-41564][pipeline-connector/fluss] Balance source split assignment across partitions --- .../enumerator/FlussSourceEnumerator.java | 188 ++++- .../source/event/ReaderSplitReportEvent.java | 47 ++ .../source/reader/FlussSourceReader.java | 12 + .../enumerator/FlussSourceEnumeratorTest.java | 679 +++++++++++++++--- .../source/reader/FlussSourceReaderTest.java | 63 ++ 5 files changed, 890 insertions(+), 99 deletions(-) create mode 100644 flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/event/ReaderSplitReportEvent.java diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java index 4813facff33..3f53abdf088 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java @@ -27,6 +27,7 @@ import org.apache.flink.cdc.common.source.discover.TableDiscovererFactory; import org.apache.flink.cdc.connectors.fluss.source.discover.FlussDefaultDiscoverer; import org.apache.flink.cdc.connectors.fluss.source.event.FinishedKvSnapshotConsumeEvent; +import org.apache.flink.cdc.connectors.fluss.source.event.ReaderSplitReportEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableRemovalAckEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableSubscriptionEvent; import org.apache.flink.cdc.connectors.fluss.source.reader.LeaseContext; @@ -75,7 +76,12 @@ /** * The enumerator for Fluss source. It discovers tables using {@link TableDiscoverer}, queries their * metadata (schema, bucket count, partitions), and generates {@link FlussSplitBase}s for each - * table-bucket pair, assigning them to readers in a round-robin fashion. + * table-bucket pair, assigning new splits to readers with the fewest buckets of the same partition, + * then the same table. A per-table round-robin cursor breaks remaining ties. + * + *

Until this source adopts FLIP-537, a temporary reader-report protocol reconstructs bucket + * ownership on startup. Discovery starts after every reader reports; restored splits remain with + * their readers. The ownership view is not added to checkpoint state. * *

The enumeration follows a four-phase pattern: * @@ -115,6 +121,12 @@ public class FlussSourceEnumerator private final Set assignedPhysicalTablePaths; private final Map> pendingPartitionSplitAssignment; + // Select owners only after reader reports and the first discovery are available. + private final List restoredPendingSplits; + private final Map> readerBuckets = new HashMap<>(); + // Runtime-only cursors for new assignments; not part of checkpoint state. + private final Map nextReaderIndex = new HashMap<>(); + private boolean discoveryStarted; private final TreeMap> consumedKvSnapshotMap; private final Set subscribedTablePaths; private final Set pendingRemovalTablePaths; @@ -159,6 +171,7 @@ public FlussSourceEnumerator( this.leaseContext = leaseContext; this.assignedPhysicalTablePaths = assignedPhysicalTablePaths; this.pendingPartitionSplitAssignment = new HashMap<>(); + this.restoredPendingSplits = new ArrayList<>(remainingSplits); this.consumedKvSnapshotMap = new TreeMap<>(); this.subscribedTablePaths = new HashSet<>(); this.pendingRemovalTablePaths = new HashSet<>(); @@ -184,7 +197,6 @@ public FlussSourceEnumerator( .map(FlussSplitBase::getTablePath) .forEach(subscribedTablePaths::add); this.checkpointCompletedBefore = checkpointCompletedBefore; - addPartitionSplitChangeToPendingAssignments(remainingSplits); } public FlussSourceEnumerator( @@ -235,6 +247,15 @@ public void start() { throw new RuntimeException("Failed to open TableDiscoverer", e); } + maybeStartDiscovery(); + } + + private void maybeStartDiscovery() { + if (admin == null || discoveryStarted || !allReadersReported()) { + return; + } + discoveryStarted = true; + if (scanDiscoveryIntervalMs > 0) { LOG.info( "Starting Fluss source enumerator with a discovery interval of {} ms.", @@ -250,6 +271,11 @@ public void start() { } } + private boolean allReadersReported() { + return context.registeredReaders().size() == context.currentParallelism() + && readerBuckets.keySet().containsAll(context.registeredReaders().keySet()); + } + // ------------------------------------------------------------------------- // Phase 1: Discover subscribed table-buckets (runs async) // ------------------------------------------------------------------------- @@ -329,6 +355,18 @@ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable .forEach(discoveredPhysicalTablePaths::add); boolean partitionsRemoved = removeExpiredPartitions(); lastDiscoveredTableBuckets = discoveryResult.tableBuckets; + Set activeBuckets = + lastDiscoveredTableBuckets.stream() + .filter( + info -> + !pendingRemovalTablePaths.contains( + info.physicalTablePath.getTablePath()) + && !pendingPartitionRemovalRequests.containsKey( + info.physicalTablePath)) + .map(info -> info.tableBucket) + .collect(Collectors.toSet()); + readerBuckets.values().forEach(buckets -> buckets.retainAll(activeBuckets)); + restoredPendingSplits.removeIf(split -> !activeBuckets.contains(split.getTableBucket())); if (!sentSubscriptionSnapshot || subscriptionChanged || bucketsChanged @@ -337,12 +375,17 @@ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable sentSubscriptionSnapshot = true; } + // Assign restored splits before initializing new ones to preserve their offsets. + assignPendingPartitionSplits(); initializeNewTableBuckets(discoveryResult.tableBuckets); } private boolean removeExpiredPartitions() { Set removedPartitions = new HashSet<>(assignedPhysicalTablePaths); removedPartitions.addAll(initializingPhysicalTablePaths); + restoredPendingSplits.stream() + .map(FlussSplitBase::getPhysicalTablePath) + .forEach(removedPartitions::add); pendingPartitionSplitAssignment.values().stream() .flatMap(Set::stream) .map(FlussSplitBase::getPhysicalTablePath) @@ -410,6 +453,9 @@ private boolean hasRemovalFence(FlussSplitBase split) { } private void initializeNewTableBuckets(List allBuckets) { + if (!allReadersReported()) { + return; + } Set knownPhysicalTablePaths = new HashSet<>(assignedPhysicalTablePaths); knownPhysicalTablePaths.addAll(initializingPhysicalTablePaths); @@ -826,7 +872,7 @@ && isCurrentPartitionBucket(split.getTableBucket())) .collect(Collectors.toList()); if (!effectiveNewSplits.isEmpty()) { addPartitionSplitChangeToPendingAssignments(effectiveNewSplits); - assignPendingPartitionSplits(context.registeredReaders().keySet()); + assignPendingPartitionSplits(); } maybeClearRemovalTombstones(); } @@ -838,20 +884,87 @@ && isCurrentPartitionBucket(split.getTableBucket())) // This method should only be invoked in the coordinator executor thread. private void addPartitionSplitChangeToPendingAssignments( Collection newPartitionSplits) { - int numReaders = context.currentParallelism(); + if (newPartitionSplits.isEmpty()) { + return; + } + int parallelism = context.currentParallelism(); + Map bucketCounts = new HashMap<>(); + Map> partitionBucketCounts = new HashMap<>(); + for (FlussSplitBase split : newPartitionSplits) { + TableBucket bucket = split.getTableBucket(); + partitionBucketCounts + .computeIfAbsent(bucket.getTableId(), ignored -> new HashMap<>()) + .computeIfAbsent(bucket.getPartitionId(), ignored -> new int[parallelism]); + } + for (int reader = 0; reader < parallelism; reader++) { + Set buckets = + new HashSet<>(readerBuckets.getOrDefault(reader, Collections.emptySet())); + pendingPartitionSplitAssignment + .getOrDefault(reader, Collections.emptySet()) + .forEach(split -> buckets.add(split.getTableBucket())); + for (TableBucket bucket : buckets) { + int[] counts = + bucketCounts.computeIfAbsent( + bucket.getTableId(), ignored -> new int[parallelism]); + counts[reader]++; + int[] partitionCounts = + partitionBucketCounts + .getOrDefault(bucket.getTableId(), Collections.emptyMap()) + .get(bucket.getPartitionId()); + if (partitionCounts != null) { + partitionCounts[reader]++; + } + } + } for (FlussSplitBase split : newPartitionSplits) { - int ownerReader = getSplitOwner(split.getTableBucket(), numReaders); + TableBucket bucket = split.getTableBucket(); + int[] counts = + bucketCounts.computeIfAbsent( + bucket.getTableId(), ignored -> new int[parallelism]); + int[] partitionCounts = + partitionBucketCounts.get(bucket.getTableId()).get(bucket.getPartitionId()); + int start = + nextReaderIndex.getOrDefault( + bucket.getTableId(), getSplitOwner(bucket, parallelism)); + int owner = start; + for (int offset = 1; offset < counts.length; offset++) { + int candidate = (start + offset) % counts.length; + if (partitionCounts[candidate] < partitionCounts[owner] + || (partitionCounts[candidate] == partitionCounts[owner] + && counts[candidate] < counts[owner])) { + owner = candidate; + } + } + counts[owner]++; + partitionCounts[owner]++; + nextReaderIndex.put(bucket.getTableId(), (owner + 1) % parallelism); pendingPartitionSplitAssignment - .computeIfAbsent(ownerReader, r -> new HashSet<>()) + .computeIfAbsent(owner, ignored -> new HashSet<>()) .add(split); } } // This method should only be invoked in the coordinator executor thread. - private void assignPendingPartitionSplits(Set pendingReaders) { + private void assignPendingPartitionSplits() { + if (!sentSubscriptionSnapshot + || (pendingPartitionSplitAssignment.isEmpty() && restoredPendingSplits.isEmpty()) + || !allReadersReported()) { + return; + } + Set discoveredBuckets = getDiscoveredBuckets(); + pendingPartitionSplitAssignment + .values() + .forEach( + splits -> + splits.removeIf( + split -> + !discoveredBuckets.contains( + split.getTableBucket()))); + addPartitionSplitChangeToPendingAssignments(restoredPendingSplits); + restoredPendingSplits.clear(); Map> incrementalAssignment = new HashMap<>(); - for (int pendingReader : pendingReaders) { + for (int pendingReader : context.registeredReaders().keySet()) { checkReaderRegistered(pendingReader); // Remove pending assignment for the reader @@ -866,6 +979,7 @@ private void assignPendingPartitionSplits(Set pendingReaders) { // Mark pending partitions as already assigned pendingAssignmentForReader.forEach( split -> { + readerBuckets.get(pendingReader).add(split.getTableBucket()); if (hasRemovalFence(split)) { fencedFreshSplits.put(split.splitId(), split); } @@ -890,8 +1004,15 @@ private void checkReaderRegistered(int readerId) { } } + private Set getDiscoveredBuckets() { + return lastDiscoveredTableBuckets.stream() + .map(info -> info.tableBucket) + .collect(Collectors.toSet()); + } + static int getSplitOwner(TableBucket tableBucket, int numReaders) { - return ((tableBucket.hashCode() * 31) & 0x7FFFFFFF) % numReaders; + // Initial round-robin position for a table. + return ((Long.hashCode(tableBucket.getTableId()) * 31) & 0x7FFFFFFF) % numReaders; } // ------------------------------------------------------------------------- @@ -905,6 +1026,37 @@ public void handleSplitRequest(int subtaskId, @Nullable String requesterHostname @Override public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) { + if (sourceEvent instanceof ReaderSplitReportEvent) { + checkReaderRegistered(subtaskId); + if (readerBuckets.containsKey(subtaskId)) { + return; + } + Set buckets = + new HashSet<>(((ReaderSplitReportEvent) sourceEvent).getBuckets()); + if (sentSubscriptionSnapshot) { + buckets.retainAll(getDiscoveredBuckets()); + // The first subscription snapshot discards restored splits for fenced paths. + lastDiscoveredTableBuckets.stream() + .filter( + info -> + removalFences.containsKey( + info.physicalTablePath.getTablePath()) + || pendingRemovalTablePaths.contains( + info.physicalTablePath.getTablePath()) + || partitionRemovalFences.containsKey( + info.physicalTablePath) + || pendingPartitionRemovalRequests.containsKey( + info.physicalTablePath)) + .forEach(info -> buckets.remove(info.tableBucket)); + } + readerBuckets.put(subtaskId, buckets); + maybeStartDiscovery(); + assignPendingPartitionSplits(); + if (sentSubscriptionSnapshot) { + initializeNewTableBuckets(lastDiscoveredTableBuckets); + } + return; + } if (sourceEvent instanceof FinishedKvSnapshotConsumeEvent) { FinishedKvSnapshotConsumeEvent event = (FinishedKvSnapshotConsumeEvent) sourceEvent; LOG.info( @@ -965,7 +1117,7 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) { @Override public void addSplitsBack(List splits, int subtaskId) { LOG.info("Adding {} splits back from subtask {}", splits.size(), subtaskId); - addPartitionSplitChangeToPendingAssignments( + Set returnedSplits = splits.stream() .filter( split -> @@ -979,16 +1131,19 @@ && isCurrentPartitionBucket(split.getTableBucket()) || split.equals( fencedFreshSplits.get( split.splitId())))) - .collect(Collectors.toList())); - // If the failed subtask has already restarted, we need to assign pending splits to it - if (context.registeredReaders().containsKey(subtaskId)) { - assignPendingPartitionSplits(Collections.singleton(subtaskId)); + .collect(Collectors.toSet()); + if (!returnedSplits.isEmpty()) { + pendingPartitionSplitAssignment + .computeIfAbsent(subtaskId, ignored -> new HashSet<>()) + .addAll(returnedSplits); } + assignPendingPartitionSplits(); } @Override public void addReader(int subtaskId) { - LOG.info("Reader {} added, assigning pending splits.", subtaskId); + LOG.info("Reader {} added, waiting for its split report.", subtaskId); + readerBuckets.remove(subtaskId); boolean restartedWithPendingRemoval = !seenReaderSubtasks.add(subtaskId) && (!pendingRemovalTablePaths.isEmpty() @@ -1022,7 +1177,6 @@ public void addReader(int subtaskId) { pendingPartitionRemovalRequests, partitionRemovalFences.keySet())); } - assignPendingPartitionSplits(Collections.singleton(subtaskId)); } @Override @@ -1033,7 +1187,7 @@ public FlussSourceEnumState snapshotState(long checkpointId) throws Exception { partitionRemovalFences.replaceAll( (partitionPath, fenceCheckpointId) -> fenceCheckpointId < 0 ? checkpointId : fenceCheckpointId); - List remainingSplits = new ArrayList<>(); + List remainingSplits = new ArrayList<>(restoredPendingSplits); pendingPartitionSplitAssignment.forEach((reader, splits) -> remainingSplits.addAll(splits)); return new FlussSourceEnumState( assignedPhysicalTablePaths, diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/event/ReaderSplitReportEvent.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/event/ReaderSplitReportEvent.java new file mode 100644 index 00000000000..28867a88d0c --- /dev/null +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/event/ReaderSplitReportEvent.java @@ -0,0 +1,47 @@ +/* + * 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.flink.cdc.connectors.fluss.source.event; + +import org.apache.flink.api.connector.source.SourceEvent; + +import org.apache.fluss.metadata.TableBucket; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * Reports the reader's restored buckets at startup, including an empty set for new readers. + * + *

This is a temporary protocol until the source adopts FLIP-537. It rebuilds the enumerator's + * assignment view without adding checkpoint state or moving restored splits between readers. + */ +public class ReaderSplitReportEvent implements SourceEvent { + + private static final long serialVersionUID = 1L; + + private final Set buckets; + + public ReaderSplitReportEvent(Set buckets) { + this.buckets = Collections.unmodifiableSet(new HashSet<>(buckets)); + } + + public Set getBuckets() { + return buckets; + } +} diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReader.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReader.java index 13bf2c751f9..25dd51f431d 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReader.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReader.java @@ -22,6 +22,7 @@ import org.apache.flink.api.connector.source.util.ratelimit.RateLimiterStrategy; import org.apache.flink.cdc.connectors.fluss.sink.v2.metrics.WrapperFlussMetricRegistry; import org.apache.flink.cdc.connectors.fluss.source.event.FinishedKvSnapshotConsumeEvent; +import org.apache.flink.cdc.connectors.fluss.source.event.ReaderSplitReportEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableRemovalAckEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableSubscriptionEvent; import org.apache.flink.cdc.connectors.fluss.source.metrics.FlussSourceReaderMetrics; @@ -127,6 +128,17 @@ public FlussSourceReader( this.subscribedPhysicalTablePaths = new HashSet<>(); } + @Override + public void start() { + super.start(); + // Temporary fallback before FLIP-537: report restored splits before discovery starts. + readerContext.sendSourceEventToCoordinator( + new ReaderSplitReportEvent( + stagedSplits.stream() + .map(FlussSplitBase::getTableBucket) + .collect(Collectors.toSet()))); + } + @Override public void close() throws Exception { try { diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java index 659e20e9172..2d41b6bf619 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java @@ -26,6 +26,7 @@ import org.apache.flink.cdc.connectors.fluss.source.discover.FlussDefaultDiscoverer; import org.apache.flink.cdc.connectors.fluss.source.discover.FlussSubscriberTableDiscoverer; import org.apache.flink.cdc.connectors.fluss.source.event.FinishedKvSnapshotConsumeEvent; +import org.apache.flink.cdc.connectors.fluss.source.event.ReaderSplitReportEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableRemovalAckEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableSubscriptionEvent; import org.apache.flink.cdc.connectors.fluss.source.reader.LeaseContext; @@ -38,13 +39,16 @@ import org.apache.fluss.client.Connection; import org.apache.fluss.client.ConnectionFactory; +import org.apache.fluss.client.admin.Admin; import org.apache.fluss.client.initializer.OffsetsInitializer; import org.apache.fluss.client.table.Table; import org.apache.fluss.client.table.scanner.batch.BatchScanUtils; import org.apache.fluss.client.table.scanner.batch.BatchScanner; import org.apache.fluss.config.ConfigOptions; +import org.apache.fluss.metadata.PartitionInfo; import org.apache.fluss.metadata.PartitionSpec; import org.apache.fluss.metadata.PhysicalTablePath; +import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.metadata.TableChange; import org.apache.fluss.metadata.TableDescriptor; import org.apache.fluss.metadata.TablePath; @@ -56,10 +60,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -282,11 +288,13 @@ void testRemovalFenceSurvivesAbortedCheckpointAndRearm() throws Throwable { .contains(tablePath); enumerator.snapshotState(1L); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(latestSubscriptionEvent(context, 0).getFencedTablePaths()) .contains(tablePath); enumerator.snapshotState(2L); enumerator.notifyCheckpointComplete(2L); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(latestSubscriptionEvent(context, 0).getFencedTablePaths()) .doesNotContain(tablePath); @@ -315,12 +323,14 @@ void testRemovalFenceSurvivesAbortedCheckpointAndRearm() throws Throwable { enumerator.notifyCheckpointComplete(3L); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(latestSubscriptionEvent(context, 0).getFencedTablePaths()) .contains(tablePath); enumerator.snapshotState(4L); enumerator.notifyCheckpointComplete(4L); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(latestSubscriptionEvent(context, 0).getFencedTablePaths()) .doesNotContain(tablePath); } finally { @@ -376,24 +386,16 @@ void testFencedAddSplitsBackDropsStaleSplitWithoutReassigningOtherBuckets() thro .flatMap(List::stream) .collect(Collectors.toList()); assertThat(freshSplits).hasSize(2); + Map owners = assignedOwners(context); FlussLogSplit freshB0 = freshSplits.stream() - .filter( - split -> - FlussSourceEnumerator.getSplitOwner( - split.getTableBucket(), NUM_READERS) - == 0) + .filter(split -> owners.get(split.getTableBucket()) == 0) .map(FlussSplitBase::asLogSplit) .findFirst() .orElseThrow(AssertionError::new); assertThat( freshSplits.stream() - .filter( - split -> - FlussSourceEnumerator.getSplitOwner( - split.getTableBucket(), - NUM_READERS) - == 1)) + .filter(split -> owners.get(split.getTableBucket()) == 1)) .singleElement(); FlussLogSplit staleB0 = @@ -451,11 +453,16 @@ void testDroppedPartitionDoesNotCreateTableRemovalTombstone() throws Throwable { fqnRegex(DATABASE_NAME, tableName)); try { enumerator.start(); - runDiscoveryCycle(context); + registerAllReaders(context, enumerator); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + context.unregisterReader(0); + context.runNextOneTimeCallable(); FlussSourceEnumStateSerializer serializer = new FlussSourceEnumStateSerializer(); assertThat(enumerator.snapshotState(0L).getRemainingSplits()).isNotEmpty(); byte[] pendingCheckpoint = serializer.serialize(enumerator.snapshotState(0L)); - registerAllReaders(context, enumerator); + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); PhysicalTablePath droppedPartition = PhysicalTablePath.of(tablePath, "20260904"); @@ -522,15 +529,19 @@ void testDroppedPartitionDoesNotCreateTableRemovalTombstone() throws Throwable { .Configuration())); try { restored.start(); + registerAllReaders(restoredContext, restored); if (checkpoint.getRemainingSplits().isEmpty()) { - registerAllReaders(restoredContext, restored); runDiscoveryCycle(restoredContext); } else { + restoredContext.unregisterReader(0); runDiscoveryCycle(restoredContext); assertThat(restored.snapshotState(1L).getRemainingSplits()) .extracting(FlussSplitBase::getPhysicalTablePath) .containsOnly(retainedPartition); - registerAllReaders(restoredContext, restored); + restoredContext.registerReader(new ReaderInfo(0, "restarted_0")); + restored.addReader(0); + restored.handleSourceEvent( + 0, new ReaderSplitReportEvent(Collections.emptySet())); } assertThat(restored.snapshotState(1L).getAssignedPhysicalTablePaths()) .containsExactly(retainedPartition); @@ -766,7 +777,7 @@ void testTableRemovalSupersedesPendingPartitionRemoval() throws Throwable { @ParameterizedTest @ValueSource(booleans = {false, true}) - void testRestorePendingPartitionRemovalRegeneratesRequestId(boolean registerBeforeDiscovery) + void testRestorePendingPartitionRemovalRegeneratesRequestId(boolean readerRestarts) throws Throwable { String tableName = "partition_ack_restore"; createPartitionedPkTable(tableName, 1); @@ -833,13 +844,17 @@ void testRestorePendingPartitionRemovalRegeneratesRequestId(boolean registerBefo new org.apache.flink.configuration.Configuration())); try { enumerator.start(); - if (registerBeforeDiscovery) { - registerAllReaders(context, enumerator); - assertThat(context.getSentSourceEvent()).isEmpty(); - runDiscoveryCycle(context); - } else { - runDiscoveryCycle(context); - registerAllReaders(context, enumerator); + registerAllReaders(context, enumerator); + assertThat(context.getSentSourceEvent()).isEmpty(); + if (readerRestarts) { + context.unregisterReader(0); + } + runDiscoveryCycle(context); + if (readerRestarts) { + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + enumerator.handleSourceEvent( + 0, new ReaderSplitReportEvent(Collections.emptySet())); } long requestId = @@ -884,7 +899,10 @@ void testExpiredPendingPartitionIsNotAssignedToLateReaders() throws Throwable { fqnRegex(DATABASE_NAME, tableName)); try { enumerator.start(); - runDiscoveryCycle(context); + registerAllReaders(context, enumerator); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + context.unregisterReader(0); + context.runNextOneTimeCallable(); assertThat(enumerator.snapshotState(0L).getRemainingSplits()).hasSize(2); connection .getAdmin() @@ -900,7 +918,9 @@ void testExpiredPendingPartitionIsNotAssignedToLateReaders() throws Throwable { split -> assertThat(split.getPhysicalTablePath()) .isEqualTo(livePath)); - registerAllReaders(context, enumerator); + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(enumerator.snapshotState(2L).getAssignedPhysicalTablePaths()) .containsExactly(livePath); for (int readerId = 0; readerId < NUM_READERS; readerId++) { @@ -1179,12 +1199,13 @@ void testMultiplePeriodicDiscoveryRoundsBeforeInitDoNotDuplicateSplits() throws } /** - * Tests that when no readers are registered yet, a completed table-bucket initialization lands - * in the pending assignment map instead of being lost or re-queued, and that once readers - * register, all pending splits are assigned exactly once. + * Tests that initialization completing during a reader restart stays pending until the reader + * reports its restored splits, without losing or re-queuing splits. */ - @Test - void testPendingAssignmentSurvivesDiscoveryUntilReadersRegister() throws Throwable { + @ParameterizedTest + @CsvSource({"true", "false"}) + void testPendingAssignmentSurvivesDiscoveryWhileReaderRestarts(boolean failsDuringDiscovery) + throws Throwable { String tableName = "pending_no_reader"; createPkTable(tableName, 3); @@ -1196,18 +1217,31 @@ void testPendingAssignmentSurvivesDiscoveryUntilReadersRegister() throws Throwab FlussSourceEnumerator enumerator = newEnumerator(context, discoverer, pattern); try { enumerator.start(); - - // No readers registered yet: initialization completes into the pending - // assignment map instead of being assigned. - runDiscoveryCycle(context); + registerAllReaders(context, enumerator); + if (failsDuringDiscovery) { + context.unregisterReader(0); + } + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + if (!failsDuringDiscovery) { + context.unregisterReader(0); + context.runNextOneTimeCallable(); + } assertThat(context.getSplitsAssignmentSequence()).isEmpty(); + assertThat(enumerator.snapshotState(1L).getRemainingSplits()) + .hasSize(failsDuringDiscovery ? 0 : 3); // A subsequent discovery round must not re-discover or re-queue the same // table-buckets while they are only pending (not yet assigned). context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); assertThat(context.getOneTimeCallables()).isEmpty(); - registerAllReaders(context, enumerator); + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + assertThat(context.getSplitsAssignmentSequence()).isEmpty(); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); + while (!context.getOneTimeCallables().isEmpty()) { + context.runNextOneTimeCallable(); + } assertThat(assignedBucketIds(context, tableName)) .containsExactlyInAnyOrder(0, 1, 2); @@ -1246,9 +1280,12 @@ void testPartitionBucketCountAfterTableDefaultChange(boolean discoveryBeforeDefa fqnRegex(DATABASE_NAME, tableName)); try { enumerator.start(); + registerAllReaders(context, enumerator); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + context.unregisterReader(0); + context.runNextOneTimeCallable(); + assertThat(enumerator.snapshotState(1L).getRemainingSplits()).hasSize(4); if (discoveryBeforeDefaultChange) { - runDiscoveryCycle(context); - assertThat(enumerator.snapshotState(1L).getRemainingSplits()).hasSize(4); connection .getAdmin() .alterTable( @@ -1270,7 +1307,10 @@ void testPartitionBucketCountAfterTableDefaultChange(boolean discoveryBeforeDefa runDiscoveryCycle(context); assertThat(context.getSplitsAssignmentSequence()).isEmpty(); - registerAllReaders(context, enumerator); + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + enumerator.handleSourceEvent( + 0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(assignedBucketIds(context, tableName)) .containsExactlyInAnyOrder(0, 1, 2, 3); @@ -1289,6 +1329,342 @@ void testPartitionBucketCountAfterTableDefaultChange(boolean discoveryBeforeDefa } } + @ParameterizedTest + @CsvSource({"0", "10000"}) + void testDiscoveryWaitsForAllReaderReports(long discoveryInterval) throws Throwable { + String tableName = "wait_for_split_reports"; + createPkTable(tableName, 2); + try (MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(NUM_READERS)) { + FlussSourceEnumerator enumerator = + newEnumerator( + context, + new FlussDefaultDiscoverer(), + fqnRegex(DATABASE_NAME, tableName), + OffsetsInitializer.earliest(), + discoveryInterval); + try { + enumerator.start(); + for (int reader = 0; reader < NUM_READERS; reader++) { + context.registerReader(new ReaderInfo(reader, "loc_" + reader)); + enumerator.addReader(reader); + } + assertThat(context.getPeriodicCallables()).isEmpty(); + assertThat(context.getOneTimeCallables()).isEmpty(); + + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); + assertThat(context.getPeriodicCallables()).isEmpty(); + assertThat(context.getOneTimeCallables()).isEmpty(); + enumerator.handleSourceEvent(1, new ReaderSplitReportEvent(Collections.emptySet())); + enumerator.handleSourceEvent(1, new ReaderSplitReportEvent(Collections.emptySet())); + + if (discoveryInterval > 0) { + assertThat(context.getPeriodicCallables()).hasSize(1); + runDiscoveryCycle(context); + } else { + assertThat(context.getOneTimeCallables()).hasSize(1); + while (!context.getOneTimeCallables().isEmpty()) { + context.runNextOneTimeCallable(); + } + } + assertThat(context.getSplitsAssignmentSequence()).hasSize(1); + assertThat(assignedBucketIds(context, tableName)).containsExactlyInAnyOrder(0, 1); + } finally { + enumerator.close(); + } + } + } + + @ParameterizedTest + @CsvSource({"false, false", "false, true", "true, false", "true, true"}) + void testRoundRobinCursorAdvancesFromSelectedOwner( + boolean separateDiscoveries, boolean oldOnStartReader) throws Throwable { + String tableName = "round_robin_partitions"; + createPartitionedPkTable(tableName, 1); + TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); + org.apache.fluss.config.Configuration config = FLUSS_CLUSTER_EXTENSION.getClientConfig(); + try (Connection connection = ConnectionFactory.createConnection(config); + MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(NUM_READERS)) { + Admin admin = connection.getAdmin(); + createPartition(admin, tablePath, "old"); + long tableId = admin.getTableInfo(tablePath).get().getTableId(); + TableBucket oldBucket = + new TableBucket( + tableId, + admin.listPartitionInfos(tablePath).get().get(0).getPartitionId(), + 0); + int startReader = FlussSourceEnumerator.getSplitOwner(oldBucket, NUM_READERS); + int oldOwner = oldOnStartReader ? startReader : 1 - startReader; + FlussSourceEnumerator enumerator = + new FlussSourceEnumerator( + context, + new FlussDefaultDiscoverer(), + config, + buildSourceConfig(config, fqnRegex(DATABASE_NAME, "round_robin_.*")), + OffsetsInitializer.earliest(), + DISCOVERY_INTERVAL_MS, + new HashSet<>( + Collections.singleton(PhysicalTablePath.of(tablePath, "old"))), + Collections.emptyList(), + LeaseContext.fromConf( + new org.apache.flink.configuration.Configuration()), + true); + try { + enumerator.start(); + for (int reader = 0; reader < NUM_READERS; reader++) { + context.registerReader(new ReaderInfo(reader, "loc_" + reader)); + enumerator.addReader(reader); + reportOwnedBuckets( + enumerator, reader, Collections.singletonMap(oldBucket, oldOwner)); + } + runDiscoveryCycle(context); + assertThat(assignedOwners(context)).isEmpty(); + + createPartition(admin, tablePath, "new_1"); + if (separateDiscoveries) { + runDiscoveryCycle(context); + assertThat(assignedOwners(context).values()).containsExactly(1 - oldOwner); + createPkTable("round_robin_other"); + runDiscoveryCycle(context); + assertThat(assignedOwners(context)).hasSize(2); + assignedOwners(context) + .forEach( + (bucket, owner) -> { + if (bucket.getTableId() != tableId) { + assertThat(owner) + .isEqualTo( + FlussSourceEnumerator.getSplitOwner( + bucket, NUM_READERS)); + } + }); + } + createPartition(admin, tablePath, "new_2"); + runDiscoveryCycle(context); + assertThat( + assignedOwners(context).entrySet().stream() + .filter(entry -> entry.getKey().getTableId() == tableId) + .map(Map.Entry::getValue)) + .containsExactlyInAnyOrder(0, 1); + } finally { + enumerator.close(); + } + } + } + + @ParameterizedTest + @CsvSource({"2", "4", "5"}) + void testSpreadsNewPartitionAcrossReadersDespiteSkewedTableCounts(int numBuckets) + throws Throwable { + int parallelism = 4; + String tableName = "partition_first_assignment"; + createPartitionedPkTable(tableName, numBuckets); + TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); + org.apache.fluss.config.Configuration config = FLUSS_CLUSTER_EXTENSION.getClientConfig(); + try (Connection connection = ConnectionFactory.createConnection(config); + MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(parallelism)) { + Admin admin = connection.getAdmin(); + for (int partition = 0; partition < 28; partition++) { + createPartition(admin, tablePath, "old_" + partition); + } + long tableId = admin.getTableInfo(tablePath).get().getTableId(); + int[] remaining = { + 7 * numBuckets + 2, 7 * numBuckets + 2, 7 * numBuckets - 2, 7 * numBuckets - 2 + }; + Set assignedPaths = new HashSet<>(); + Map restoredOwners = new HashMap<>(); + int owner = 0; + for (PartitionInfo partition : admin.listPartitionInfos(tablePath).get()) { + assignedPaths.add(PhysicalTablePath.of(tablePath, partition.getPartitionName())); + for (int bucket = 0; bucket < numBuckets; bucket++) { + while (remaining[owner] == 0) { + owner++; + } + restoredOwners.put( + new TableBucket(tableId, partition.getPartitionId(), bucket), owner); + remaining[owner]--; + } + } + FlussSourceEnumerator enumerator = + new FlussSourceEnumerator( + context, + new FlussDefaultDiscoverer(), + config, + buildSourceConfig(config, fqnRegex(DATABASE_NAME, tableName)), + OffsetsInitializer.earliest(), + DISCOVERY_INTERVAL_MS, + assignedPaths, + Collections.emptyList(), + LeaseContext.fromConf( + new org.apache.flink.configuration.Configuration()), + true); + try { + enumerator.start(); + for (int reader = 0; reader < parallelism; reader++) { + context.registerReader(new ReaderInfo(reader, "restored_" + reader)); + enumerator.addReader(reader); + reportOwnedBuckets(enumerator, reader, restoredOwners); + } + runDiscoveryCycle(context); + assertThat(assignedOwners(context)).isEmpty(); + + for (int partition = 0; partition < 2; partition++) { + Set previouslyAssigned = assignedOwners(context).keySet(); + createPartition(admin, tablePath, "new_" + partition); + runDiscoveryCycle(context); + Map owners = assignedOwners(context); + owners.keySet().removeAll(previouslyAssigned); + assertBalancedOwners(owners, parallelism, numBuckets); + assertThat(new HashSet<>(owners.values())) + .hasSize(Math.min(numBuckets, parallelism)); + assertThat( + owners.entrySet().stream() + .filter(entry -> entry.getKey().getBucket() == 0) + .map(Map.Entry::getValue)) + .singleElement() + .isIn(2, 3); + } + } finally { + enumerator.close(); + } + } + } + + @ParameterizedTest + @CsvSource({"1, 4", "2, 4", "3, 3"}) + void testBalancesNewPartitionsUsingRestoredReaderReports( + int numBuckets, int restoredParallelism) throws Throwable { + String tableName = "reported_partition_assignment"; + String otherTable = "other_partition_ids"; + createPartitionedPkTable(tableName, numBuckets); + createPartitionedPkTable(otherTable, 1); + TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); + String pattern = fqnRegex(DATABASE_NAME, tableName); + Map restoredOwners = new HashMap<>(); + FlussSourceEnumState state; + try (Connection connection = + ConnectionFactory.createConnection(FLUSS_CLUSTER_EXTENSION.getClientConfig())) { + Admin admin = connection.getAdmin(); + for (int partition = 0; partition < 4; partition++) { + createPartition(admin, tablePath, "p" + partition); + for (int other = 0; other < 3; other++) { + createPartition( + admin, + TablePath.of(DATABASE_NAME, otherTable), + "p" + partition + "_" + other); + } + } + try (MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(4)) { + FlussSourceEnumerator enumerator = + newEnumerator(context, new FlussDefaultDiscoverer(), pattern); + try { + enumerator.start(); + registerAllReaders(context, enumerator); + runDiscoveryCycle(context); + assertBalancedOwners(assignedOwners(context), 4, 4 * numBuckets); + for (SplitsAssignment assignment : + context.getSplitsAssignmentSequence()) { + for (Map.Entry> entry : + assignment.assignment().entrySet()) { + for (FlussSplitBase split : entry.getValue()) { + if (!"p0".equals(split.getPhysicalTablePath().getPartitionName())) { + int reader = + restoredParallelism == 4 + ? (entry.getKey() + 1) % 4 + : restoredOwners.size() % restoredParallelism; + restoredOwners.put(split.getTableBucket(), reader); + } + } + } + } + admin.dropPartition( + tablePath, + new PartitionSpec(Collections.singletonMap("ds", "p0")), + false) + .get(); + runDiscoveryCycle(context); + state = enumerator.snapshotState(1L); + } finally { + enumerator.close(); + } + } + createPartition(admin, tablePath, "p4"); + try (MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(restoredParallelism)) { + org.apache.fluss.config.Configuration config = + FLUSS_CLUSTER_EXTENSION.getClientConfig(); + FlussSourceEnumerator enumerator = + new FlussSourceEnumerator( + context, + new FlussDefaultDiscoverer(), + config, + buildSourceConfig(config, pattern), + OffsetsInitializer.earliest(), + DISCOVERY_INTERVAL_MS, + state, + LeaseContext.fromConf( + new org.apache.flink.configuration.Configuration())); + try { + enumerator.start(); + for (int reader = 0; reader < restoredParallelism; reader++) { + context.registerReader(new ReaderInfo(reader, "restored_" + reader)); + enumerator.addReader(reader); + } + assertThat(context.getPeriodicCallables()).isEmpty(); + for (int reader = 0; reader < restoredParallelism; reader++) { + assertThat(context.getSplitsAssignmentSequence()).isEmpty(); + reportOwnedBuckets(enumerator, reader, restoredOwners); + } + runDiscoveryCycle(context); + Map owners = new HashMap<>(restoredOwners); + owners.putAll(assignedOwners(context)); + assertBalancedOwners(owners, restoredParallelism, 4 * numBuckets); + assertThat(assignedOwners(context)).hasSize(numBuckets); + + Map.Entry> freshAssignment = + context.getSplitsAssignmentSequence() + .get(0) + .assignment() + .entrySet() + .iterator() + .next(); + int failedReader = freshAssignment.getKey(); + List returned = freshAssignment.getValue(); + int assignmentsBeforeRestart = context.getSplitsAssignmentSequence().size(); + context.unregisterReader(failedReader); + enumerator.addSplitsBack(returned, failedReader); + context.registerReader(new ReaderInfo(failedReader, "restarted")); + enumerator.addReader(failedReader); + assertThat(context.getSplitsAssignmentSequence()) + .hasSize(assignmentsBeforeRestart); + reportOwnedBuckets(enumerator, failedReader, restoredOwners); + assertThat(context.getSplitsAssignmentSequence()) + .hasSize(assignmentsBeforeRestart + 1); + assertThat( + context.getSplitsAssignmentSequence() + .get(assignmentsBeforeRestart) + .assignment()) + .containsOnlyKeys(failedReader); + assertThat( + context.getSplitsAssignmentSequence() + .get(assignmentsBeforeRestart) + .assignment() + .get(failedReader)) + .containsExactlyInAnyOrderElementsOf(returned); + + createPartition(admin, tablePath, "p5"); + runDiscoveryCycle(context); + owners.putAll(assignedOwners(context)); + assertBalancedOwners(owners, restoredParallelism, 5 * numBuckets); + } finally { + enumerator.close(); + } + } + } + } + /** * Tests that once one partition's initialization completes, a subsequent discovery round does * not re-queue initialization for another partition whose initialization is still in flight. @@ -1545,6 +1921,119 @@ void testDiscoveryFailsWhenOffsetInitializationIsIncomplete() throws Throwable { // Enumerator checkpoint restore tests // ===================================================================== + @ParameterizedTest + @CsvSource({"false", "true"}) + void testRestoredPendingSplitsWaitForReportsAndDiscovery(boolean readerRestarts) + throws Throwable { + String tableName = "restore_pending_owner"; + createPartitionedPkTable(tableName, 1); + TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); + org.apache.fluss.config.Configuration config = FLUSS_CLUSTER_EXTENSION.getClientConfig(); + try (Connection connection = ConnectionFactory.createConnection(config); + MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(NUM_READERS)) { + Admin admin = connection.getAdmin(); + for (String partition : Arrays.asList("reported", "returned", "pending")) { + createPartition(admin, tablePath, partition); + } + long tableId = admin.getTableInfo(tablePath).get().getTableId(); + Map partitionIds = + admin.listPartitionInfos(tablePath).get().stream() + .collect( + Collectors.toMap( + PartitionInfo::getPartitionName, + PartitionInfo::getPartitionId)); + FlussLogSplit pendingSplit = + new FlussLogSplit( + PhysicalTablePath.of(tablePath, "pending"), + new TableBucket(tableId, partitionIds.get("pending"), 0), + 123L); + FlussLogSplit returnedSplit = + new FlussLogSplit( + PhysicalTablePath.of(tablePath, "returned"), + new TableBucket(tableId, partitionIds.get("returned"), 0), + 456L); + FlussLogSplit deletedPartitionSplit = + new FlussLogSplit( + PhysicalTablePath.of(tablePath, "deleted"), + new TableBucket(tableId, Long.MAX_VALUE - 10, 0), + 789L); + int originalOwner = + FlussSourceEnumerator.getSplitOwner(pendingSplit.getTableBucket(), NUM_READERS); + int expectedOwner = (originalOwner + 1) % NUM_READERS; + Map reportedOwners = new HashMap<>(); + reportedOwners.put( + new TableBucket(tableId, partitionIds.get("reported"), 0), originalOwner); + // The first discovery must remove stale reports before choosing an owner. + for (int partition = 0; partition < 3; partition++) { + reportedOwners.put( + new TableBucket(tableId, Long.MAX_VALUE - partition, 0), expectedOwner); + } + FlussSourceEnumState state = + new FlussSourceEnumState( + new HashSet<>( + Arrays.asList( + PhysicalTablePath.of(tablePath, "reported"), + returnedSplit.getPhysicalTablePath())), + Arrays.asList(pendingSplit, deletedPartitionSplit), + "restored-pending-lease"); + FlussSourceEnumerator enumerator = + new FlussSourceEnumerator( + context, + new FlussDefaultDiscoverer(), + config, + buildSourceConfig(config, fqnRegex(DATABASE_NAME, tableName)), + OffsetsInitializer.earliest(), + DISCOVERY_INTERVAL_MS, + state, + LeaseContext.fromConf( + new org.apache.flink.configuration.Configuration())); + try { + enumerator.start(); + assertThat(enumerator.snapshotState(1L).getRemainingSplits()) + .containsExactlyInAnyOrder(pendingSplit, deletedPartitionSplit); + enumerator.addSplitsBack(Collections.singletonList(returnedSplit), originalOwner); + for (int reader = 0; reader < NUM_READERS; reader++) { + assertThat(context.getPeriodicCallables()).isEmpty(); + context.registerReader(new ReaderInfo(reader, "restored_" + reader)); + enumerator.addReader(reader); + reportOwnedBuckets(enumerator, reader, reportedOwners); + } + assertThat(context.getSplitsAssignmentSequence()).isEmpty(); + assertThat(enumerator.snapshotState(2L).getRemainingSplits()) + .containsExactlyInAnyOrder( + pendingSplit, deletedPartitionSplit, returnedSplit); + if (readerRestarts) { + context.unregisterReader(originalOwner); + } + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + if (readerRestarts) { + assertThat(context.getSplitsAssignmentSequence()).isEmpty(); + assertThat(enumerator.snapshotState(3L).getRemainingSplits()) + .containsExactlyInAnyOrder(pendingSplit, returnedSplit); + context.registerReader(new ReaderInfo(originalOwner, "restarted")); + enumerator.addReader(originalOwner); + reportOwnedBuckets(enumerator, originalOwner, reportedOwners); + } + assertThat(context.getOneTimeCallables()).isEmpty(); + assertThat(assignedOwners(context)) + .hasSize(2) + .containsEntry(pendingSplit.getTableBucket(), expectedOwner) + .containsEntry(returnedSplit.getTableBucket(), originalOwner); + assertThat(context.getSplitsAssignmentSequence()).hasSize(1); + Map> assignment = + context.getSplitsAssignmentSequence().get(0).assignment(); + assertThat(assignment.get(expectedOwner)).containsExactly(pendingSplit); + assertThat(assignment.get(originalOwner)).containsExactly(returnedSplit); + assertThat(enumerator.snapshotState(4L).getRemainingSplits()).isEmpty(); + runDiscoveryCycle(context); + assertThat(context.getSplitsAssignmentSequence()).hasSize(1); + } finally { + enumerator.close(); + } + } + } + @Test void testRestorePendingLatestSplitPreservesStartingOffsetAfterRescale() throws Throwable { String tableName = "restore_pending_latest"; @@ -1576,8 +2065,10 @@ void testRestorePendingLatestSplitPreservesStartingOffsetAfterRescale() throws T DISCOVERY_INTERVAL_MS); try { enumerator.start(); - - runDiscoveryCycle(context); + registerAllReaders(context, enumerator); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + context.unregisterReader(0); + context.runNextOneTimeCallable(); checkpoint = enumerator.snapshotState(1L); assertThat(checkpoint.getAssignedPhysicalTablePaths()).isEmpty(); @@ -1596,12 +2087,7 @@ void testRestorePendingLatestSplitPreservesStartingOffsetAfterRescale() throws T String.format("INSERT INTO %s VALUES (2, 'after-checkpoint')", tableName)) .await(); - int originalOwner = - FlussSourceEnumerator.getSplitOwner( - checkpointedSplit.getTableBucket(), NUM_READERS); - int restoredParallelism = - findParallelismWithDifferentOwner( - checkpointedSplit.getTableBucket(), NUM_READERS, originalOwner); + int restoredParallelism = NUM_READERS + 1; int restoredOwner = FlussSourceEnumerator.getSplitOwner( checkpointedSplit.getTableBucket(), restoredParallelism); @@ -1623,20 +2109,8 @@ void testRestorePendingLatestSplitPreservesStartingOffsetAfterRescale() throws T new org.apache.flink.configuration.Configuration())); try { restoredEnumerator.start(); - - // Discovery may run before the restored split's owner reader registers. + registerAllReaders(restoredContext, restoredEnumerator); runDiscoveryCycle(restoredContext); - - restoredContext.registerReader( - new ReaderInfo(originalOwner, "loc_" + originalOwner)); - restoredEnumerator.addReader(originalOwner); - assertThat(restoredContext.getSplitsAssignmentSequence()).isEmpty(); - - restoredContext.registerReader( - new ReaderInfo(restoredOwner, "loc_" + restoredOwner)); - restoredEnumerator.addReader(restoredOwner); - - assertThat(restoredOwner).isNotEqualTo(originalOwner); assertThat(restoredContext.getSplitsAssignmentSequence()).hasSize(1); SplitsAssignment assignment = restoredContext.getSplitsAssignmentSequence().get(0); @@ -1674,7 +2148,10 @@ void testRestoreHybridSplitKeepsCheckpointedSnapshotAvailable() throws Throwable DISCOVERY_INTERVAL_MS); try { enumerator.start(); - runDiscoveryCycle(context); + registerAllReaders(context, enumerator); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + context.unregisterReader(0); + context.runNextOneTimeCallable(); checkpoint = enumerator.snapshotState(1L); assertThat(checkpoint.getRemainingSplits()).hasSize(1); @@ -1717,13 +2194,11 @@ void testRestoreHybridSplitKeepsCheckpointedSnapshotAvailable() throws Throwable new org.apache.flink.configuration.Configuration())); try { restoredEnumerator.start(); - runDiscoveryCycle(restoredContext); - int owner = FlussSourceEnumerator.getSplitOwner( checkpointedSplit.getTableBucket(), NUM_READERS); - restoredContext.registerReader(new ReaderInfo(owner, "loc_" + owner)); - restoredEnumerator.addReader(owner); + registerAllReaders(restoredContext, restoredEnumerator); + runDiscoveryCycle(restoredContext); assertThat(restoredContext.getSplitsAssignmentSequence()).hasSize(1); FlussHybridSnapshotLogSplit restoredSplit = @@ -1963,6 +2438,7 @@ void testSubscriptionDeletionPersistsTombstoneUntilEveryReaderAcknowledges() thr .containsExactly(tablePath); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); long restartedRequestId = latestSubscriptionEvent(context, 0) .getPendingRemovalRequests() @@ -2044,6 +2520,7 @@ void testRemovalWaitsForRegisteredReadersAndDropsLateFailedSplit() throws Throwa context.registerReader(new ReaderInfo(0, "restarted_0")); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); long restartedRequestId = latestSubscriptionEvent(context, 0) .getPendingRemovalRequests() @@ -2277,8 +2754,8 @@ void testRestoreRegeneratesRemovalRequestIdAndRejectsOldAcknowledgement() throws restoredState); try { enumerator.start(); - runDiscoveryCycle(context); registerAllReaders(context, enumerator); + runDiscoveryCycle(context); long restoredRequestId = latestSubscriptionEvent(context, 0) @@ -2342,12 +2819,16 @@ void testRestartedReaderWaitsForFreshDiscoveryBeforeReceivingRemovalSnapshot() enumerator.start(); context.registerReader(new ReaderInfo(0, "loc_0")); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); context.unregisterReader(0); context.registerReader(new ReaderInfo(0, "loc_0_restarted")); enumerator.addReader(0); + enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); assertThat(context.getSentSourceEvent()).doesNotContainKey(0); - + context.registerReader(new ReaderInfo(1, "loc_1")); + enumerator.addReader(1); + enumerator.handleSourceEvent(1, new ReaderSplitReportEvent(Collections.emptySet())); context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); assertThat(latestSubscriptionEvent(context, 0).getPendingRemovalRequests()) @@ -2462,6 +2943,53 @@ void testSubscriptionDeletionRemovesPendingKvSnapshotRelease() throws Throwable // Helpers // ===================================================================== + private static void createPartition(Admin admin, TablePath tablePath, String partition) + throws Exception { + admin.createPartition( + tablePath, + new PartitionSpec(Collections.singletonMap("ds", partition)), + false) + .get(); + } + + private static Map assignedOwners( + MockSplitEnumeratorContext context) { + Map owners = new HashMap<>(); + context.getSplitsAssignmentSequence() + .forEach( + assignment -> + assignment + .assignment() + .forEach( + (reader, splits) -> + splits.forEach( + split -> + owners.put( + split + .getTableBucket(), + reader)))); + return owners; + } + + private static void assertBalancedOwners( + Map owners, int parallelism, int total) { + assertThat(owners).hasSize(total); + int[] counts = new int[parallelism]; + owners.values().forEach(reader -> counts[reader]++); + assertThat(Arrays.stream(counts).max().getAsInt() - Arrays.stream(counts).min().getAsInt()) + .isLessThanOrEqualTo(1); + } + + private static void reportOwnedBuckets( + FlussSourceEnumerator enumerator, int reader, Map owners) { + Set buckets = + owners.entrySet().stream() + .filter(entry -> entry.getValue() == reader) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + enumerator.handleSourceEvent(reader, new ReaderSplitReportEvent(buckets)); + } + private FlussSourceEnumerator newEnumerator( MockSplitEnumeratorContext context, TableDiscoverer discoverer, @@ -2535,9 +3063,11 @@ private static Configuration buildSourceConfig( private static void registerAllReaders( MockSplitEnumeratorContext context, FlussSourceEnumerator enumerator) { - for (int readerId = 0; readerId < NUM_READERS; readerId++) { + for (int readerId = 0; readerId < context.currentParallelism(); readerId++) { context.registerReader(new ReaderInfo(readerId, "loc_" + readerId)); enumerator.addReader(readerId); + enumerator.handleSourceEvent( + readerId, new ReaderSplitReportEvent(Collections.emptySet())); } } @@ -2561,21 +3091,6 @@ private static void acknowledgePartitionRemoval( } } - private static int findParallelismWithDifferentOwner( - org.apache.fluss.metadata.TableBucket tableBucket, - int currentParallelism, - int currentOwner) { - for (int parallelism = currentParallelism + 1; - parallelism <= currentParallelism + 10; - parallelism++) { - if (FlussSourceEnumerator.getSplitOwner(tableBucket, parallelism) != currentOwner) { - return parallelism; - } - } - throw new IllegalStateException( - "Could not find a parallelism with a different split owner"); - } - /** * Drives one full discovery cycle: runs the periodic callable (phase 1 + 2) and, if new * table-buckets were discovered, the follow-up one-time callable (phase 3 + 4). diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReaderTest.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReaderTest.java index 3e3962597a3..97d6cebddae 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReaderTest.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/reader/FlussSourceReaderTest.java @@ -26,6 +26,7 @@ import org.apache.flink.cdc.connectors.fluss.sink.v2.metrics.WrapperFlussMetricRegistry; import org.apache.flink.cdc.connectors.fluss.source.deserializer.FlussRecordDeserializer; import org.apache.flink.cdc.connectors.fluss.source.event.FinishedKvSnapshotConsumeEvent; +import org.apache.flink.cdc.connectors.fluss.source.event.ReaderSplitReportEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableRemovalAckEvent; import org.apache.flink.cdc.connectors.fluss.source.event.TableSubscriptionEvent; import org.apache.flink.cdc.connectors.fluss.source.metrics.FlussSourceReaderMetrics; @@ -62,6 +63,68 @@ /** Tests for subscription-aware split handling in {@link FlussSourceReader}. */ class FlussSourceReaderTest { + @Test + void testReportsRestoredSplitsAtStartBeforeSubscription() throws Exception { + TestingReaderContext context = new TestingReaderContext(); + TrackingFetcherManager fetcher = + new TrackingFetcherManager(new FutureCompletingBlockingQueue<>()); + try (FlussSourceReader reader = + new FlussSourceReader<>( + context, + new WrapperFlussMetricRegistry( + context.metricGroup(), Collections.emptySet()), + new FlussRecordEmitter<>(new FlussRecordDeserializer()), + fetcher, + null)) { + FlussLogSplit split = testSplit(); + reader.addSplits(Collections.singletonList(split)); + reader.start(); + assertThat(fetcher.addedSplits).isEmpty(); + assertThat(context.getSentEvents()) + .singleElement() + .isInstanceOfSatisfying( + ReaderSplitReportEvent.class, + report -> { + assertThat(report.getBuckets()) + .containsExactly(split.getTableBucket()); + }); + + context.clearSentEvents(); + reader.handleSourceEvents( + new TableSubscriptionEvent( + Collections.singleton(split.getTablePath()), + Collections.emptyMap(), + Collections.emptySet(), + Collections.singleton(split.getPhysicalTablePath()))); + assertThat(fetcher.addedSplits).containsExactly(split); + assertThat(context.getSentEvents()).isEmpty(); + } + } + + @Test + void testEmptyReaderReportsAtStart() throws Exception { + TestingReaderContext context = new TestingReaderContext(); + try (FlussSourceReader reader = newReader(context)) { + reader.start(); + assertThat(context.getSentEvents()).hasSize(1); + TableSubscriptionEvent subscription = + new TableSubscriptionEvent( + Collections.emptySet(), + Collections.emptyMap(), + Collections.emptySet(), + Collections.emptySet()); + reader.handleSourceEvents(subscription); + reader.handleSourceEvents(subscription); + assertThat(context.getSentEvents()) + .singleElement() + .isInstanceOfSatisfying( + ReaderSplitReportEvent.class, + report -> { + assertThat(report.getBuckets()).isEmpty(); + }); + } + } + @Test void testStagesSplitUntilFirstSubscriptionSnapshotAndIncludesItInCheckpoint() throws Exception { TestingReaderContext readerContext = new TestingReaderContext(); From 1ca062fc0780e56d0de45996b886a455edd04b98 Mon Sep 17 00:00:00 2001 From: Hongshun Wang Date: Fri, 27 Nov 2026 17:03:05 +0800 Subject: [PATCH 2/3] [FLINK-41564][pipeline-connector/fluss] Preserve bucket ownership across reader restarts Retain logical bucket ownership across local reader restarts and defer owner selection until the initial distribution is known. Preserve initialized offsets and cover initialization around reader re-registration in tests. Generated-by: Codex CLI 0.167.2 AI-Model: gpt-6 AI-Contributed/Feature: 81/81 AI-Contributed/UT: 110/110 --- .../enumerator/FlussSourceEnumerator.java | 81 +++++++++---- .../enumerator/FlussSourceEnumeratorTest.java | 110 +++++++++++++++++- 2 files changed, 162 insertions(+), 29 deletions(-) diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java index 3f53abdf088..eae3a09d945 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java @@ -81,7 +81,9 @@ * *

Until this source adopts FLIP-537, a temporary reader-report protocol reconstructs bucket * ownership on startup. Discovery starts after every reader reports; restored splits remain with - * their readers. The ownership view is not added to checkpoint state. + * their readers. Ownership survives local reader restarts, and returned splits keep their original + * owners. Reports from known readers are ignored. The ownership view is not checkpointed and is + * rebuilt from reader reports when the enumerator is restored. * *

The enumeration follows a four-phase pattern: * @@ -93,8 +95,8 @@ * (callback). *

  • {@link #initPendingBucketSplits} — resolves starting offsets and creates splits for new * table-buckets (async). - *
  • {@link #handleTableBucketChanges} — marks physical table paths as assigned and distributes - * splits to readers (callback). + *
  • {@link #handleTableBucketChanges} — queues initialized splits for owner selection and + * assignment once all readers are ready (callback). * * *

    Tracking is done at {@link PhysicalTablePath} granularity (i.e. tablePath + partitionName), so @@ -120,10 +122,33 @@ public class FlussSourceEnumerator private final LeaseContext leaseContext; private final Set assignedPhysicalTablePaths; + + /** Splits awaiting delivery to selected owners, including splits returned to their owners. */ private final Map> pendingPartitionSplitAssignment; - // Select owners only after reader reports and the first discovery are available. - private final List restoredPendingSplits; + + /** Initialized or restored pending splits whose owners have not yet been selected. */ + private final List unassignedPendingSplits; + + /** + * Combines each reader's bucket ownership into an enumerator-wide view for load balancing. + * + *

    {@code
    +     * readerBuckets (global distribution)
    +     *   +-- reader 0 -> {bucket A, bucket B}
    +     *   +-- reader 1 -> {bucket C, bucket D}
    +     *   `-- reader 2 -> {bucket E, bucket F}
    +     * }
    + * + *

    Initial reports establish entries, new assignments add buckets, and discovery removes + * inactive buckets. Only bucket identities are tracked here; offsets remain in the splits. + * + *

    Entries survive local reader restarts because returned splits retain their owners. Later + * reports describe checkpoint-restored buckets and must not replace this maintained view. An + * absent entry means the reader's initial ownership is not yet known; an empty set means it has + * reported no buckets. + */ private final Map> readerBuckets = new HashMap<>(); + // Runtime-only cursors for new assignments; not part of checkpoint state. private final Map nextReaderIndex = new HashMap<>(); private boolean discoveryStarted; @@ -171,7 +196,7 @@ public FlussSourceEnumerator( this.leaseContext = leaseContext; this.assignedPhysicalTablePaths = assignedPhysicalTablePaths; this.pendingPartitionSplitAssignment = new HashMap<>(); - this.restoredPendingSplits = new ArrayList<>(remainingSplits); + this.unassignedPendingSplits = new ArrayList<>(remainingSplits); this.consumedKvSnapshotMap = new TreeMap<>(); this.subscribedTablePaths = new HashSet<>(); this.pendingRemovalTablePaths = new HashSet<>(); @@ -251,7 +276,7 @@ public void start() { } private void maybeStartDiscovery() { - if (admin == null || discoveryStarted || !allReadersReported()) { + if (admin == null || discoveryStarted || !allReadersReady()) { return; } discoveryStarted = true; @@ -271,7 +296,8 @@ private void maybeStartDiscovery() { } } - private boolean allReadersReported() { + /** All readers must be registered and their initial bucket ownership must be known. */ + private boolean allReadersReady() { return context.registeredReaders().size() == context.currentParallelism() && readerBuckets.keySet().containsAll(context.registeredReaders().keySet()); } @@ -366,7 +392,7 @@ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable .map(info -> info.tableBucket) .collect(Collectors.toSet()); readerBuckets.values().forEach(buckets -> buckets.retainAll(activeBuckets)); - restoredPendingSplits.removeIf(split -> !activeBuckets.contains(split.getTableBucket())); + unassignedPendingSplits.removeIf(split -> !activeBuckets.contains(split.getTableBucket())); if (!sentSubscriptionSnapshot || subscriptionChanged || bucketsChanged @@ -375,7 +401,7 @@ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable sentSubscriptionSnapshot = true; } - // Assign restored splits before initializing new ones to preserve their offsets. + // Assign initialized splits before initializing new ones to preserve their offsets. assignPendingPartitionSplits(); initializeNewTableBuckets(discoveryResult.tableBuckets); } @@ -383,7 +409,7 @@ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable private boolean removeExpiredPartitions() { Set removedPartitions = new HashSet<>(assignedPhysicalTablePaths); removedPartitions.addAll(initializingPhysicalTablePaths); - restoredPendingSplits.stream() + unassignedPendingSplits.stream() .map(FlussSplitBase::getPhysicalTablePath) .forEach(removedPartitions::add); pendingPartitionSplitAssignment.values().stream() @@ -453,12 +479,15 @@ private boolean hasRemovalFence(FlussSplitBase split) { } private void initializeNewTableBuckets(List allBuckets) { - if (!allReadersReported()) { + if (!allReadersReady()) { return; } Set knownPhysicalTablePaths = new HashSet<>(assignedPhysicalTablePaths); knownPhysicalTablePaths.addAll(initializingPhysicalTablePaths); + unassignedPendingSplits.stream() + .map(FlussSplitBase::getPhysicalTablePath) + .forEach(knownPhysicalTablePaths::add); pendingPartitionSplitAssignment.values().stream() .flatMap(Set::stream) .map(FlussSplitBase::getPhysicalTablePath) @@ -807,13 +836,10 @@ private static void validateBucketOffsets( } // ------------------------------------------------------------------------- - // Phase 4: Handle new splits — mark assigned and assign to readers (callback) + // Phase 4: Handle new splits — queue and assign when readers are ready (callback) // ------------------------------------------------------------------------- - /** - * Receives newly created splits, records their {@link PhysicalTablePath}s as assigned, and - * distributes the splits to registered readers. - */ + /** Receives initialized splits and queues them for assignment once all readers are ready. */ private void handleTableBucketChanges( List newSplits, Throwable error, @@ -871,7 +897,7 @@ && isCurrentPartitionBucket(info.tableBucket)) && isCurrentPartitionBucket(split.getTableBucket())) .collect(Collectors.toList()); if (!effectiveNewSplits.isEmpty()) { - addPartitionSplitChangeToPendingAssignments(effectiveNewSplits); + unassignedPendingSplits.addAll(effectiveNewSplits); assignPendingPartitionSplits(); } maybeClearRemovalTombstones(); @@ -947,8 +973,8 @@ private void addPartitionSplitChangeToPendingAssignments( // This method should only be invoked in the coordinator executor thread. private void assignPendingPartitionSplits() { if (!sentSubscriptionSnapshot - || (pendingPartitionSplitAssignment.isEmpty() && restoredPendingSplits.isEmpty()) - || !allReadersReported()) { + || (pendingPartitionSplitAssignment.isEmpty() && unassignedPendingSplits.isEmpty()) + || !allReadersReady()) { return; } Set discoveredBuckets = getDiscoveredBuckets(); @@ -960,8 +986,8 @@ private void assignPendingPartitionSplits() { split -> !discoveredBuckets.contains( split.getTableBucket()))); - addPartitionSplitChangeToPendingAssignments(restoredPendingSplits); - restoredPendingSplits.clear(); + addPartitionSplitChangeToPendingAssignments(unassignedPendingSplits); + unassignedPendingSplits.clear(); Map> incrementalAssignment = new HashMap<>(); for (int pendingReader : context.registeredReaders().keySet()) { @@ -1028,6 +1054,7 @@ public void handleSplitRequest(int subtaskId, @Nullable String requesterHostname public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) { if (sourceEvent instanceof ReaderSplitReportEvent) { checkReaderRegistered(subtaskId); + // Local restarts retain ownership, which may include assignments after the checkpoint. if (readerBuckets.containsKey(subtaskId)) { return; } @@ -1142,8 +1169,7 @@ && isCurrentPartitionBucket(split.getTableBucket()) @Override public void addReader(int subtaskId) { - LOG.info("Reader {} added, waiting for its split report.", subtaskId); - readerBuckets.remove(subtaskId); + LOG.info("Reader {} registered.", subtaskId); boolean restartedWithPendingRemoval = !seenReaderSubtasks.add(subtaskId) && (!pendingRemovalTablePaths.isEmpty() @@ -1177,6 +1203,11 @@ public void addReader(int subtaskId) { pendingPartitionRemovalRequests, partitionRemovalFences.keySet())); } + maybeStartDiscovery(); + assignPendingPartitionSplits(); + if (sentSubscriptionSnapshot) { + initializeNewTableBuckets(lastDiscoveredTableBuckets); + } } @Override @@ -1187,7 +1218,7 @@ public FlussSourceEnumState snapshotState(long checkpointId) throws Exception { partitionRemovalFences.replaceAll( (partitionPath, fenceCheckpointId) -> fenceCheckpointId < 0 ? checkpointId : fenceCheckpointId); - List remainingSplits = new ArrayList<>(restoredPendingSplits); + List remainingSplits = new ArrayList<>(unassignedPendingSplits); pendingPartitionSplitAssignment.forEach((reader, splits) -> remainingSplits.addAll(splits)); return new FlussSourceEnumState( assignedPhysicalTablePaths, diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java index 2d41b6bf619..1d82b5b0ade 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/test/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumeratorTest.java @@ -1200,7 +1200,7 @@ void testMultiplePeriodicDiscoveryRoundsBeforeInitDoNotDuplicateSplits() throws /** * Tests that initialization completing during a reader restart stays pending until the reader - * reports its restored splits, without losing or re-queuing splits. + * re-registers, without losing or re-queuing splits. */ @ParameterizedTest @CsvSource({"true", "false"}) @@ -1237,8 +1237,8 @@ void testPendingAssignmentSurvivesDiscoveryWhileReaderRestarts(boolean failsDuri context.registerReader(new ReaderInfo(0, "restarted_0")); enumerator.addReader(0); - assertThat(context.getSplitsAssignmentSequence()).isEmpty(); - enumerator.handleSourceEvent(0, new ReaderSplitReportEvent(Collections.emptySet())); + assertThat(context.getSplitsAssignmentSequence()) + .hasSize(failsDuringDiscovery ? 0 : 1); while (!context.getOneTimeCallables().isEmpty()) { context.runNextOneTimeCallable(); } @@ -1251,6 +1251,107 @@ void testPendingAssignmentSurvivesDiscoveryWhileReaderRestarts(boolean failsDuri } } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void testInitializationDuringLocalRestartUsesKnownBucketDistribution( + boolean initializationBeforeRegistration) throws Throwable { + String tableName = "init_before_restored_report"; + createPartitionedPkTable(tableName, 1); + TablePath tablePath = TablePath.of(DATABASE_NAME, tableName); + AtomicInteger offsetInitializationCount = new AtomicInteger(); + OffsetsInitializer offsetsInitializer = + (partitionName, bucketIds, retriever) -> { + long offset = 100L + offsetInitializationCount.incrementAndGet(); + return bucketIds.stream() + .collect(Collectors.toMap(bucket -> bucket, bucket -> offset)); + }; + + try (Connection connection = + ConnectionFactory.createConnection( + FLUSS_CLUSTER_EXTENSION.getClientConfig()); + MockSplitEnumeratorContext context = + new MockSplitEnumeratorContext<>(NUM_READERS)) { + Admin admin = connection.getAdmin(); + for (int partition = 0; partition < 16; partition++) { + createPartition(admin, tablePath, "old_" + partition); + } + FlussSourceEnumerator enumerator = + newEnumerator( + context, + new FlussDefaultDiscoverer(), + fqnRegex(DATABASE_NAME, tableName), + offsetsInitializer, + DISCOVERY_INTERVAL_MS); + try { + enumerator.start(); + registerAllReaders(context, enumerator); + runDiscoveryCycle(context); + Map restoredOwners = assignedOwners(context); + assertBalancedOwners(restoredOwners, NUM_READERS, 16); + + for (int partition = 0; partition < 4; partition++) { + createPartition(admin, tablePath, "new_" + partition); + } + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + assertThat(context.getOneTimeCallables()).hasSize(1); + context.unregisterReader(0); + List pendingSplits = Collections.emptyList(); + if (initializationBeforeRegistration) { + context.runNextOneTimeCallable(); + pendingSplits = enumerator.snapshotState(1L).getRemainingSplits(); + assertThat(pendingSplits).hasSize(4); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + assertThat(context.getOneTimeCallables()).isEmpty(); + assertThat(enumerator.snapshotState(2L).getRemainingSplits()) + .containsExactlyInAnyOrderElementsOf(pendingSplits); + } + assertThat(context.getSplitsAssignmentSequence()).hasSize(1); + context.registerReader(new ReaderInfo(0, "restarted_0")); + enumerator.addReader(0); + if (!initializationBeforeRegistration) { + context.runNextOneTimeCallable(); + } + + assertThat(context.getSplitsAssignmentSequence()).hasSize(2); + List newSplits = + context.getSplitsAssignmentSequence().get(1).assignment().values().stream() + .flatMap(List::stream) + .collect(Collectors.toList()); + assertThat(newSplits) + .hasSize(4) + .allSatisfy(split -> assertThat(split).isInstanceOf(FlussLogSplit.class)); + assertThat(newSplits) + .extracting(split -> ((FlussLogSplit) split).getStartingOffset()) + .containsExactlyInAnyOrder(117L, 118L, 119L, 120L); + if (initializationBeforeRegistration) { + assertThat(newSplits).containsExactlyInAnyOrderElementsOf(pendingSplits); + } + assertThat( + assignedOwners(context).values().stream() + .collect( + Collectors.groupingBy( + owner -> owner, Collectors.counting()))) + .containsEntry(0, 10L) + .containsEntry(1, 10L); + assertThat(enumerator.snapshotState(3L).getRemainingSplits()).isEmpty(); + + reportOwnedBuckets(enumerator, 0, restoredOwners); + context.runPeriodicCallable(DISCOVERY_CALLABLE_INDEX); + assertThat(context.getOneTimeCallables()).isEmpty(); + assertThat(context.getSplitsAssignmentSequence()).hasSize(2); + assertThat(offsetInitializationCount.get()).isEqualTo(20); + + createPartition(admin, tablePath, "after_report_0"); + createPartition(admin, tablePath, "after_report_1"); + runDiscoveryCycle(context); + assertBalancedOwners(assignedOwners(context), NUM_READERS, 22); + assertThat(offsetInitializationCount.get()).isEqualTo(22); + } finally { + enumerator.close(); + } + } + } + @ParameterizedTest(name = "discoveryBeforeDefaultChange = {0}") @ValueSource(booleans = {true, false}) void testPartitionBucketCountAfterTableDefaultChange(boolean discoveryBeforeDefaultChange) @@ -1638,7 +1739,7 @@ void testBalancesNewPartitionsUsingRestoredReaderReports( context.registerReader(new ReaderInfo(failedReader, "restarted")); enumerator.addReader(failedReader); assertThat(context.getSplitsAssignmentSequence()) - .hasSize(assignmentsBeforeRestart); + .hasSize(assignmentsBeforeRestart + 1); reportOwnedBuckets(enumerator, failedReader, restoredOwners); assertThat(context.getSplitsAssignmentSequence()) .hasSize(assignmentsBeforeRestart + 1); @@ -2013,6 +2114,7 @@ void testRestoredPendingSplitsWaitForReportsAndDiscovery(boolean readerRestarts) .containsExactlyInAnyOrder(pendingSplit, returnedSplit); context.registerReader(new ReaderInfo(originalOwner, "restarted")); enumerator.addReader(originalOwner); + assertThat(context.getSplitsAssignmentSequence()).hasSize(1); reportOwnedBuckets(enumerator, originalOwner, reportedOwners); } assertThat(context.getOneTimeCallables()).isEmpty(); From e8d8ad0a07b44b1dbb2cec8c8bc40c6f8ab90806 Mon Sep 17 00:00:00 2001 From: Hongshun Wang Date: Fri, 27 Nov 2026 17:05:20 +0800 Subject: [PATCH 3/3] improve javadoc Clarify logical bucket ownership, pending split states, and recovery contracts while removing repeated implementation details. Generated-by: Codex CLI 0.167.2 AI-Model: gpt-6 AI-Contributed/Feature: 94/94 AI-Contributed/UT: 0/0 --- .../enumerator/FlussSourceEnumerator.java | 94 +++++-------------- 1 file changed, 26 insertions(+), 68 deletions(-) diff --git a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java index eae3a09d945..3095be49053 100644 --- a/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java +++ b/flink-cdc-connect/flink-cdc-pipeline-connectors/flink-cdc-pipeline-connector-fluss/src/main/java/org/apache/flink/cdc/connectors/fluss/source/enumerator/FlussSourceEnumerator.java @@ -74,36 +74,17 @@ import java.util.stream.Collectors; /** - * The enumerator for Fluss source. It discovers tables using {@link TableDiscoverer}, queries their - * metadata (schema, bucket count, partitions), and generates {@link FlussSplitBase}s for each - * table-bucket pair, assigning new splits to readers with the fewest buckets of the same partition, - * then the same table. A per-table round-robin cursor breaks remaining ties. + * Discovers Fluss table-buckets and assigns new splits to readers with the fewest buckets of the + * same partition, then the same table. A per-table round-robin cursor breaks remaining ties. * - *

    Until this source adopts FLIP-537, a temporary reader-report protocol reconstructs bucket - * ownership on startup. Discovery starts after every reader reports; restored splits remain with - * their readers. Ownership survives local reader restarts, and returned splits keep their original - * owners. Reports from known readers are ignored. The ownership view is not checkpointed and is - * rebuilt from reader reports when the enumerator is restored. + *

    Until this source adopts FLIP-537, reader reports establish the initial bucket ownership view. + * New owners are selected only after all readers are registered, their initial reports are + * available, and the first discovery has removed inactive buckets from the view. * - *

    The enumeration follows a four-phase pattern: - * - *

      - *
    1. {@link #getSubscribedTableBuckets()} — discovers subscribed tables and enumerates all - * table-buckets including partitions (async). - *
    2. {@link #checkTableBucketChanges} — compares discovered table-buckets with assigned, - * pending, and initializing ones and triggers split creation for new table-buckets - * (callback). - *
    3. {@link #initPendingBucketSplits} — resolves starting offsets and creates splits for new - * table-buckets (async). - *
    4. {@link #handleTableBucketChanges} — queues initialized splits for owner selection and - * assignment once all readers are ready (callback). - *
    - * - *

    Tracking is done at {@link PhysicalTablePath} granularity (i.e. tablePath + partitionName), so - * newly created partitions of an already-known table will be discovered and assigned. - * - *

    The starting offsets for each bucket are resolved via the {@link OffsetsInitializer}, which - * supports earliest, latest, and timestamp-based initialization strategies. + *

    Local reader restarts retain this view, and returned splits keep their original owners. The + * view is not checkpointed: enumerator recovery rebuilds it from reader reports. Splits restored by + * readers stay with them; pending splits are checkpointed without owners and reassigned with their + * existing offsets. */ public class FlussSourceEnumerator implements SplitEnumerator { @@ -123,29 +104,28 @@ public class FlussSourceEnumerator private final Set assignedPhysicalTablePaths; - /** Splits awaiting delivery to selected owners, including splits returned to their owners. */ + /** + * Splits with selected owners awaiting delivery, including splits returned to their original + * owners by {@link #addSplitsBack(List, int)}. + */ private final Map> pendingPartitionSplitAssignment; - /** Initialized or restored pending splits whose owners have not yet been selected. */ + /** + * Initialized or restored pending splits awaiting owner selection. Assignment must preserve + * their existing offsets. + */ private final List unassignedPendingSplits; /** - * Combines each reader's bucket ownership into an enumerator-wide view for load balancing. - * - *

    {@code
    -     * readerBuckets (global distribution)
    -     *   +-- reader 0 -> {bucket A, bucket B}
    -     *   +-- reader 1 -> {bucket C, bucket D}
    -     *   `-- reader 2 -> {bucket E, bucket F}
    -     * }
    + * Global logical bucket ownership used for load balancing; it can differ from the buckets + * currently held by online readers. * - *

    Initial reports establish entries, new assignments add buckets, and discovery removes - * inactive buckets. Only bucket identities are tracked here; offsets remain in the splits. + *

    Within this enumerator instance, each reader's first report establishes its entry. + * Assignments add buckets and discovery removes inactive buckets. Registration does not clear + * entries; later reports must not overwrite ownership maintained since the checkpoint. * - *

    Entries survive local reader restarts because returned splits retain their owners. Later - * reports describe checkpoint-restored buckets and must not replace this maintained view. An - * absent entry means the reader's initial ownership is not yet known; an empty set means it has - * reported no buckets. + *

    An absent entry means no initial report has been received; an empty set is a known + * ownership view with no active buckets. */ private final Map> readerBuckets = new HashMap<>(); @@ -306,13 +286,6 @@ private boolean allReadersReady() { // Phase 1: Discover subscribed table-buckets (runs async) // ------------------------------------------------------------------------- - /** - * Discovers all subscribed tables via the {@link TableDiscoverer}, then queries their metadata - * (bucket count, partitions) and enumerates every individual table-bucket. For partitioned - * tables, each partition contributes its own set of buckets. - * - * @return the full list of discovered table-bucket entries. - */ private DiscoveryResult getSubscribedTableBuckets() throws Exception { List allBuckets = new ArrayList<>(); Set discoveredTableIds = discoverer.discover(); @@ -357,10 +330,6 @@ private DiscoveryResult getSubscribedTableBuckets() throws Exception { // Phase 2: Check for table-bucket changes (callback) // ------------------------------------------------------------------------- - /** - * Compares the discovered table-buckets against assigned, pending, and initializing {@link - * PhysicalTablePath}s and triggers split creation for newly discovered table-buckets. - */ private void checkTableBucketChanges(DiscoveryResult discoveryResult, Throwable error) { if (error != null) { throw new FlinkRuntimeException("Failed to discover subscribed table-buckets.", error); @@ -626,15 +595,6 @@ private void maybeClearRemovalTombstones() { // Phase 3: Create pending splits for new table-buckets (runs async) // ------------------------------------------------------------------------- - /** - * Groups the new table-buckets by {@link TablePath} (for the {@link BucketOffsetsRetrieverImpl} - * instance) and then by partition name (for batch offset resolution via the {@link - * OffsetsInitializer}), and creates {@link FlussSplitBase} instances. - * - *

    For primary key tables with {@link SnapshotOffsetsInitializer} ("full" startup mode), KV - * snapshots are retrieved: buckets with a snapshot get a {@link FlussHybridSnapshotLogSplit}, - * buckets without a snapshot fall back to a {@link FlussLogSplit}. - */ private List initPendingBucketSplits(List newBuckets) throws Exception { List newSplits = new ArrayList<>(); @@ -685,9 +645,8 @@ private List initPendingBucketSplits(List newBu } /** - * Creates splits for primary key table buckets in "full" startup mode. Retrieves KV snapshots - * and creates {@link FlussHybridSnapshotLogSplit} for buckets with a snapshot, and falls back - * to {@link FlussLogSplit} for buckets without a snapshot. + * Primary key buckets in "full" startup mode use hybrid splits when a KV snapshot exists and + * fall back to log-only splits otherwise. */ private List initHybridSnapshotLogSplits( TablePath tablePath, @@ -839,7 +798,6 @@ private static void validateBucketOffsets( // Phase 4: Handle new splits — queue and assign when readers are ready (callback) // ------------------------------------------------------------------------- - /** Receives initialized splits and queues them for assignment once all readers are ready. */ private void handleTableBucketChanges( List newSplits, Throwable error,