Skip to content

Subscription: fix retained snapshot completion across DataNodes and DataRegions - #19364

Merged
jt2594838 merged 9 commits into
masterfrom
fix/retained-snapshot-completion-across-datanodes-and-regions
Nov 26, 2026
Merged

jt2594838 merged 9 commits into
masterfrom
fix/retained-snapshot-completion-across-datanodes-and-regions

Conversation

@VGalaxies

Copy link
Copy Markdown
Contributor

Problem

For retained snapshot topics (mode=snapshot with retain-progress-after-unsubscribe=true) in a multi-DataNode / multi-DataRegion cluster, completion and auto-unsubscription had four gaps:

  1. Premature global unsubscribe on the client: receiving a TERMINATION signal from the first DataNode immediately triggered global unsubscribe(topicName) on ConfigNode, cutting off historical TsFile streaming on other DataNodes that had not finished yet.
  2. Premature local completion on a multi-DataRegion DataNode: SubscriptionPrefetchingQueue marked a snapshot queue completed upon receiving the first PipeTerminateEvent, without waiting for all expected local DataRegions of the subscription pipe to terminate.
  3. Stalled completion when a DataNode owns zero local DataRegions: a DataNode running the subscription pipe with no local DataRegions (and therefore no local PipeTask / prefetching queue) never emitted TERMINATION, keeping a multi-provider consumer waiting indefinitely.
  4. Server-side handleExit() bypassing the multi-DataNode barrier: when a consumer connection to one locally completed (or zero-region) DataNode disconnected, SubscriptionReceiverV1#unsubscribeCompleteTopics() immediately called global unsubscribe on ConfigNode while other DataNodes were still streaming historical data.

Fix

  • Client multi-DataNode TERMINATION barrier (AbstractSubscriptionConsumer, AbstractSubscriptionProviders):
    • Track terminated DataNode IDs per retained snapshot topic (terminatedDataNodeIdsByTopic) and wait until all expected DataNode providers have reported TERMINATION before auto-unsubscribing on ConfigNode.
    • Exclude already-terminated DataNodes when polling remaining active providers, and clear tracked termination state on provider disconnect / reconnect or unsubscribe.
  • DataNode multi-DataRegion TERMINATION aggregation (PipeTerminateEvent, PipeDataNodeTaskAgent, SubscriptionPrefetchingQueue):
    • Expose getExpectedDataRegionIds(...) on PipeDataNodeTaskAgent and aggregate PipeTerminateEvent region completions in SubscriptionPrefetchingQueue until every expected local DataRegion has terminated before marking the queue completed.
  • Zero-local-region DataNode completion (PipeDataNodeTaskAgent, SubscriptionBroker):
    • Add PipeDataNodeTaskAgent#isRunningSubscriptionPipeWithoutLocalTasks(pipeName, isTableModel) checking both empty local PipeTasks and getExpectedDataRegionIds(pipeMeta).isEmpty() (so failed local task creation is never misclassified as completed), allowing SubscriptionBroker to emit TERMINATION for DataNodes with no local regions.
  • Preserve multi-DataNode barrier on disconnect (SubscriptionReceiverV1):
    • Skip server-side single-DataNode global auto-unsubscribe in handleExit() / unsubscribeCompleteTopics() for retained snapshot topics (isSnapshotMode() && isProgressRetainedAfterUnsubscribe()), letting client-side multi-DataNode coordination handle global unsubscription.

Tests

  • SubscriptionConsumerMultiProviderPollTest (iotdb-client/subscription): 36/36 pass (including multi-provider retained snapshot barrier tests).
  • PipeDataNodeTaskAgentTest: 21/21 pass (including testIsRunningSubscriptionPipeWithoutLocalTasksChecksExpectedRegions).
  • SubscriptionReceiverV1Test: 30/30 pass (including testHandleExitSkipsAutoUnsubscribeForRetainedSnapshotTopics).
  • SubscriptionRetainedInitialReplayTest: 9/11 pass (all new multi-region and zero-local-task retained snapshot tests pass; 2 unrelated pre-existing ClassCastException errors on master in assertDownloadedTabletPagesReplayTheirRows:226).
  • Verified spotless:apply and -P with-zh-locale full -am test-compile (28 modules).

@Caideyipi Caideyipi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One actionable issue found; see the inline review comment.

