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 @@ -40,12 +40,15 @@ public class WriterSafeFrontierTracker {

private final Map<Integer, WriterFrontierState> states = new HashMap<>();
private volatile long effectiveSafePtVersion;
private volatile long safeFrontierVersion;

public synchronized void recordAppliedProgress(
final long physicalTime, final int writerNodeId, final long appliedLocalSeq) {
final WriterFrontierState state =
states.computeIfAbsent(writerNodeId, ignored -> new WriterFrontierState());
state.appliedLocalSeq = Math.max(state.appliedLocalSeq, appliedLocalSeq);
final WriterFrontierState state = getOrCreateWriterState(writerNodeId);
if (appliedLocalSeq > state.appliedLocalSeq) {
state.appliedLocalSeq = appliedLocalSeq;
safeFrontierVersion++;
}
long effectiveSafePt = Math.max(state.effectiveSafePt, physicalTime);
if (state.hasPendingSafeTime() && state.appliedLocalSeq >= state.pendingSafeLocalSeq) {
effectiveSafePt = Math.max(effectiveSafePt, state.pendingSafePhysicalTime);
Expand All @@ -59,8 +62,7 @@ public synchronized void observePendingWriterSafeTimeBarrier(
if (safePhysicalTime <= 0) {
return;
}
final WriterFrontierState state =
states.computeIfAbsent(writerNodeId, ignored -> new WriterFrontierState());
final WriterFrontierState state = getOrCreateWriterState(writerNodeId);
if (state.appliedLocalSeq >= barrierLocalSeq) {
advanceEffectiveSafePt(state, safePhysicalTime);
state.clearPendingSafeTime();
Expand Down Expand Up @@ -122,11 +124,26 @@ public long getEffectiveSafePtVersion() {
return effectiveSafePtVersion;
}

public long getSafeFrontierVersion() {
return safeFrontierVersion;
}

private WriterFrontierState getOrCreateWriterState(final int writerNodeId) {
WriterFrontierState state = states.get(writerNodeId);
if (state == null) {
state = new WriterFrontierState();
states.put(writerNodeId, state);
safeFrontierVersion++;
}
return state;
}

private void advanceEffectiveSafePt(
final WriterFrontierState state, final long safePhysicalTime) {
if (safePhysicalTime > state.effectiveSafePt) {
state.effectiveSafePt = safePhysicalTime;
effectiveSafePtVersion++;
safeFrontierVersion++;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class WriterSafeFrontierTrackerTest {

Expand Down Expand Up @@ -94,4 +95,26 @@ public void testEffectiveSafePtSnapshotIncludesAtomicVersion() {
assertEquals(2L, snapshot.getVersion());
assertEquals(Long.valueOf(250L), snapshot.getEffectiveSafePts().get(9));
}

@Test
public void testSafeFrontierVersionTracksSnapshotChanges() {
final WriterSafeFrontierTracker tracker = new WriterSafeFrontierTracker();
final long initialVersion = tracker.getSafeFrontierVersion();

tracker.observePendingWriterSafeTimeBarrier(200L, 9, 30L);
final long afterWriterRegistration = tracker.getSafeFrontierVersion();
assertTrue(afterWriterRegistration > initialVersion);

tracker.recordAppliedProgress(150L, 9, 29L);
final long afterAppliedProgress = tracker.getSafeFrontierVersion();
assertTrue(afterAppliedProgress > afterWriterRegistration);
assertEquals(29L, tracker.snapshotSafeFrontiers().get(9).getLocalSeq());

tracker.recordAppliedProgress(150L, 9, 29L);
assertEquals(afterAppliedProgress, tracker.getSafeFrontierVersion());

tracker.recordAppliedProgress(150L, 9, 30L);
assertTrue(tracker.getSafeFrontierVersion() > afterAppliedProgress);
assertEquals(200L, tracker.snapshotSafeFrontiers().get(9).getPhysicalTime());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,8 @@ public class ConsensusPrefetchingQueue {
// converting or retaining their Tablets, so a long writer prefix cannot exhaust the memory
// needed to find an older record from another writer.
private final Map<Integer, WriterReplayState> orderedWriterReplay = new ConcurrentHashMap<>();
private Map<Integer, SafeFrontier> safeFrontierSnapshot;
private long safeFrontierSnapshotVersion = Long.MIN_VALUE;
private long orderedReplayStartSearchIndex = Long.MIN_VALUE;
private int orderedWriterRoundRobinStart;
private final AtomicLong orderedRequestBytes = new AtomicLong();
Expand Down Expand Up @@ -2111,12 +2113,9 @@ private PrefetchRoundResult driveOrderedWriterReplay(
lingerBatch.reset();
}
}
final Map<Integer, SafeFrontier> safeFrontiers =
serverImpl.getWriterSafeFrontierTracker().snapshotSafeFrontiers();
for (final int writerNodeId : replayActiveWriterNodeIds) {
getOrCreateWriterReplay(writerNodeId).wasRuntimeActive = true;
}
safeFrontiers.keySet().forEach(this::getOrCreateWriterReplay);
final Map<Integer, SafeFrontier> initialSafeFrontiers = refreshSafeFrontierSnapshot();
replayActiveWriterNodeIds.forEach(this::getOrCreateWriterReplay);
initialSafeFrontiers.keySet().forEach(this::getOrCreateWriterReplay);
recoveryWriterProgressByWriter.keySet().forEach(id -> getOrCreateWriterReplay(id.getNodeId()));
realtimeEntriesByWriter.keySet().forEach(this::getOrCreateWriterReplay);
for (final IndexedConsensusRequest request : pendingEntries) {
Expand Down Expand Up @@ -2150,6 +2149,13 @@ private PrefetchRoundResult driveOrderedWriterReplay(
if (orderedWriterReplay.size() != writerCount && remainingEntryBudget[0] > 0) {
continue;
}
final Map<Integer, SafeFrontier> safeFrontiers = refreshSafeFrontierSnapshot();
final int writerCountBeforeFrontierRefresh = orderedWriterReplay.size();
safeFrontiers.keySet().forEach(this::getOrCreateWriterReplay);
if (orderedWriterReplay.size() != writerCountBeforeFrontierRefresh
&& remainingEntryBudget[0] > 0) {
continue;
}
if (replayActiveWriterNodeIds != activeWriterNodeIds) {
return PrefetchRoundResult.rescheduleNow();
}
Expand All @@ -2175,7 +2181,7 @@ private PrefetchRoundResult driveOrderedWriterReplay(
Objects.nonNull(safe) && state.consumedLocalSeq < safe.getLocalSeq();
if (!isWriterRuntimeActive(replayActiveWriterNodeIds, writerNodeId)
&& state.caughtUp
&& !(state.wasRuntimeActive && hasUnreadAppliedProgress)) {
&& !hasUnreadAppliedProgress) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java:2184 — Retired writer with unreachable applied frontier blocks ordered replay forever

The skip decision now also holds a Long.MIN_VALUE barrier for non-runtime-active writers while state.consumedLocalSeq < safe.getLocalSeq(), but consumedLocalSeq only grows by reading that writer's WAL records. When those records are no longer readable (WAL pruned by getSafelyDeletedSearchIndex / topic retention, or broken files), the retired writer blocks every other writer's head permanently; the previous !(state.wasRuntimeActive && hasUnreadAppliedProgress) form skipped these caught-up write
…[truncated]

Fix: Only hold the applied-frontier barrier while the missing sequence is still replayable: skip the writer (or fall back to its safe time) once its applied seq cannot be reached from the readable WAL, e.g. compare against the per-writer tail/recovery pro
…[truncated]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not apply the suggested local WAL-tail comparison. A local WAL search position is not a verified upper bound for a remote writer localSeq, and a read error cannot distinguish temporary visibility delay from permanent loss; using either to release the barrier could skip a delayed record and violate ordering. This case needs an authoritative per-writer replayability/retention watermark or a handoff guarantee that the retired writer can no longer apply records. Is there an existing source for that guarantee? I am leaving this thread open pending that invariant.

continue;
}
final long safePt =
Expand All @@ -2185,6 +2191,10 @@ private PrefetchRoundResult driveOrderedWriterReplay(
frontiers.add(WriterFrontier.forBarrier(writerNodeId, safePt));
}
}
if (safeFrontierSnapshotVersion

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java:2194 — Frontier-version guard aborts the whole delivery round on any concurrent applied progress

safeFrontierVersion is bumped by every applied record on the write path (IoTConsensusServerImpl.recordAppliedProgress:354). The guard runs once per emitted entry and on any bump discards the selection and returns RESCHEDULE_LATER(100ms) even when every frontier is a plain head and no retired-writer release used the snapshot, so a region with active ingestion drops rounds (no entry delivered, no linger flush) whenever progress advances inside the decision window.

Fix: Re-refresh the snapshot and continue the loop as drainWriterEntries does at lines 4015-4023 instead of returning a 100ms delayed reschedule, and only apply this guard when a retired-writer release was decided from the snapshot.

!= serverImpl.getWriterSafeFrontierTracker().getSafeFrontierVersion()) {
return PrefetchRoundResult.rescheduleAfter(WRITER_BARRIER_RETRY_SLEEP_MS);
}
final WriterFrontier next = frontiers.peek();
if (Objects.isNull(next) || next.isBarrier) {
lastBlockedWriterFrontier = next;
Expand Down Expand Up @@ -2312,6 +2322,16 @@ private WriterReplayState getOrCreateWriterReplay(final int writerNodeId) {
});
}

private Map<Integer, SafeFrontier> refreshSafeFrontierSnapshot() {
final WriterSafeFrontierTracker tracker = serverImpl.getWriterSafeFrontierTracker();
final long version = tracker.getSafeFrontierVersion();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java:2327 — Cached safe-frontier version is read before the snapshot copy, so the stamp always lags the data

getSafeFrontierVersion() is read outside the monitor before the synchronized snapshotSafeFrontiers() copy, so safeFrontierSnapshotVersion is at most the copy's version. A bump during the copy leaves the returned map already holding the newer progress while the stamp lags, which forces a spurious re-copy on the next call and a guaranteed mismatch at the line 2194 guard (which then aborts the round).

Fix: Capture the version and copy the states under the same monitor, as snapshotEffectiveSafePtsWithVersion() does, and stamp the copy with that atomically read version.

if (Objects.isNull(safeFrontierSnapshot) || safeFrontierSnapshotVersion != version) {
safeFrontierSnapshot = tracker.snapshotSafeFrontiers();
safeFrontierSnapshotVersion = version;
}
return safeFrontierSnapshot;
}

private boolean fillOrderedWriterHead(
final int writerNodeId,
final WriterReplayState state,
Expand Down Expand Up @@ -2460,7 +2480,6 @@ private static final class WriterReplayState {
private IndexedConsensusRequest head;
private boolean fromPending;
private boolean caughtUp;
private boolean wasRuntimeActive;

private WriterReplayState(final ProgressWALIterator iterator, final long consumedLocalSeq) {
this.iterator = iterator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public class ConsensusPrefetchingQueueWriterOrderingTest {
private int originalWalEntries;
private int originalTablets;
private int originalDelay;
private final WriterSafeFrontierTracker tracker = new WriterSafeFrontierTracker();
private final WriterSafeFrontierTracker tracker = spy(new WriterSafeFrontierTracker());
private final AtomicInteger conversions = new AtomicInteger();
private final AtomicInteger walReads = new AtomicInteger();
private ConsensusPrefetchingQueue queue;
Expand Down Expand Up @@ -343,6 +343,87 @@ public void testLeaderOnlyReplayKeepsPreviousWriterWhenSafeTimeIsUnavailable() t
assertEquals(Set.of(1, 5), queue.getActiveWriterNodeIds());
}

@Test
public void testLeaderOnlyReplayWaitsForUnreadRetiredWriterUntilWalVisibility() throws Exception {
final File directory = temporaryFolder.newFolder("leader-only-unseen-writer-wal");
newQueue(walNode(directory, 1), 1024 * 1024, TopicConstant.ORDER_MODE_LEADER_ONLY_VALUE);
queue.applyRuntimeState(new ConsensusRegionRuntimeState(2, 5, true, Set.of(1, 5, 7)));
queue.applyRuntimeState(new ConsensusRegionRuntimeState(3, 1, true, Set.of(1, 5, 7)));
tracker.recordAppliedProgress(0, 5, 0);
tracker.observePendingWriterSafeTimeBarrier(3000, 1, 0);
assertEquals(Set.of(1, 5), queue.getActiveWriterNodeIds());
assertTrue(pending().offer(request(1, 1, 2000)));

queue.drivePrefetchOnce();
assertEquals(0, conversions.get());
assertNull(queue.poll("consumer"));

queue.applyRuntimeState(ConsensusRegionRuntimeState.leaderOnly(4, 1, true));
assertEquals(Set.of(1), queue.getActiveWriterNodeIds());
final AtomicInteger safeFrontierSnapshots = new AtomicInteger();
doAnswer(
invocation -> {
final int snapshot = safeFrontierSnapshots.getAndIncrement();
final Object result = invocation.callRealMethod();
if (snapshot == 0) {
tracker.recordAppliedProgress(5000, 1, 0);
} else if (snapshot == 1) {
tracker.recordAppliedProgress(0, 5, 1);
}
return result;
})
.when(tracker)
.snapshotSafeFrontiers();
tracker.recordAppliedProgress(4000, 1, 0);

for (int round = 0; round < 10; round++) {
assertEquals(PrefetchRoundResult.Type.RESCHEDULE_LATER, queue.drivePrefetchOnce().getType());
}
assertEquals(3, safeFrontierSnapshots.get());
assertEquals(0, conversions.get());
assertEquals(0L, queue.getRetainedTabletBytes());
assertNull(queue.poll("consumer"));

final File data =
new File(directory, WALFileUtils.getLogFileName(0, 0, WALFileStatus.CONTAINS_SEARCH_INDEX));
try (WALWriter writer = new WALWriter(data, WALFileVersion.V3)) {
writeEntry(writer, -1, 5, 1000, 1);
}
try (WALWriter ignored =
new WALWriter(
new File(
directory, WALFileUtils.getLogFileName(1, 1, WALFileStatus.CONTAINS_SEARCH_INDEX)),
WALFileVersion.V3)) {}
queue.drivePrefetchOnce();

assertEvent(5, 1000);
assertEvent(1, 2000);
assertNull(queue.poll("consumer"));
assertEquals(2, conversions.get());
}

@Test
public void testLeaderOnlyReplayReleasesRetiredCaughtUpWriterWithoutSafeTime() throws Exception {
newQueue(
mock(ConsensusReqReader.class), 1024 * 1024, TopicConstant.ORDER_MODE_LEADER_ONLY_VALUE);
queue.applyRuntimeState(new ConsensusRegionRuntimeState(2, 5, true, Set.of(1, 5)));
queue.applyRuntimeState(new ConsensusRegionRuntimeState(3, 1, true, Set.of(1, 5)));
tracker.recordAppliedProgress(0, 5, 0);
assertTrue(pending().offer(request(1, 1, 2000)));

queue.drivePrefetchOnce();
assertNull(queue.poll("consumer"));
assertEquals(0, conversions.get());

queue.applyRuntimeState(ConsensusRegionRuntimeState.leaderOnly(4, 1, true));
queue.drivePrefetchOnce();

assertEvent(1, 2000);
assertNull(queue.poll("consumer"));
assertEquals(1, conversions.get());
assertEquals(Set.of(1), queue.getActiveWriterNodeIds());
}

@Test
public void testDefaultPendingBatchBoundaryKeepsWriterOrdering() throws Exception {
config.setSubscriptionConsensusBatchMaxDelayInMs(50);
Expand Down