This is an automated email from the ASF dual-hosted git repository.

JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new 29bc0e5a7a1 Prevent lost remote table attribute updates during 
broadcast
29bc0e5a7a1 is described below

commit 29bc0e5a7a186a9af0f53a853e1b12e1f8e2f449
Author: Jackie Tien <[email protected]>
AuthorDate: Sun Dec 6 13:06:03 2026 +0800

    Prevent lost remote table attribute updates during broadcast
---
 .../it/schema/IoTDBAttributeUpdateOrderingIT.java  | 51 +++++++++++++
 .../fetcher/TableDeviceCacheAttributeGuard.java    | 88 +++++++++++-----------
 .../update/DeviceAttributeCacheUpdater.java        |  5 +-
 .../GeneralRegionAttributeSecurityService.java     |  2 +-
 .../TableDeviceCacheAttributeGuardTest.java        | 18 +++++
 .../fetcher/cache/TableDeviceSchemaCacheTest.java  | 45 +++++++++++
 .../update/UpdateContainerSerializationTest.java   | 47 ++++++++++++
 7 files changed, 211 insertions(+), 45 deletions(-)

diff --git 
a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java
 
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java
index 2086ecc3549..b87d718aa45 100644
--- 
a/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java
+++ 
b/integration-test/src/test/java/org/apache/iotdb/relational/it/schema/IoTDBAttributeUpdateOrderingIT.java
@@ -25,11 +25,17 @@ import org.apache.iotdb.it.framework.IoTDBTestRunner;
 import org.apache.iotdb.itbase.category.TableClusterIT;
 import 
org.apache.iotdb.relational.it.schema.fault.MetadataFaultController.Node;
 
+import org.awaitility.Awaitility;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 import org.junit.runner.RunWith;
 
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.List;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
@@ -37,6 +43,51 @@ import static org.junit.Assert.assertTrue;
 @RunWith(IoTDBTestRunner.class)
 @Category(TableClusterIT.class)
 public class IoTDBAttributeUpdateOrderingIT extends 