terminateEvent,
e);
}
terminateEvent.decreaseReferenceCount(SubscriptionPrefetchingQueue.class.getName(), true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Preserve the drain barrier for non-marking terminators. This branch is used outside snapshot mode, including the historical-plus-realtime path. Previously, the terminator stayed pending until both inFlightEvents and prefetchingQueue drained; releasing it immediately lets prefetch continue into realtime events while historical replay events may still be unacknowledged, so live events can be polled before replay completion. Please retain the drain/retry check when shouldMark is false.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this! Addressed in df8194d: restored the drain and retry barrier for non-marking PipeTerminateEvents (currentNonMarkingTerminateEvent) in SubscriptionPrefetchingQueue. Both tryPrefetch and tryPrefetchV2 now pause prefetching subsequent realtime events until batches.emitAll succeeds and both inFlightEvents and prefetchingQueue are drained, and retry on poll/ack/nack/prefetch paths. Added regression test SubscriptionRetainedInitialReplayTest#testNonMarkingTerminateEventPreservesDrainBarrierBeforeRealtimePrefetch.

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 5.39846% with 368 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.50%. Comparing base (7aa0826) to head (1ff5426).

Files with missing lines Patch % Lines
...scription/broker/SubscriptionPrefetchingQueue.java 0.00% 177 Missing ⚠️
...on/consumer/base/AbstractSubscriptionConsumer.java 0.00% 86 Missing ⚠️
...n/consumer/base/AbstractSubscriptionProviders.java 0.00% 60 Missing ⚠️
.../subscription/receiver/SubscriptionReceiverV1.java 0.00% 22 Missing ⚠️
...otdb/db/pipe/agent/task/PipeDataNodeTaskAgent.java 47.82% 12 Missing ⚠️
...tdb/db/subscription/broker/SubscriptionBroker.java 0.00% 9 Missing ⚠️
...ipe/event/common/terminate/PipeTerminateEvent.java 0.00% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19364      +/-   ##
============================================
- Coverage     50.53%   50.50%   -0.04%     
  Complexity      129      129              
============================================
  Files          5786     5786              
  Lines        425745   426059     +314     
  Branches      56465    56549      +84     
============================================
+ Hits         215163   215190      +27     
- Misses       210582   210869     +287     

☔ 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.

Copilot AI left a comment

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.

🟡 Changes recommended

Critical membership races and incomplete endpoint discovery can trigger premature global unsubscribe, while leadership transfer with outstanding acknowledgements can leave subscription queues permanently incomplete.

3 open issues
What changed in this PR

This PR coordinates retained snapshot completion across DataNodes and local DataRegions so subscription consumers wait for all historical data before automatically unsubscribing.

Changes:

  • Adds a client-side completion barrier across known DataNode providers.
  • Aggregates local DataRegion termination events and handles DataNodes with no local tasks.
  • Prevents disconnect-triggered unsubscribe from bypassing the barrier and adds regression coverage.
File Description
iotdb-core/​datanode/​src/​test/​java/​org/​apache/​iotdb/​db/​subscription/​receiver/​SubscriptionReceiverV1Test.java Tests disconnect handling for retained snapshots.
iotdb-core/​datanode/​src/​test/​java/​org/​apache/​iotdb/​db/​subscription/​agent/​SubscriptionRetainedInitialReplayTest.java Tests regional completion, acknowledgement barriers, and zero-task nodes.
iotdb-core/​datanode/​src/​test/​java/​org/​apache/​iotdb/​db/​pipe/​agent/​task/​PipeDataNodeTaskAgentTest.java Tests expected-region checks for zero-task completion.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​subscription/​receiver/​SubscriptionReceiverV1.java Skips disconnect-triggered unsubscribe for retained snapshots.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​subscription/​broker/​SubscriptionPrefetchingQueue.java Aggregates regional termination and waits for outstanding deliveries.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​subscription/​broker/​SubscriptionBroker.java Reports completion for running snapshots without local tasks.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​pipe/​event/​common/​terminate/​PipeTerminateEvent.java Exposes region identity and completion-marking behavior.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​pipe/​agent/​task/​PipeDataNodeTaskAgent.java Exposes expected regions and zero-local-task checks.
iotdb-client/​subscription/​src/​test/​java/​org/​apache/​iotdb/​session/​subscription/​consumer/​base/​SubscriptionConsumerMultiProviderPollTest.java Tests completion across multiple providers.
iotdb-client/​subscription/​src/​main/​java/​org/​apache/​iotdb/​session/​subscription/​consumer/​base/​AbstractSubscriptionProviders.java Tracks cluster membership and routes heartbeat completion signals.
iotdb-client/​subscription/​src/​main/​java/​org/​apache/​iotdb/​session/​subscription/​consumer/​base/​AbstractSubscriptionConsumer.java Coordinates provider termination and skips polling completed providers.

Review effort: Balanced

Comment on lines +840 to +841
final Set<Integer> expectedDataNodeIds = getExpectedDataNodeIds();
synchronized (topicTerminationLock) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 4d3bee9: handleProviderTopicTermination now holds providers.acquireReadLock() across reading providers.getExpectedDataNodeIds() / providers.getTopologyGeneration() and checking topicTerminationLock, and validates that topologyGeneration is unchanged before issuing unsubscribe(); syncInternal also clears termination state and increments topologyGeneration whenever cluster membership changes. Added regression test SubscriptionConsumerMultiProviderPollTest#testRetainedSnapshotTerminationDoesNotUseStaleMembershipAcrossConcurrentSync.

Comment on lines +312 to +314
final Set<Integer> ids = new HashSet<>(knownClusterDataNodeIds);
ids.addAll(subscriptionProviders.keySet());
return ids;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 4d3bee9: AbstractSubscriptionProviders.getExpectedDataNodeIds() now returns Collections.emptySet() when knownClusterDataNodeIds is empty so an unproven cluster topology cannot trigger premature global unsubscribe if initial endpoint discovery fails. Added regression test SubscriptionConsumerMultiProviderPollTest#testRetainedSnapshotTerminationWaitsWhenEndpointDiscoveryFailsDuringOpen.


final PipeTerminateEvent lastTerminateEvent =
pendingTerminateEvents.get(pendingTerminateEvents.size() - 1);
lastTerminateEvent.addOnCommittedHook(this::markCompleted);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 4d3bee9: SubscriptionPrefetchingQueue now tracks per-region termination events, validates expected regions against active committer keys (PipeEventCommitManager.isCurrentCommitterKey), attaches completion hooks to each expected region's event (tracking awaitingCompletionCommitterKeys and committedTerminateDataRegionIds), and handles both zero-expected-region completion and concurrent committer deregistration. Added regression test SubscriptionRetainedInitialReplayTest#testRetainedSnapshotCompletesAfterLastRegionLosesLeadershipWithOutstandingAck.

@sonarqubecloud

Copy link
Copy Markdown

@jt2594838
jt2594838 merged commit c5804fa into master Nov 26, 2026
40 of 42 checks passed
@jt2594838
jt2594838 deleted the fix/retained-snapshot-completion-across-datanodes-and-regions branch November 26, 2026 01:33
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.

4 participants