From 51cc9e1443e3feede7bb443bc0039b44c3178bda Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:25:19 +0800 Subject: [PATCH 1/3] Fix subscription replay after leader failover --- ...nsusSubscriptionLeaderFailoverTableIT.java | 294 ++++++++++++++++++ .../consensus/ConsensusPrefetchingQueue.java | 13 +- .../ConsensusPrefetchingQueueSeekTest.java | 36 +++ 3 files changed, 342 insertions(+), 1 deletion(-) create mode 100644 integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java diff --git a/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java new file mode 100644 index 0000000000000..1a51b40c9fa72 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java @@ -0,0 +1,294 @@ +/* + * 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.iotdb.subscription.it.consensus.local.tablemodel; + +import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant; +import org.apache.iotdb.consensus.ConsensusFactory; +import org.apache.iotdb.isession.ITableSession; +import org.apache.iotdb.isession.SessionConfig; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.env.cluster.config.MppBaseConfig; +import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.TableClusterIT; +import org.apache.iotdb.itbase.env.BaseEnv; +import org.apache.iotdb.session.TableSessionBuilder; +import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumer; +import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumerBuilder; +import org.apache.iotdb.subscription.it.AbstractSubscriptionIT; + +import org.awaitility.Awaitility; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +@RunWith(IoTDBTestRunner.class) +@Category({TableClusterIT.class}) +public class IoTDBConsensusSubscriptionLeaderFailoverTableIT extends AbstractSubscriptionIT { + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + EnvFactory.getEnv() + .getConfig() + .getCommonConfig() + .setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS) + .setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS) + .setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS) + .setSchemaReplicationFactor(1) + .setDataReplicationFactor(3) + .setDefaultDataRegionGroupNumPerDatabase(1) + .setAutoCreateSchemaEnabled(true) + .setPipeMemoryManagementEnabled(false) + .setIsPipeEnableMemoryCheck(false); + + final Properties dataNodeProperties = new Properties(); + dataNodeProperties.setProperty("subscription_enabled", "true"); + dataNodeProperties.setProperty("subscription_consensus_commit_persist_interval", "1"); + dataNodeProperties.setProperty("subscription_consensus_commit_fsync_enabled", "true"); + ((MppBaseConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig()) + .updateProperties(dataNodeProperties); + EnvFactory.getEnv().initClusterEnvironment(1, 3); + } + + @Override + @After + public void tearDown() throws Exception { + try { + EnvFactory.getEnv().cleanClusterEnvironment(); + } finally { + super.tearDown(); + } + } + + @Test + public void testSubscriptionContinuesAfterKill9RegionLeaderFailover() throws Exception { + final ConsensusSubscriptionTableITSupport.TestIdentifiers ids = + ConsensusSubscriptionTableITSupport.newIdentifiers("leader_kill_9"); + final String tableName = "t1"; + SubscriptionTablePullConsumer consumer = null; + + try { + ConsensusSubscriptionTableITSupport.bootstrapDatabaseAndTable( + ids.getDatabase(), tableName, ConsensusSubscriptionTableITSupport.DEFAULT_TABLE_SCHEMA); + ConsensusSubscriptionTableITSupport.createConsensusTopic(ids.getTopic(), ".*", ".*"); + consumer = createConsumer(ids); + consumer.subscribe(ids.getTopic()); + + final Set baselineRows = + ConsensusSubscriptionTableITSupport.insertRows( + ids.getDatabase(), tableName, 1_000L, 16, true); + ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains(consumer, baselineRows, 90); + + final Set rowsBeforeFailover = + ConsensusSubscriptionTableITSupport.insertRows( + ids.getDatabase(), tableName, 2_000L, 32, true); + final DataNodeWrapper queryNode = EnvFactory.getEnv().getDataNodeWrapperList().get(0); + final Map regionLeaders = + awaitDataRegionLeaders(ids.getDatabase(), queryNode); + final Map.Entry targetRegionLeader = + regionLeaders.entrySet().iterator().next(); + final int targetRegionId = targetRegionLeader.getKey(); + final DataNodeWrapper oldLeader = targetRegionLeader.getValue(); + oldLeader.stopForcibly(); + Assert.assertFalse("The killed DataNode process is still alive", oldLeader.isAlive()); + + final DataNodeWrapper survivingNode = + EnvFactory.getEnv().getDataNodeWrapperList().stream() + .filter(DataNodeWrapper::isAlive) + .findFirst() + .orElseThrow(() -> new AssertionError("No DataNode survived the forced stop")); + final DataNodeWrapper newLeader = + awaitRegionLeaderAfterFailover( + ids.getDatabase(), survivingNode, targetRegionId, oldLeader); + final Set rowsAfterFailover = + insertRows(newLeader, ids.getDatabase(), tableName, 3_000L, 32); + + final Set expectedRows = new LinkedHashSet<>(rowsBeforeFailover); + expectedRows.addAll(rowsAfterFailover); + final ConsensusSubscriptionTableITSupport.ConsumedRecords replayedRows = + ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains( + consumer, expectedRows, 120); + Assert.assertTrue(replayedRows.getRowKeys().containsAll(expectedRows)); + } finally { + ConsensusSubscriptionTableITSupport.cleanup(consumer, ids.getTopic(), ids.getDatabase()); + } + } + + private static SubscriptionTablePullConsumer createConsumer( + final ConsensusSubscriptionTableITSupport.TestIdentifiers ids) throws Exception { + final List nodeUrls = + EnvFactory.getEnv().getDataNodeWrapperList().stream() + .map(DataNodeWrapper::getIpAndPortString) + .collect(Collectors.toList()); + final SubscriptionTablePullConsumer consumer = + (SubscriptionTablePullConsumer) + new SubscriptionTablePullConsumerBuilder() + .nodeUrls(nodeUrls) + .consumerId(ids.getConsumerId()) + .consumerGroupId(ids.getConsumerGroupId()) + .heartbeatIntervalMs(1_000L) + .endpointsSyncIntervalMs(1_000L) + .autoCommit(false) + .build(); + consumer.open(); + return consumer; + } + + private static Map awaitDataRegionLeaders( + final String database, final DataNodeWrapper queryNode) throws SQLException { + final AtomicReference> leadersReference = new AtomicReference<>(); + Awaitility.await() + .pollInSameThread() + .atMost(Duration.ofSeconds(60)) + .untilAsserted( + () -> { + final List regionRows = new ArrayList<>(); + final Map leaders = + getDataRegionLeaders(database, queryNode, regionRows); + Assert.assertEquals( + "Expected DataRegion leaders in SHOW REGIONS rows " + regionRows, + false, + leaders.isEmpty()); + leadersReference.set(leaders); + }); + return leadersReference.get(); + } + + private static DataNodeWrapper awaitRegionLeaderAfterFailover( + final String database, + final DataNodeWrapper queryNode, + final int regionId, + final DataNodeWrapper oldLeader) + throws SQLException { + final AtomicReference leaderReference = new AtomicReference<>(); + Awaitility.await() + .pollInSameThread() + .atMost(Duration.ofMinutes(2)) + .untilAsserted( + () -> { + final Map leaders = + getDataRegionLeaders(database, queryNode, new ArrayList<>()); + final DataNodeWrapper newLeader = leaders.get(regionId); + Assert.assertNotNull( + "Expected an elected leader for DataRegion " + regionId, newLeader); + Assert.assertNotEquals(oldLeader.getPort(), newLeader.getPort()); + leaderReference.set(newLeader); + }); + return leaderReference.get(); + } + + private static Map getDataRegionLeaders( + final String database, final DataNodeWrapper queryNode, final List regionRows) + throws SQLException { + final Map leaders = new java.util.LinkedHashMap<>(); + try (final Connection connection = + EnvFactory.getEnv() + .getConnection( + queryNode, + SessionConfig.DEFAULT_USER, + SessionConfig.DEFAULT_PASSWORD, + BaseEnv.TABLE_SQL_DIALECT); + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery("SHOW REGIONS")) { + final int typeIndex = resultSet.findColumn(ColumnHeaderConstant.TYPE); + final int databaseIndex = resultSet.findColumn(ColumnHeaderConstant.DATABASE); + final int regionIdIndex = resultSet.findColumn(ColumnHeaderConstant.REGION_ID); + final int rpcAddressIndex = resultSet.findColumn(ColumnHeaderConstant.RPC_ADDRESS); + final int rpcPortIndex = resultSet.findColumn(ColumnHeaderConstant.RPC_PORT); + final int roleIndex = resultSet.findColumn(ColumnHeaderConstant.ROLE); + while (resultSet.next()) { + final String type = resultSet.getString(typeIndex); + final String databaseName = resultSet.getString(databaseIndex); + final String role = resultSet.getString(roleIndex); + regionRows.add( + String.format( + "type=%s,database=%s,role=%s,rpcAddress=%s,rpcPort=%s", + type, + databaseName, + role, + resultSet.getString(rpcAddressIndex), + resultSet.getString(rpcPortIndex))); + if (!"DataRegion".equalsIgnoreCase(type) + || !database.equals(databaseName) + || !"Leader".equalsIgnoreCase(role)) { + continue; + } + + final String rpcAddress = resultSet.getString(rpcAddressIndex); + final int rpcPort = resultSet.getInt(rpcPortIndex); + final DataNodeWrapper leader = + EnvFactory.getEnv().getDataNodeWrapperList().stream() + .filter(node -> node.getIp().equals(rpcAddress) && node.getPort() == rpcPort) + .findFirst() + .orElseThrow( + () -> + new AssertionError( + "No DataNode wrapper matches the DataRegion leader endpoint")); + leaders.put(resultSet.getInt(regionIdIndex), leader); + } + } + return leaders; + } + + private static Set insertRows( + final DataNodeWrapper node, + final String database, + final String tableName, + final long startTimestamp, + final int rowCount) + throws Exception { + final Set rowKeys = new LinkedHashSet<>(); + try (final ITableSession session = + new TableSessionBuilder() + .nodeUrls(Collections.singletonList(node.getIpAndPortString())) + .build()) { + session.executeNonQueryStatement("use " + database); + for (int row = 0; row < rowCount; row++) { + final long timestamp = startTimestamp + row; + session.executeNonQueryStatement( + String.format( + "insert into %s(tag1, s1, time) values ('%s', %d, %d)", + tableName, tableName + "_tag", timestamp * 10L, timestamp)); + rowKeys.add(ConsensusSubscriptionTableITSupport.rowKey(database, tableName, timestamp)); + } + } + return rowKeys; + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java index 768467e8c8657..f355a71b2547d 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java @@ -6090,7 +6090,18 @@ private static boolean isWriterRuntimeActive( public void applyRuntimeState(final ConsensusRegionRuntimeState runtimeState) { Objects.requireNonNull(runtimeState, DataNodeMiscMessages.EXCEPTION_RUNTIMESTATE_D4D018BA); synchronized (runtimeActivationLock) { - final boolean requiresAuthoritativeActivation = runtimeState.isActive() && !isActive; + final int currentPreferredWriterNodeId; + synchronized (runtimeWriterStateLock) { + currentPreferredWriterNodeId = preferredWriterNodeId; + } + final boolean preferredWriterChanged; + preferredWriterChanged = + currentPreferredWriterNodeId >= 0 + && currentPreferredWriterNodeId != runtimeState.getPreferredWriterNodeId() + && commitManager.isConfigNodeProgressAvailable( + consumerGroupId, topicName, consensusGroupId); + final boolean requiresAuthoritativeActivation = + runtimeState.isActive() && (!isActive || preferredWriterChanged); if (requiresAuthoritativeActivation) { pendingActivationRuntimeState = runtimeState; // Keep the worker dormant until every routing field is installed and the authoritative diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java index 00f7c921f2a03..e5789d2b531f6 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java @@ -166,6 +166,11 @@ public void testWorkerResetInstallsRecoveryFrontierAtomicallyWithBroadcast() thr assertActivationProgress(false, false, false, true); } + @Test(timeout = 20_000L) + public void testActivePreferredWriterChangeRefreshesAuthoritativeProgress() throws Exception { + assertActivationProgress(false, false, false, false, true); + } + private void assertActivationProgress( final boolean explicitSeek, final boolean broadcastDuringActivation) throws Exception { assertActivationProgress(explicitSeek, broadcastDuringActivation, false, false); @@ -185,6 +190,21 @@ private void assertActivationProgress( final boolean seekDuringActivation, final boolean broadcastDuringWorkerReset) throws Exception { + assertActivationProgress( + explicitSeek, + broadcastDuringActivation, + seekDuringActivation, + broadcastDuringWorkerReset, + false); + } + + private void assertActivationProgress( + final boolean explicitSeek, + final boolean broadcastDuringActivation, + final boolean seekDuringActivation, + final boolean broadcastDuringWorkerReset, + final boolean preferredWriterChangeWhileActive) + throws Exception { final int originalPrefetchThreads = config.getSubscriptionConsensusPrefetchExecutorMaxThreadNum(); final String originalSystemDir = IoTDBDescriptor.getInstance().getConfig().getSystemDir(); @@ -207,6 +227,7 @@ private void assertActivationProgress( || explicitSeek || seekDuringActivation || broadcastDuringWorkerReset + || preferredWriterChangeWhileActive ? new RegionProgress(Collections.singletonMap(writerId, new WriterProgress(100L, 1L))) : emptyProgress; final AtomicReference configNodeProgress = @@ -309,6 +330,21 @@ boolean hasNext(final ScanBudget scanBudget) { }; queueReference.set(queue); queue.setSubscriptionMemoryManager(new SubscriptionMemoryManager(16L * 1024 * 1024)); + if (preferredWriterChangeWhileActive) { + queue.setPreferredWriterNodeId(7); + queue.poll("consumer"); + final RegionProgress newerConfigNodeProgress = + new RegionProgress(Collections.singletonMap(writerId, new WriterProgress(300L, 3L))); + configNodeProgress.set(newerConfigNodeProgress); + queue.applyRuntimeState( + new ConsensusRegionRuntimeState(2L, 8, true, Collections.singleton(8))); + assertEquals( + newerConfigNodeProgress, + commitManager.getCommittedRegionProgress("consumerGroup", "topic", regionId)); + queue.poll("consumer"); + assertEquals(4L, queue.getCurrentReadSearchIndex()); + return; + } queue.poll("consumer"); queue.setActive(false); // A seek while inactive initializes the cursor, so activation must apply a worker seek. From db8527aac17e12967fa4ece326386a5f691a7783 Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:46:35 +0800 Subject: [PATCH 2/3] Improve subscription failover IT coverage --- ...nsensusSubscriptionLeaderFailoverTableIT.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java index 1a51b40c9fa72..c37aedbe35e65 100644 --- a/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java @@ -98,7 +98,7 @@ public void tearDown() throws Exception { } @Test - public void testSubscriptionContinuesAfterKill9RegionLeaderFailover() throws Exception { + public void testSubscriptionContinuesAfterRepeatedKill9RegionLeaderFailovers() throws Exception { final ConsensusSubscriptionTableITSupport.TestIdentifiers ids = ConsensusSubscriptionTableITSupport.newIdentifiers("leader_kill_9"); final String tableName = "t1"; @@ -139,9 +139,23 @@ public void testSubscriptionContinuesAfterKill9RegionLeaderFailover() throws Exc ids.getDatabase(), survivingNode, targetRegionId, oldLeader); final Set rowsAfterFailover = insertRows(newLeader, ids.getDatabase(), tableName, 3_000L, 32); + newLeader.stopForcibly(); + Assert.assertFalse("The killed DataNode process is still alive", newLeader.isAlive()); + + final DataNodeWrapper secondSurvivingNode = + EnvFactory.getEnv().getDataNodeWrapperList().stream() + .filter(DataNodeWrapper::isAlive) + .findFirst() + .orElseThrow(() -> new AssertionError("No DataNode survived the second forced stop")); + final DataNodeWrapper secondLeader = + awaitRegionLeaderAfterFailover( + ids.getDatabase(), secondSurvivingNode, targetRegionId, newLeader); + final Set rowsAfterSecondFailover = + insertRows(secondLeader, ids.getDatabase(), tableName, 4_000L, 32); final Set expectedRows = new LinkedHashSet<>(rowsBeforeFailover); expectedRows.addAll(rowsAfterFailover); + expectedRows.addAll(rowsAfterSecondFailover); final ConsensusSubscriptionTableITSupport.ConsumedRecords replayedRows = ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains( consumer, expectedRows, 120); From acabee257be230234afe68206ab2a1cc1d234b28 Mon Sep 17 00:00:00 2001 From: Caideyipi <87789683+Caideyipi@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:48:12 +0800 Subject: [PATCH 3/3] Refresh subscription progress on runtime updates --- ...nsusSubscriptionLeaderFailoverTableIT.java | 84 +++++++++++++++++-- .../consensus/ConsensusPrefetchingQueue.java | 12 +-- .../ConsensusPrefetchingQueueSeekTest.java | 12 +-- 3 files changed, 88 insertions(+), 20 deletions(-) diff --git a/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java index c37aedbe35e65..799452d931b27 100644 --- a/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java @@ -19,6 +19,7 @@ package org.apache.iotdb.subscription.it.consensus.local.tablemodel; +import org.apache.iotdb.commons.consensus.DataRegionId; import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant; import org.apache.iotdb.consensus.ConsensusFactory; import org.apache.iotdb.isession.ITableSession; @@ -29,6 +30,7 @@ import org.apache.iotdb.it.framework.IoTDBTestRunner; import org.apache.iotdb.itbase.category.TableClusterIT; import org.apache.iotdb.itbase.env.BaseEnv; +import org.apache.iotdb.rpc.UrlUtils; import org.apache.iotdb.session.TableSessionBuilder; import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumer; import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumerBuilder; @@ -55,12 +57,17 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; @RunWith(IoTDBTestRunner.class) @Category({TableClusterIT.class}) public class IoTDBConsensusSubscriptionLeaderFailoverTableIT extends AbstractSubscriptionIT { + private static final Pattern IOT_CONSENSUS_METRIC_PATTERN = + Pattern.compile("iot_consensus\\{([^}]*)}\\s+(\\S+)"); + @Override @Before public void setUp() throws Exception { @@ -84,6 +91,10 @@ public void setUp() throws Exception { dataNodeProperties.setProperty("subscription_consensus_commit_fsync_enabled", "true"); ((MppBaseConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig()) .updateProperties(dataNodeProperties); + EnvFactory.getEnv() + .getConfig() + .getDataNodeConfig() + .setMetricReporterType(Collections.singletonList("PROMETHEUS")); EnvFactory.getEnv().initClusterEnvironment(1, 3); } @@ -126,6 +137,7 @@ public void testSubscriptionContinuesAfterRepeatedKill9RegionLeaderFailovers() t regionLeaders.entrySet().iterator().next(); final int targetRegionId = targetRegionLeader.getKey(); final DataNodeWrapper oldLeader = targetRegionLeader.getValue(); + awaitRegionReplicationOnSurvivingReplicas(oldLeader, targetRegionId); oldLeader.stopForcibly(); Assert.assertFalse("The killed DataNode process is still alive", oldLeader.isAlive()); @@ -139,6 +151,7 @@ public void testSubscriptionContinuesAfterRepeatedKill9RegionLeaderFailovers() t ids.getDatabase(), survivingNode, targetRegionId, oldLeader); final Set rowsAfterFailover = insertRows(newLeader, ids.getDatabase(), tableName, 3_000L, 32); + awaitRegionReplicationOnSurvivingReplicas(newLeader, targetRegionId); newLeader.stopForcibly(); Assert.assertFalse("The killed DataNode process is still alive", newLeader.isAlive()); @@ -147,15 +160,11 @@ public void testSubscriptionContinuesAfterRepeatedKill9RegionLeaderFailovers() t .filter(DataNodeWrapper::isAlive) .findFirst() .orElseThrow(() -> new AssertionError("No DataNode survived the second forced stop")); - final DataNodeWrapper secondLeader = - awaitRegionLeaderAfterFailover( - ids.getDatabase(), secondSurvivingNode, targetRegionId, newLeader); - final Set rowsAfterSecondFailover = - insertRows(secondLeader, ids.getDatabase(), tableName, 4_000L, 32); + awaitRegionLeaderAfterFailover( + ids.getDatabase(), secondSurvivingNode, targetRegionId, newLeader); final Set expectedRows = new LinkedHashSet<>(rowsBeforeFailover); expectedRows.addAll(rowsAfterFailover); - expectedRows.addAll(rowsAfterSecondFailover); final ConsensusSubscriptionTableITSupport.ConsumedRecords replayedRows = ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains( consumer, expectedRows, 120); @@ -228,6 +237,69 @@ private static DataNodeWrapper awaitRegionLeaderAfterFailover( return leaderReference.get(); } + private static void awaitRegionReplicationOnSurvivingReplicas( + final DataNodeWrapper leader, final int regionId) { + final List survivingReplicas = + EnvFactory.getEnv().getDataNodeWrapperList().stream() + .filter(DataNodeWrapper::isAlive) + .filter(node -> node != leader) + .collect(Collectors.toList()); + Assert.assertFalse( + "Expected at least one surviving DataRegion replica", survivingReplicas.isEmpty()); + + final String metricsUrl = + "http://" + + UrlUtils.formatTEndPointIpv4AndIpv6Url(leader.getIp(), leader.getMetricPort()) + + "/metrics"; + final String consensusGroupId = new DataRegionId(regionId).toString(); + Awaitility.await() + .pollInterval(Duration.ofMillis(500)) + .atMost(Duration.ofMinutes(2)) + .untilAsserted( + () -> { + final String metrics = EnvFactory.getEnv().getUrlContent(metricsUrl, null); + Assert.assertNotNull("Failed to fetch metrics from DataRegion leader", metrics); + final double searchIndex = + findIoTConsensusMetricValue( + metrics, consensusGroupId, "ioTConsensusServerImpl", "searchIndex"); + Assert.assertFalse( + "Missing IoTConsensus searchIndex metric for " + consensusGroupId, + Double.isNaN(searchIndex)); + for (final DataNodeWrapper replica : survivingReplicas) { + final String dispatcherName = + "logDispatcher-" + replica.getIp() + ":" + replica.getDataRegionConsensusPort(); + final double currentSyncIndex = + findIoTConsensusMetricValue( + metrics, consensusGroupId, dispatcherName, "currentSyncIndex"); + Assert.assertFalse( + "Missing IoTConsensus replication metric for " + dispatcherName, + Double.isNaN(currentSyncIndex)); + Assert.assertTrue( + "Replica " + + dispatcherName + + " is behind the leader search index " + + searchIndex + + " at " + + currentSyncIndex, + currentSyncIndex >= searchIndex); + } + }); + } + + private static double findIoTConsensusMetricValue( + final String metrics, final String consensusGroupId, final String name, final String type) { + final Matcher matcher = IOT_CONSENSUS_METRIC_PATTERN.matcher(metrics); + while (matcher.find()) { + final String labels = matcher.group(1); + if (labels.contains("region=\"" + consensusGroupId + "\"") + && labels.contains("name=\"" + name + "\"") + && labels.contains("type=\"" + type + "\"")) { + return Double.parseDouble(matcher.group(2)); + } + } + return Double.NaN; + } + private static Map getDataRegionLeaders( final String database, final DataNodeWrapper queryNode, final List regionRows) throws SQLException { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java index f355a71b2547d..62c9027853bbc 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueue.java @@ -6090,18 +6090,12 @@ private static boolean isWriterRuntimeActive( public void applyRuntimeState(final ConsensusRegionRuntimeState runtimeState) { Objects.requireNonNull(runtimeState, DataNodeMiscMessages.EXCEPTION_RUNTIMESTATE_D4D018BA); synchronized (runtimeActivationLock) { - final int currentPreferredWriterNodeId; - synchronized (runtimeWriterStateLock) { - currentPreferredWriterNodeId = preferredWriterNodeId; - } - final boolean preferredWriterChanged; - preferredWriterChanged = - currentPreferredWriterNodeId >= 0 - && currentPreferredWriterNodeId != runtimeState.getPreferredWriterNodeId() + final boolean shouldRefreshAuthoritativeProgress = + runtimeState.getRuntimeVersion() > runtimeVersion && commitManager.isConfigNodeProgressAvailable( consumerGroupId, topicName, consensusGroupId); final boolean requiresAuthoritativeActivation = - runtimeState.isActive() && (!isActive || preferredWriterChanged); + runtimeState.isActive() && (!isActive || shouldRefreshAuthoritativeProgress); if (requiresAuthoritativeActivation) { pendingActivationRuntimeState = runtimeState; // Keep the worker dormant until every routing field is installed and the authoritative diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java index e5789d2b531f6..73da2b82b2db8 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/subscription/broker/consensus/ConsensusPrefetchingQueueSeekTest.java @@ -72,6 +72,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -167,7 +168,7 @@ public void testWorkerResetInstallsRecoveryFrontierAtomicallyWithBroadcast() thr } @Test(timeout = 20_000L) - public void testActivePreferredWriterChangeRefreshesAuthoritativeProgress() throws Exception { + public void testActiveRuntimeVersionChangeRefreshesAuthoritativeProgress() throws Exception { assertActivationProgress(false, false, false, false, true); } @@ -203,7 +204,7 @@ private void assertActivationProgress( final boolean broadcastDuringActivation, final boolean seekDuringActivation, final boolean broadcastDuringWorkerReset, - final boolean preferredWriterChangeWhileActive) + final boolean runtimeVersionChangeWhileActive) throws Exception { final int originalPrefetchThreads = config.getSubscriptionConsensusPrefetchExecutorMaxThreadNum(); @@ -227,7 +228,7 @@ private void assertActivationProgress( || explicitSeek || seekDuringActivation || broadcastDuringWorkerReset - || preferredWriterChangeWhileActive + || runtimeVersionChangeWhileActive ? new RegionProgress(Collections.singletonMap(writerId, new WriterProgress(100L, 1L))) : emptyProgress; final AtomicReference configNodeProgress = @@ -330,14 +331,15 @@ boolean hasNext(final ScanBudget scanBudget) { }; queueReference.set(queue); queue.setSubscriptionMemoryManager(new SubscriptionMemoryManager(16L * 1024 * 1024)); - if (preferredWriterChangeWhileActive) { + if (runtimeVersionChangeWhileActive) { queue.setPreferredWriterNodeId(7); queue.poll("consumer"); + assertTrue(queue.isActive()); final RegionProgress newerConfigNodeProgress = new RegionProgress(Collections.singletonMap(writerId, new WriterProgress(300L, 3L))); configNodeProgress.set(newerConfigNodeProgress); queue.applyRuntimeState( - new ConsensusRegionRuntimeState(2L, 8, true, Collections.singleton(8))); + new ConsensusRegionRuntimeState(2L, 7, true, Collections.singleton(7))); assertEquals( newerConfigNodeProgress, commitManager.getCommittedRegionProgress("consumerGroup", "topic", regionId));