Skip to content

[Subscription] Unblock replay after leader-only writer handoff - #19450

Open
Caideyipi wants to merge 2 commits into
masterfrom
fix/retired-writer-safe-frontier
Open

Caideyipi wants to merge 2 commits into
masterfrom
fix/retired-writer-safe-frontier

Conversation

@Caideyipi

Copy link
Copy Markdown
Collaborator

Summary

  • Refresh safe-frontier snapshots after WAL scanning and initialize replay state for newly observed writers, so newly applied progress is not missed by the ordering decision.
  • Release a retired writer's barrier only after replay is caught up and its consumed local sequence covers the applied frontier.

Example

Before: preferred writer 1 has an entry at physical time 2000, while retired writer 5 has applied local sequence 1 at physical time 1000 but that record is not yet visible to WAL replay. Writer 1 must remain blocked until writer 5's record becomes visible and is delivered first. Conversely, once writer 5 is caught up with no unread applied progress and no usable safe time, it must not block writer 1 indefinitely.

After: the queue keeps the barrier while writer 5's applied sequence is unread, then delivers writer 5 before writer 1 when the WAL record appears; it releases the barrier when the retired writer is caught up and has no unread frontier.

Validation

  • mvn spotless:apply -pl iotdb-core/datanode passed.
  • git diff --check passed.
  • The targeted Maven test remains unverified on this PR commit. The latest prior attempt stopped during compilation at PipeDataNodeTaskAgent.java:127 and :228, before any tests ran. An earlier run with 16 of 17 tests passing predates the final fixture adjustment.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Initial independent review summary

  • Review scope: only the two requested files, comparing the source worktree changes against its HEAD (7a347e44ddb76dd33d41401e1eee29271563a144); no branch-history differences were included. No actionable issues were found.
  • The same two-file patch is committed on origin/master ecc01fd45b9a06ff250665282c6f7cee72c81377 as c8cfeaa5f4167780cd69b6d9a85af24495b5544b. The local candidate, remote branch, and PR head match at c8cfeaa5f4167780cd69b6d9a85af24495b5544b.
  • mvn spotless:apply -pl iotdb-core/datanode and git diff --check pass. The targeted Maven test remains unverified: the latest prior attempt failed compilation in unrelated PipeDataNodeTaskAgent.java:127 and :228, with zero tests executed. The earlier 16/17 run predates the final fixture adjustment.

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 Map<Integer, SafeFrontier> safeFrontiers =
serverImpl.getWriterSafeFrontierTracker().snapshotSafeFrontiers();

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:2152 — Per-entry synchronized safe-frontier snapshot on the replay hot path

snapshotSafeFrontiers() moved from once per round to once per delivered entry inside the while loop. It is synchronized on the shared WriterSafeFrontierTracker and copies every tracked writer plus one SafeFrontier each, while recordAppliedProgress takes the same monitor on the consensus write path under stateMachineLock; with the default subscriptionConsensusBatchMaxWalEntries=1024 this adds up to ~1024 monitor acquisitions and map copies per round per queue.

Fix: Cache the snapshot and refresh it only when applied progress changes (e.g. add a version counter bumped by recordAppliedProgress, or compare per-writer localSeq before re-snapshotting).

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.

Addressed in 00f800d. Added a monotonically increasing safe-frontier version for writer registration, applied-sequence advances, and effective safe-time advances. The queue reuses the copied snapshot while that version is unchanged and refreshes it only when the version changes. The targeted tracker and queue tests pass.

continue;
}
final Map<Integer, SafeFrontier> safeFrontiers =
serverImpl.getWriterSafeFrontierTracker().snapshotSafeFrontiers();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Guard against progress advancing after this snapshot

This is still a point-in-time snapshot. recordAppliedProgress() can advance a retired writer after this call returns while the independent WAL reader has already reported caught up and cannot yet see the record. The decision below then sees no unread progress and can omit that writer barrier, allowing a newer writer entry to be emitted first. The added regression advances progress after the initial snapshot, before this refresh, so it does not cover this post-refresh window. Please ensure the frontier used to release a retired writer remains valid through the ordering decision, and add a test that advances the sequence after this snapshot.

@Caideyipi Caideyipi Nov 30, 2026 •

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.

The version recheck and post-snapshot regression are in 00f800d. Clarification: the check detects progress advances between snapshot acquisition and the final validation, but it is not atomic with the subsequent selection/publication, so a concurrent advance after validation is not excluded. I am leaving this thread open; fully closing that interval needs a coordination or handoff-sealing guarantee. Is there an existing API or invariant for that?

@codecov

codecov Bot commented Nov 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.64%. Comparing base (ecc01fd) to head (c8cfeaa).

Files with missing lines Patch % Lines
...on/broker/consensus/ConsensusPrefetchingQueue.java 0.00% 9 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19450      +/-   ##
============================================
- Coverage     50.64%   50.64%   -0.01%     
  Complexity      137      137              
============================================
  Files          5788     5788              
  Lines        427345   427349       +4     
  Branches      56808    56808              
============================================
- Hits         216449   216430      -19     
- Misses       210896   210919      +23     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sonarqubecloud

Copy link
Copy Markdown

@Caideyipi

Caideyipi commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Review-comment update

  • Reviewed base: c8cfeaa5f4167780cd69b6d9a85af24495b5544b. Commit 00f800d829ccc8bcdf99c569d0034d769d485989 is pushed; local and confirmed PR heads match.
  • Addressed snapshot-copy overhead with versioned caching. Added a final frontier-version check before writer selection and a regression for progress advancing after snapshot return. The check detects changes before validation, but is not atomic with selection/publication; the P1 thread remains open to review the residual race.
  • The unreadable or pruned WAL concern also remains open: no authoritative per-writer replayability watermark is available in the current path, and a local WAL position is not safe evidence that a remote writer sequence cannot still appear. The inline reply asks for the required invariant.
  • Validation: scoped Spotless passed, git diff --check passed, and the clean targeted Maven run passed all 22 tests (0 failures, errors, or skips). An earlier fixture iteration failed one assertion; it was corrected before the final run.

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.


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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants