Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,20 @@ public SourceReader<SeaTunnelRow, CheckpointableSequenceSplit> createReader(
return new CheckpointableSequenceSourceReader(
readerContext,
config.get(CheckpointableSequenceSourceFactory.RECORDS_PER_POLL),
config.get(CheckpointableSequenceSourceFactory.EMIT_INTERVAL_MS));
config.get(CheckpointableSequenceSourceFactory.EMIT_INTERVAL_MS),
config.get(CheckpointableSequenceSourceFactory.PAUSE_AFTER_OFFSETS_PER_SPLIT),
config.get(CheckpointableSequenceSourceFactory.RESUME_FILE));
}

@Override
public SourceSplitEnumerator<CheckpointableSequenceSplit, CheckpointableSequenceState>
createEnumerator(
SourceSplitEnumerator.Context<CheckpointableSequenceSplit> enumeratorContext) {
return new CheckpointableSequenceSplitEnumerator(
enumeratorContext, createInitialSplits(), false);
enumeratorContext,
createInitialSplits(),
false,
config.get(CheckpointableSequenceSourceFactory.ONE_SPLIT_PER_READER));
}

@Override
Expand All @@ -109,7 +114,8 @@ public SourceReader<SeaTunnelRow, CheckpointableSequenceSplit> createReader(
return new CheckpointableSequenceSplitEnumerator(
enumeratorContext,
checkpointState.getPendingSplits(),
checkpointState.getPendingSplits().isEmpty());
checkpointState.getPendingSplits().isEmpty(),
config.get(CheckpointableSequenceSourceFactory.ONE_SPLIT_PER_READER));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,51 @@ public class CheckpointableSequenceSourceFactory implements TableSourceFactory {
public static final Option<Long> EMIT_INTERVAL_MS =
Options.key("emit_interval_ms").longType().defaultValue(50L);

/**
* When enabled, the enumerator hands at most one split to each reader instead of draining the
* whole pending queue into the first reader that registers.
*
* <p>The default keeps the historical behaviour so existing fixtures and tests are unaffected.
* The per-reader mode exists so tests can give every parallel reader its own checkpoint state:
* with the default mode a single reader owns all splits and the other subtasks checkpoint an
* empty state, which cannot exercise per-subtask state restoration.
*/
public static final Option<Boolean> ONE_SPLIT_PER_READER =
Options.key("one_split_per_reader")
.booleanType()
.defaultValue(false)
.withDescription(
"Assign at most one split to every source reader instead of assigning all pending splits to the first registered reader");

/**
* When set to a non-negative value, every reader stops emitting as soon as its own split has
* advanced this many offsets from the split's start and keeps polling without emitting until
* the file named by {@link #RESUME_FILE} exists.
*
* <p>This turns "the job is interrupted in the middle of its input" into a controlled
* precondition: the readers park at a known, non-terminal offset of their own split instead of
* racing to the end of a finite range while the test prepares the savepoint. The historical
* default {@code -1} keeps the fixture emitting without a gate.
*/
public static final Option<Long> PAUSE_AFTER_OFFSETS_PER_SPLIT =
Options.key("pause_after_offsets_per_split")
.longType()
.defaultValue(-1L)
.withDescription(
"Stop emitting after every split advanced this many offsets and resume once resume_file exists; negative disables the gate");

/**
* Path of the file that releases {@link #PAUSE_AFTER_OFFSETS_PER_SPLIT}. The gate is open when
* this option is empty, and also when the file already exists, so a restored run whose split
* state is past the pause offset never parks again.
*/
public static final Option<String> RESUME_FILE =
Options.key("resume_file")
.stringType()
.defaultValue("")
.withDescription(
"File whose creation releases a reader paused by pause_after_offsets_per_split");

@Override
public String factoryIdentifier() {
return "CheckpointableSequenceSource";
Expand All @@ -57,7 +102,15 @@ public String factoryIdentifier() {
@Override
public OptionRule optionRule() {
return OptionRule.builder()
.optional(START_OFFSET, END_OFFSET, SPLIT_NUM, RECORDS_PER_POLL, EMIT_INTERVAL_MS)
.optional(
START_OFFSET,
END_OFFSET,
SPLIT_NUM,
RECORDS_PER_POLL,
EMIT_INTERVAL_MS,
ONE_SPLIT_PER_READER,
PAUSE_AFTER_OFFSETS_PER_SPLIT,
RESUME_FILE)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.apache.seatunnel.api.source.SourceReader;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
Expand All @@ -33,13 +35,29 @@ public class CheckpointableSequenceSourceReader
private final Context context;
private final int recordsPerPoll;
private final long emitIntervalMs;
/** Offsets a split may advance before the reader parks; negative keeps the historical mode. */
private final long pauseAfterOffsetsPerSplit;
/** File whose existence opens the progress gate; empty means the gate is never closed. */
private final String resumeFile;

private volatile boolean noMoreSplits;

public CheckpointableSequenceSourceReader(
Context context, int recordsPerPoll, long emitIntervalMs) {
this(context, recordsPerPoll, emitIntervalMs, -1L, "");
}

public CheckpointableSequenceSourceReader(
Context context,
int recordsPerPoll,
long emitIntervalMs,
long pauseAfterOffsetsPerSplit,
String resumeFile) {
this.context = context;
this.recordsPerPoll = recordsPerPoll;
this.emitIntervalMs = emitIntervalMs;
this.pauseAfterOffsetsPerSplit = pauseAfterOffsetsPerSplit;
this.resumeFile = resumeFile == null ? "" : resumeFile;
}

@Override
Expand All @@ -50,6 +68,15 @@ public void close() {}

@Override
public void pollNext(Collector<SeaTunnelRow> output) throws Exception {
if (progressGateClosed()) {
// The gate is checked and honoured outside the checkpoint lock on purpose. A paused
// reader must keep returning from pollNext without emitting: blocking inside the
// checkpoint lock would prevent the barrier injector from snapshotting this reader's
// parked split state, so the savepoint that the pause is meant to make partial could
// never complete. Sleeping one poll interval also keeps cancellation responsive.
Thread.sleep(Math.max(emitIntervalMs, 10L));
return;
}
synchronized (output.getCheckpointLock()) {
CheckpointableSequenceSplit split = activeSplits.poll();
if (split == null) {
Expand Down Expand Up @@ -77,6 +104,29 @@ public void pollNext(Collector<SeaTunnelRow> output) throws Exception {
}
}

/**
* Tells whether this reader has advanced its current split to the configured pause boundary and
* the resume file that releases the gate does not exist yet.
*
* <p>The gate is owned by the test fixture, so the pause point is a deterministic offset of
* every split instead of a wall-clock guess about how far a reader happened to get. A split
* that has no data left keeps the gate open so a misconfigured pause point can never park a
* reader forever, and an already created resume file keeps it open across a restore.
*/
private boolean progressGateClosed() {
if (pauseAfterOffsetsPerSplit < 0L) {
return false;
}
CheckpointableSequenceSplit split = activeSplits.peekFirst();
if (split == null || !split.hasRemaining()) {
return false;
}
if (split.getNextOffset() - split.getStartOffset() < pauseAfterOffsetsPerSplit) {
return false;
}
return resumeFile.isEmpty() || !Files.exists(Paths.get(resumeFile));
}

@Override
public List<CheckpointableSequenceSplit> snapshotState(long checkpointId) throws Exception {
return new ArrayList<>(activeSplits);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

Expand All @@ -33,15 +34,29 @@ public class CheckpointableSequenceSplitEnumerator
private final Context<CheckpointableSequenceSplit> context;
private final Deque<CheckpointableSequenceSplit> pendingSplits;
private final Set<Integer> registeredReaders = ConcurrentHashMap.newKeySet();
/** Splits a reader handed back to the enumerator during restore, keyed by reader index. */
private final Map<Integer, Deque<CheckpointableSequenceSplit>> returnedSplits =
new ConcurrentHashMap<>();

private final boolean oneSplitPerReader;
private volatile boolean awaitingRestoredSplits;

public CheckpointableSequenceSplitEnumerator(
Context<CheckpointableSequenceSplit> context,
List<CheckpointableSequenceSplit> pendingSplits,
boolean awaitingRestoredSplits) {
this(context, pendingSplits, awaitingRestoredSplits, false);
}

public CheckpointableSequenceSplitEnumerator(
Context<CheckpointableSequenceSplit> context,
List<CheckpointableSequenceSplit> pendingSplits,
boolean awaitingRestoredSplits,
boolean oneSplitPerReader) {
this.context = context;
this.pendingSplits = new ArrayDeque<>(pendingSplits);
this.awaitingRestoredSplits = awaitingRestoredSplits;
this.oneSplitPerReader = oneSplitPerReader;
}

@Override
Expand All @@ -56,6 +71,18 @@ public void close() throws IOException {}
@Override
public void addSplitsBack(List<CheckpointableSequenceSplit> splits, int subtaskId) {
awaitingRestoredSplits = false;
if (oneSplitPerReader) {
// A restored reader hands its own splits back through this method before it registers
// with the enumerator. Hold them until that reader registers (or hand them over
// immediately if it already has) instead of pushing them through the one-split
// distribution below, which would either drop them or give them to another reader.
returnedSplits.computeIfAbsent(subtaskId, reader -> new ArrayDeque<>()).addAll(splits);
if (registeredReaders.contains(subtaskId)) {
assignPendingSplits(subtaskId);
}
signalNoMoreSplitsWhenDrained();
return;
}
for (CheckpointableSequenceSplit split : splits) {
pendingSplits.addFirst(split);
}
Expand Down Expand Up @@ -90,11 +117,46 @@ private void assignPendingSplits(int subtaskId) {
if (!registeredReaders.contains(subtaskId)) {
return;
}
if (oneSplitPerReader) {
// A reader that already registered during a restore gets back exactly the splits it
// handed over; a freshly registered reader takes one split from the pending queue, so
// two readers end up owning one split each instead of the first reader draining all.
Deque<CheckpointableSequenceSplit> returned = returnedSplits.get(subtaskId);
CheckpointableSequenceSplit split;
boolean assigned = false;
while (returned != null && (split = returned.pollFirst()) != null) {
context.assignSplit(subtaskId, split);
assigned = true;
}
if (!assigned && !pendingSplits.isEmpty()) {
context.assignSplit(subtaskId, pendingSplits.pollFirst());
}
signalNoMoreSplitsWhenDrained();
return;
}
while (!pendingSplits.isEmpty()) {
context.assignSplit(subtaskId, pendingSplits.pollFirst());
}
if (!awaitingRestoredSplits) {
context.signalNoMoreSplits(subtaskId);
}
}

private void signalNoMoreSplitsWhenDrained() {
if (awaitingRestoredSplits || !pendingSplits.isEmpty() || hasReturnedSplits()) {
return;
}
for (Integer reader : registeredReaders) {
context.signalNoMoreSplits(reader);
}
}

private boolean hasReturnedSplits() {
for (Deque<CheckpointableSequenceSplit> splits : returnedSplits.values()) {
if (!splits.isEmpty()) {
return true;
}
}
return false;
}
}
Loading