TableMetadataPropagationTestBase {
+  @Test
+  public void testBroadcastPastIdleSchemaRegion() throws Exception {
+    // Three single-replica SchemaRegions on two DataNodes put at least two 
leaders on one node.
+    final List<String> databases =
+        Arrays.asList("metadata_broadcast_a", "metadata_broadcast_b", 
"metadata_broadcast_c");
+    try (Connection connection = EnvFactory.getEnv().getTableConnection();
+        Statement statement = connection.createStatement()) {
+      try {
+        for (String db : databases) {
+          statement.execute("CREATE DATABASE " + db);
+          statement.execute(
+              "CREATE TABLE "
+                  + db
+                  + ".sensor (device STRING TAG, model STRING ATTRIBUTE, 
reading INT32 FIELD)");
+          statement.execute(
+              "INSERT INTO "
+                  + db
+                  + ".sensor(time, device, model, reading) VALUES (1, 'd0', 
'old', 10)");
+        }
+        for (String db : databases) {
+          assertCachedModel(db, "old");
+        }
+        // Update one region at a time so that the other leaders are idle in 
any iteration order.
+        for (String db : databases) {
+          statement.execute("UPDATE " + db + ".sensor SET model='new' WHERE 
device='d0'");
+          Awaitility.await("attribute broadcast for " + db)
+              .atMost(20, TimeUnit.SECONDS)
+              .untilAsserted(() -> assertCachedModel(db, "new"));
+        }
+      } finally {
+        for (String db : databases) {
+          statement.execute("DROP DATABASE IF EXISTS " + db);
+        }
+      }
+    }
+  }
+
+  private static void assertCachedModel(String database, String model) {
+    TestUtils.tableResultSetEqualTestUnordered(
+        "SELECT model, reading FROM sensor WHERE device='d0'",
+        new String[] {"model", "reading"},
+        new String[] {model + ",10,"},
+        database);
+  }
+
   /** a delayed batch belongs to the dropped column's earlier lifetime. */
   @Test
   public void testOldAttributeBatchAfterDropAndReadd() throws Exception {
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java
index 7176c127900..71b1bf666b9 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuard.java
@@ -25,8 +25,7 @@ import 
org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateClea
 import 
org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateContainer;
 import 
org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateDetailContainer;
 import org.apache.iotdb.mpp.rpc.thrift.TAttributeUpdateReq;
-
-import org.apache.tsfile.utils.Pair;
+import org.apache.iotdb.mpp.rpc.thrift.TSchemaRegionAttributeInfo;
 
 import javax.annotation.Nonnull;
 
@@ -37,7 +36,6 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.LinkedBlockingDeque;
-import java.util.stream.Collectors;
 
 import static 
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceSchemaFetcher.convertTagValuesToDeviceID;
 
@@ -45,29 +43,28 @@ public class TableDeviceCacheAttributeGuard {
 
   // Unbounded queue
   private final LinkedBlockingDeque<Set<?>> applyQueue = new 
LinkedBlockingDeque<>();
-  private final Map<Integer, Pair<Long, String>>
-      fetchedSchemaRegionIds2LargestVersionAndDatabaseMap = new 
ConcurrentHashMap<>();
+  private final Map<Integer, Long> acceptedRegionVersions = new 
ConcurrentHashMap<>();
   private final TableDeviceSchemaCache cache = 
TableDeviceSchemaCache.getInstance();
 
   public boolean isRegionFetched(final Integer schemaRegionId) {
-    return 
fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.containsKey(schemaRegionId);
+    return acceptedRegionVersions.containsKey(schemaRegionId);
   }
 
   public void addFetchedRegion(final Integer schemaRegionId) {
     // Later schema reads must not let delayed updates bypass the accepted 
version.
-    fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.putIfAbsent(
-        schemaRegionId, new Pair<>(Long.MIN_VALUE, null));
+    acceptedRegionVersions.putIfAbsent(schemaRegionId, Long.MIN_VALUE);
   }
 
   @SuppressWarnings("unchecked")
-  public @Nonnull Set<Long> addFetchQueryId(final long queryId) {
+  public synchronized @Nonnull Set<Long> addFetchQueryId(final long queryId) {
+    // Register the ID before tryUpdateCache can remove an empty fetch group.
     final Set<?> lastSet = applyQueue.peekLast();
     final Set<Long> longSet;
     if (Objects.isNull(lastSet) || lastSet instanceof HashSet) {
       longSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
       applyQueue.add(longSet);
     } else {
-      // The elements must be SetFromMap<Long> or HashSet<byte[]>
+      // Fetch IDs use a concurrent set. Queued cache updates use a HashSet.
       longSet = (Set<Long>) lastSet;
     }
     longSet.add(queryId);
@@ -75,47 +72,58 @@ public class TableDeviceCacheAttributeGuard {
   }
 
   public synchronized void handleAttributeUpdate(final TAttributeUpdateReq 
updateReq) {
-    // Trim the schema regions with lower or equal version
-    // or with this node restarted before fetching
+    final Set<Runnable> updates = new HashSet<>();
     updateReq
         .getAttributeUpdateMap()
         .entrySet()
         .removeIf(
             entry -> {
-              if 
(!fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.containsKey(entry.getKey())
-                  || entry.getValue().getVersion()
-                      <= fetchedSchemaRegionIds2LargestVersionAndDatabaseMap
-                          .get(entry.getKey())
-                          .getLeft()) {
+              final Long acceptedVersion = 
acceptedRegionVersions.get(entry.getKey());
+              final TSchemaRegionAttributeInfo info = entry.getValue();
+              if (acceptedVersion == null || info.getVersion() < 
acceptedVersion) {
                 return true;
               }
-              fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.put(
-                  entry.getKey(),
-                  new Pair<>(entry.getValue().getVersion(), 
entry.getValue().getDatabase()));
-              return false;
+              final boolean sameVersion = info.getVersion() == acceptedVersion;
+              if (!sameVersion) {
+                acceptedRegionVersions.put(entry.getKey(), info.getVersion());
+              }
+              final String database = info.getDatabase();
+              final byte[] body = info.getBody();
+              updates.add(() -> applyBatch(database, body, sameVersion));
+              return sameVersion;
             });
-    applyQueue.add(
-        updateReq.getAttributeUpdateMap().entrySet().stream()
-            .map(entry -> new Pair<>(entry.getKey(), 
entry.getValue().getBody()))
-            .collect(Collectors.toSet()));
+    applyQueue.add(updates);
     tryUpdateCache();
   }
 
+  private void applyBatch(final String database, final byte[] body, final 
boolean sameVersion) {
+    final UpdateContainer container = 
DeviceAttributeCacheUpdater.getContainer(body);
+    if (sameVersion && container instanceof UpdateDetailContainer detail) {
+      // Several size-limited batches can share one write version. Invalidate 
the affected
+      // devices after older fetches finish. This also makes a delayed retry 
safe when a newer
+      // value has already been fetched.
+      detail
+          .getUpdateMap()
+          .forEach(
+              (table, devices) ->
+                  devices
+                      .keySet()
+                      .forEach(
+                          tags ->
+                              cache.invalidateAttributes(
+                                  database,
+                                  convertTagValuesToDeviceID(table, 
tags.toArray(new String[0])))));
+    } else {
+      handleContainer(database, container);
+    }
+  }
+
   @SuppressWarnings("unchecked")
   public synchronized void tryUpdateCache() {
     while (!applyQueue.isEmpty()) {
       final Set<?> firstElement = applyQueue.peek();
       if (firstElement instanceof HashSet) {
-        for (final Object element : firstElement) {
-          final Pair<Integer, byte[]> schemaRegionIdContainerBytesPair =
-              (Pair<Integer, byte[]>) element;
-          handleContainer(
-              fetchedSchemaRegionIds2LargestVersionAndDatabaseMap
-                  .get(schemaRegionIdContainerBytesPair.getLeft())
-                  .getRight(),
-              DeviceAttributeCacheUpdater.getContainer(
-                  schemaRegionIdContainerBytesPair.getRight()));
-        }
+        ((Set<Runnable>) firstElement).forEach(Runnable::run);
         applyQueue.removeFirst();
       } else if (firstElement.isEmpty()) {
         applyQueue.removeFirst();
@@ -128,14 +136,8 @@ public class TableDeviceCacheAttributeGuard {
   // This must be synchronized with "handleUpdate" to avoid unordered execution
   // with region migration's "handleContainer" and stale "handleUpdate" logic
   public synchronized void setVersion(final int schemaRegionId, final long 
newVersion) {
-    fetchedSchemaRegionIds2LargestVersionAndDatabaseMap.computeIfPresent(
-        schemaRegionId,
-        (id, pair) -> {
-          if (newVersion > pair.getLeft()) {
-            pair.setLeft(newVersion);
-          }
-          return pair;
-        });
+    acceptedRegionVersions.computeIfPresent(
+        schemaRegionId, (id, version) -> Math.max(version, newVersion));
   }
 
   public void handleContainer(final String database, final UpdateContainer 
container) {
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java
index bb753c365c6..8219c3aae08 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/DeviceAttributeCacheUpdater.java
@@ -155,6 +155,9 @@ public class DeviceAttributeCacheUpdater {
 
   public Pair<Long, Map<TDataNodeLocation, byte[]>> getAttributeUpdateInfo(
       final @Nonnull AtomicInteger limit, final @Nonnull AtomicBoolean 
hasRemaining) {
+    // A write that finishes during serialization may be absent from these 
bytes. Its version
+    // belongs to a later batch.
+    final long batchVersion = version.get();
     // Note that the "updateContainerStatistics" is unsafe to use here for 
whole read of detail
     // container because the update map is read by GRASS thread, and the 
container's size may change
     // during the read process
@@ -183,7 +186,7 @@ public class DeviceAttributeCacheUpdater {
       limit.addAndGet(-5);
       updateBytes.put(location, container.getUpdateContent(limit, 
hasRemaining));
     }
-    return new Pair<>(version.get(), updateBytes);
+    return new Pair<>(batchVersion, updateBytes);
   }
 
   public void commit(final TableDeviceAttributeCommitUpdateNode node) {
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java
index 4f668a19075..afee10c0645 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/GeneralRegionAttributeSecurityService.java
@@ -114,7 +114,7 @@ public class GeneralRegionAttributeSecurityService extends 
AbstractPeriodicalSer
       final Pair<Long, Map<TDataNodeLocation, byte[]>> currentResult =
           regionLeader.getAttributeUpdateInfo(limit, hasRemaining);
       if (currentResult.getRight().isEmpty()) {
-        break;
+        continue;
       }
       attributeUpdateCommitMap.put(regionLeader.getSchemaRegionId(), 
currentResult);
     }
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java
index 30c6c04d913..31d9f96762b 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/TableDeviceCacheAttributeGuardTest.java
@@ -54,6 +54,24 @@ public class TableDeviceCacheAttributeGuardTest {
     assertFalse(newer.getAttributeUpdateMap().isEmpty());
   }
 
+  @Test
+  public void testMigrationOnlyAdvancesFetchedRegionVersion() {
+    final TableDeviceCacheAttributeGuard guard = new 
TableDeviceCacheAttributeGuard();
+    guard.setVersion(1, 5);
+    assertFalse(guard.isRegionFetched(1));
+
+    guard.addFetchedRegion(1);
+    assertTrue(guard.isRegionFetched(1));
+    guard.setVersion(1, 5);
+    guard.setVersion(1, 3);
+    final TAttributeUpdateReq stale = update(4);
+    guard.handleAttributeUpdate(stale);
+    assertTrue(stale.getAttributeUpdateMap().isEmpty());
+    final TAttributeUpdateReq newer = update(6);
+    guard.handleAttributeUpdate(newer);
+    assertFalse(newer.getAttributeUpdateMap().isEmpty());
+  }
+
   private static TAttributeUpdateReq update(final long version) {
     final byte[] body =
         new UpdateDetailContainer().getUpdateContent(new AtomicInteger(1024), 
new AtomicBoolean());
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
index 9b53a0e34fe..2b460d57585 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/fetcher/cache/TableDeviceSchemaCacheTest.java
@@ -31,7 +31,11 @@ import 
org.apache.iotdb.commons.schema.table.column.TagColumnSchema;
 import org.apache.iotdb.commons.schema.table.column.TimeColumnSchema;
 import org.apache.iotdb.confignode.rpc.thrift.TDatabaseSchema;
 import 
org.apache.iotdb.db.queryengine.plan.analyze.cache.partition.PartitionCache;
+import 
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceCacheAttributeGuard;
+import 
org.apache.iotdb.db.schemaengine.schemaregion.attribute.update.UpdateDetailContainer;
 import org.apache.iotdb.db.schemaengine.table.DataNodeTableCache;
+import org.apache.iotdb.mpp.rpc.thrift.TAttributeUpdateReq;
+import org.apache.iotdb.mpp.rpc.thrift.TSchemaRegionAttributeInfo;
 
 import org.apache.tsfile.common.conf.TSFileConfig;
 import org.apache.tsfile.enums.TSDataType;
@@ -48,6 +52,7 @@ import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
 
+import java.nio.ByteBuffer;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -55,7 +60,10 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.OptionalLong;
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import static 
org.apache.iotdb.db.queryengine.plan.relational.metadata.fetcher.TableDeviceSchemaFetcher.convertTagValuesToDeviceID;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -201,6 +209,43 @@ public class TableDeviceSchemaCacheTest {
     return TableDeviceSchemaCache.createForTest(1300L);
   }
 
+  @Test
+  public void testDifferentAttributeBatchesAtTheSameVersion() {
+    final TableDeviceSchemaCache cache = TableDeviceSchemaCache.getInstance();
+    final TableDeviceCacheAttributeGuard guard = new 
TableDeviceCacheAttributeGuard();
+    guard.addFetchedRegion(1);
+    final String[] firstTags = {"hebei", "p_1", "d_0"};
+    final String[] secondTags = {"hebei", "p_1", "d_1"};
+    final IDeviceID first = convertTagValuesToDeviceID(table1, firstTags);
+    final IDeviceID second = convertTagValuesToDeviceID(table1, secondTags);
+    final Map<String, Binary> oldValue =
+        Collections.singletonMap(attributeName1, new Binary("old", 
TSFileConfig.STRING_CHARSET));
+    final Map<String, Binary> newValue =
+        Collections.singletonMap(attributeName1, new Binary("new", 
TSFileConfig.STRING_CHARSET));
+    cache.putAttributes(database1, first, oldValue);
+    cache.putAttributes(database1, second, oldValue);
+
+    guard.handleAttributeUpdate(attributeBatch(firstTags, newValue));
+    Assert.assertEquals(newValue, cache.getDeviceAttribute(database1, first));
+    final Set<Long> fetches = guard.addFetchQueryId(42);
+    guard.handleAttributeUpdate(attributeBatch(secondTags, newValue));
+    // A fetch already in progress can still install its old result.
+    cache.putAttributes(database1, second, oldValue);
+    fetches.remove(42L);
+    guard.tryUpdateCache();
+    Assert.assertNull(cache.getDeviceAttribute(database1, second));
+    Assert.assertEquals(newValue, cache.getDeviceAttribute(database1, first));
+  }
+
+  private static TAttributeUpdateReq attributeBatch(String[] tags, Map<String, 
Binary> values) {
+    final UpdateDetailContainer container = new UpdateDetailContainer();
+    container.updateAttribute(table1, tags, values);
+    final byte[] body = container.getUpdateContent(new AtomicInteger(4096), 
new AtomicBoolean());
+    final Map<Integer, TSchemaRegionAttributeInfo> updates = new HashMap<>();
+    updates.put(1, new TSchemaRegionAttributeInfo(3L, database1, 
ByteBuffer.wrap(body)));
+    return new TAttributeUpdateReq(updates);
+  }
+
   @Test
   public void testDeviceCache() {
     final TableDeviceSchemaCache cache = createTestCache();
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java
index db72c6c963e..23db80b52b4 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/schemaengine/schemaregion/attribute/update/UpdateContainerSerializationTest.java
@@ -19,8 +19,12 @@
 
 package org.apache.iotdb.db.schemaengine.schemaregion.attribute.update;
 
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.db.schemaengine.rescon.MemSchemaRegionStatistics;
+
 import org.apache.tsfile.common.conf.TSFileConfig;
 import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.Pair;
 import org.apache.tsfile.utils.ReadWriteIOUtils;
 import org.junit.Test;
 
@@ -39,9 +43,52 @@ import java.util.concurrent.atomic.AtomicReference;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 public class UpdateContainerSerializationTest {
 
+  @Test
+  public void testBatchVersionWhenAttributeChangesDuringSerialization() {
+    final MemSchemaRegionStatistics statistics = 
mock(MemSchemaRegionStatistics.class);
+    when(statistics.isAllowToCreateNewSeries()).thenReturn(true);
+    final DeviceAttributeCacheUpdater updater = new 
DeviceAttributeCacheUpdater(statistics, "db");
+    final TDataNodeLocation remote = new 
TDataNodeLocation().setDataNodeId(Integer.MAX_VALUE);
+    updater.addLocation(remote);
+    final String[] device = {"d1"};
+    final Binary updated = new Binary("after", TSFileConfig.STRING_CHARSET);
+    final Binary initial =
+        new Binary("before", TSFileConfig.STRING_CHARSET) {
+          @Override
+          public byte[] getValues() {
+            // Complete the next write after the broadcaster has selected the 
previous value.
+            updater.update("t", device, Collections.singletonMap("model", 
updated));
+            updater.afterUpdate();
+            return super.getValues();
+          }
+        };
+    updater.update("t", device, Collections.singletonMap("model", initial));
+    updater.afterUpdate();
+
+    final Pair<Long, Map<TDataNodeLocation, byte[]>> first =
+        updater.getAttributeUpdateInfo(new AtomicInteger(4096), new 
AtomicBoolean());
+    final Pair<Long, Map<TDataNodeLocation, byte[]>> second =
+        updater.getAttributeUpdateInfo(new AtomicInteger(4096), new 
AtomicBoolean());
+    assertEquals(
+        new Binary("before", TSFileConfig.STRING_CHARSET),
+        modelInBatch(first.getRight().get(remote)));
+    assertEquals(updated, modelInBatch(second.getRight().get(remote)));
+    assertTrue(
+        "Versions of the two writes: " + first.getLeft() + ", " + 
second.getLeft(),
+        first.getLeft() < second.getLeft());
+  }
+
+  private static Binary modelInBatch(final byte[] bytes) {
+    final UpdateDetailContainer container =
+        (UpdateDetailContainer) 
DeviceAttributeCacheUpdater.getContainer(bytes);
+    return 
container.getUpdateMap().get("t").get(Collections.singletonList("d1")).get("model");
+  }
+
   @Test
   public void testTableAddedDuringSerialization() throws Exception {
     assertConcurrentUpdateRoundTrip(0);

Reply via email to