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

JackieTien97 pushed a commit to branch ty/fix-table-attribute-batches
in repository https://gitbox.apache.org/repos/asf/iotdb.git

commit 4e2fe779d16898106b3299f79c8679f8c339b5a5
Author: JackieTien97 <[email protected]>
AuthorDate: Sun Dec 6 09:35:54 2026 +0800

    Prevent lost remote table attribute updates during broadcast
---
 .../fetcher/TableDeviceCacheAttributeGuard.java    | 88 +++++++++++-----------
 .../update/DeviceAttributeCacheUpdater.java        |  5 +-
 .../fetcher/cache/TableDeviceSchemaCacheTest.java  | 45 +++++++++++
 .../update/UpdateContainerSerializationTest.java   | 47 ++++++++++++
 4 files changed, 141 insertions(+), 44 deletions(-)

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..9b10a533ce1 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) {
+      // 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.
+      ((UpdateDetailContainer) container)
+          .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/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