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 399c9f2fa2f Fix unstable it
399c9f2fa2f is described below

commit 399c9f2fa2fb480925bbf257e179d54d731d4577
Author: Jackie Tien <[email protected]>
AuthorDate: Thu Dec 3 15:34:09 2026 +0800

    Fix unstable it
---
 .../iotdb/tool/backup/IoTDBDataBackTool.java       |  6 +-
 .../iotdb/tool/backup/IoTDBDataBackToolTest.java   | 45 ++++++++++-----
 .../java/org/apache/iotdb/db/conf/IoTDBConfig.java |  2 +-
 .../org/apache/iotdb/db/conf/IoTDBDescriptor.java  |  6 +-
 .../metadata/spill/DeviceEntrySpillManager.java    | 67 ++++++++++++++--------
 .../spill/SegmentDeviceEntrySourceTest.java        | 34 +++++++++++
 .../apache/iotdb/commons/concurrent/HashLock.java  | 15 +++--
 .../apache/iotdb/commons/conf/IoTDBConstant.java   |  2 +-
 .../iotdb/commons/concurrent/HashLockTest.java     | 60 +++++++++++++++++++
 9 files changed, 188 insertions(+), 49 deletions(-)

diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/backup/IoTDBDataBackTool.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/backup/IoTDBDataBackTool.java
index f095bc96b4c..8a396ee6c25 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/backup/IoTDBDataBackTool.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/backup/IoTDBDataBackTool.java
@@ -587,7 +587,7 @@ public class IoTDBDataBackTool {
       for (int j = 0; j < dirs.length; j++) {
         if (i == tiers.length - 1
             && j == dirs.length - 1
-            && IoTDBConstant.OBJECT_STORAGE_DIR.equals(dirs[j])) {
+            && IoTDBConstant.OBJECT_STORAGE_DIR.equalsIgnoreCase(dirs[j])) {
           break;
         }
         // Resolve before joining so an empty local entry retains its place in 
the tier.
@@ -600,7 +600,7 @@ public class IoTDBDataBackTool {
 
   private static String getObjectStorageSuffix(String dataDirs) {
     int separator = Math.max(dataDirs.lastIndexOf(';'), 
dataDirs.lastIndexOf(','));
-    if (IoTDBConstant.OBJECT_STORAGE_DIR.equals(dataDirs.substring(separator + 
1))) {
+    if 
(IoTDBConstant.OBJECT_STORAGE_DIR.equalsIgnoreCase(dataDirs.substring(separator 
+ 1))) {
       return dataDirs.substring(Math.max(0, separator));
     }
     return "";
@@ -875,7 +875,7 @@ public class IoTDBDataBackTool {
   private static boolean matchDirectory(String inputDir, String patternDir) {
     String[] inputLevels = inputDir.split(",");
     String[] patternLevels = patternDir.split(",");
-    return inputLevels.length == patternLevels.length || patternLevels.length 
== 1;
+    return inputLevels.length == patternLevels.length || inputLevels.length == 
1;
   }
 
   private static void initDataNodeProperties(Properties properties) {
diff --git 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/backup/IoTDBDataBackToolTest.java
 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/backup/IoTDBDataBackToolTest.java
index 8a1c3d2e283..062fb77bbdd 100644
--- 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/backup/IoTDBDataBackToolTest.java
+++ 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/backup/IoTDBDataBackToolTest.java
@@ -63,24 +63,41 @@ public class IoTDBDataBackToolTest {
 
   @Test
   public void testBackupAllDataDirectoriesWithWhitespace() throws Exception {
-    Path second = temporaryFolder.getRoot().toPath().resolve("disk two");
-    writeSample(home.resolve("first"), "first");
-    writeSample(second, "second");
-    writeSample(home.resolve("OBJECT_STORAGE"), "third");
+    assertBackupWithWhitespace("OBJECT_STORAGE");
+  }
+
+  @Test
+  public void testBackupWithLowercaseObjectStorage() throws Exception {
+    assertBackupWithWhitespace("object_storage");
+  }
+
+  private void assertBackupWithWhitespace(String marker) throws Exception {
+    Path first = home.resolve("first");
+    Path second = temporaryFolder.newFolder("disk two").toPath();
+    writeSequenceFile(first, "first");
+    writeSequenceFile(second, "second");
+    writeSequenceFile(home, "home");
+    writeSample(home.resolve(marker), "decoy");
 
     Properties properties = new Properties();
-    properties.setProperty("dn_data_dirs", "first, " + second + " ,; 
OBJECT_STORAGE");
-    Properties restored = runBackup(properties);
+    properties.setProperty("dn_data_dirs", "first, " + second + " ,; " + 
marker);
+    String[] tiers = 
runBackup(properties).getProperty("dn_data_dirs").split(";", -1);
 
+    assertEquals(2, tiers.length);
+    assertTrue(tiers[1], marker.equalsIgnoreCase(tiers[1]));
     Path data = backup.resolve("data").resolve("datanode").resolve("data");
-    String restoredDataDirs = restored.getProperty("dn_data_dirs");
-    assertEquals(
-        data.resolve("data1") + "," + data.resolve("data2") + ";" + 
data.resolve("data3"),
-        restoredDataDirs);
-    String[] dirs = restoredDataDirs.split("[,;]");
-    assertEquals("first", Files.readString(Path.of(dirs[0], "sample")));
-    assertEquals("second", Files.readString(Path.of(dirs[1], "sample")));
-    assertEquals("third", Files.readString(Path.of(dirs[2], "sample")));
+    String[] dirs = tiers[0].split(",", -1);
+    assertArrayEquals(
+        new String[] {
+          data.resolve("data1").toString(),
+          data.resolve("data2").toString(),
+          data.resolve("data3").toString()
+        },
+        dirs);
+    assertRestoredSequenceFile(first, dirs[0]);
+    assertRestoredSequenceFile(second, dirs[1]);
+    assertRestoredSequenceFile(home, dirs[2]);
+    assertFalse(Files.exists(data.resolve("data4")));
   }
 
   @Test
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
index bd2895f8876..2b7f90633c4 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
@@ -1500,7 +1500,7 @@ public class IoTDBConfig implements 
DefaultEncodingProvider {
   private void formulateDataDirs(String[][] tierDataDirs) {
     for (int i = 0; i < tierDataDirs.length; i++) {
       for (int j = 0; j < tierDataDirs[i].length; j++) {
-        if (tierDataDirs[i][j].equals(OBJECT_STORAGE_DIR)) {
+        if (tierDataDirs[i][j].equalsIgnoreCase(OBJECT_STORAGE_DIR)) {
           // Notice: dataNodeId hasn't been initialized
           tierDataDirs[i][j] = 
FSUtils.getOSDefaultPath(getObjectStorageBucket(), dataNodeId);
         }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
index 4eec35ca33d..b4bde78781d 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
@@ -2215,7 +2215,11 @@ public class IoTDBDescriptor {
     String[] tiers = dataDirs.split(IoTDBConstant.TIER_SEPARATOR);
     String[][] tierDataDirs = new String[tiers.length][];
     for (int i = 0; i < tiers.length; ++i) {
-      tierDataDirs[i] = tiers[i].split(",");
+      // keep the last empty string if the last tier is empty, so use 
split(",", -1)
+      // String[] tiers = "hot,;cold".split(";", -1); // ["hot,", "cold"]
+      // String[] firstTier = tiers[0].split(",", -1); // ["hot", ""]
+      // empty string means using IOTDB_HOME
+      tierDataDirs[i] = tiers[i].split(",", -1);
       for (int j = 0; j < tierDataDirs[i].length; j++) {
         tierDataDirs[i][j] = tierDataDirs[i][j].trim();
       }
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntrySpillManager.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntrySpillManager.java
index 0525f9d6efd..f192d3254da 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntrySpillManager.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/DeviceEntrySpillManager.java
@@ -19,6 +19,7 @@
 
 package org.apache.iotdb.db.queryengine.plan.relational.metadata.spill;
 
+import org.apache.iotdb.commons.concurrent.HashLock;
 import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId;
 import org.apache.iotdb.commons.utils.TestOnly;
 import org.apache.iotdb.db.conf.IoTDBDescriptor;
@@ -37,12 +38,13 @@ import java.nio.file.SimpleFileVisitor;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicBoolean;
 
 public final class DeviceEntrySpillManager {
 
   private static final Logger LOGGER = 
LoggerFactory.getLogger(DeviceEntrySpillManager.class);
 
+  // Owner and query cleanup walk overlapping trees. Keep the directory stable 
during segment I/O.
+  private final HashLock directoryLocks = new HashLock(1024);
   private final ConcurrentHashMap<String, Set<Path>> queryDirectories = new 
ConcurrentHashMap<>();
 
   private DeviceEntrySpillManager() {}
@@ -52,39 +54,53 @@ public final class DeviceEntrySpillManager {
   }
 
   public Path register(String queryId, PlanNodeId planNodeId) throws 
IOException {
-    Path ownerDirectory = resolveOwnerDirectory(queryId, planNodeId.getId());
-    Files.createDirectories(ownerDirectory);
-    queryDirectories
-        .computeIfAbsent(queryId, ignored -> ConcurrentHashMap.newKeySet())
-        .add(ownerDirectory);
-    return ownerDirectory;
+    directoryLocks.writeLock(queryId);
+    try {
+      Path ownerDirectory = resolveOwnerDirectory(queryId, planNodeId.getId());
+      Files.createDirectories(ownerDirectory);
+      queryDirectories
+          .computeIfAbsent(queryId, ignored -> ConcurrentHashMap.newKeySet())
+          .add(ownerDirectory);
+      return ownerDirectory;
+    } finally {
+      directoryLocks.writeUnlock(queryId);
+    }
   }
 
   public void deregisterOwner(String queryId, Path ownerDirectory) throws 
IOException {
-    deleteDirectoryIfExists(ownerDirectory);
-    AtomicBoolean removedLastOwner = new AtomicBoolean(false);
-    queryDirectories.computeIfPresent(
-        queryId,
-        (ignored, owners) -> {
-          owners.remove(ownerDirectory);
-          if (owners.isEmpty()) {
-            removedLastOwner.set(true);
-            return null;
-          }
-          return owners;
-        });
-    if (removedLastOwner.get()) {
-      deleteDirectoryIfExists(resolveQueryDirectory(queryId));
+    directoryLocks.writeLock(queryId);
+    try {
+      deleteDirectoryIfExists(ownerDirectory);
+      Set<Path> owners = queryDirectories.get(queryId);
+      if (owners != null) {
+        owners.remove(ownerDirectory);
+        if (owners.isEmpty()) {
+          deleteDirectoryIfExists(resolveQueryDirectory(queryId));
+          queryDirectories.remove(queryId);
+        }
+      }
+    } finally {
+      directoryLocks.writeUnlock(queryId);
     }
   }
 
   public void deregisterQuery(String queryId) throws IOException {
-    queryDirectories.remove(queryId);
-    deleteDirectoryIfExists(resolveQueryDirectory(queryId));
+    directoryLocks.writeLock(queryId);
+    try {
+      queryDirectories.remove(queryId);
+      deleteDirectoryIfExists(resolveQueryDirectory(queryId));
+    } finally {
+      directoryLocks.writeUnlock(queryId);
+    }
   }
 
   public byte[] readSegment(String queryId, String planNodeId, int segmentId) 
throws IOException {
-    return Files.readAllBytes(resolveSegment(queryId, planNodeId, segmentId));
+    directoryLocks.readLock(queryId);
+    try {
+      return Files.readAllBytes(resolveSegment(queryId, planNodeId, 
segmentId));
+    } finally {
+      directoryLocks.readUnlock(queryId);
+    }
   }
 
   public Path resolveSegment(String queryId, String planNodeId, int segmentId) 
throws IOException {
@@ -97,6 +113,7 @@ public final class DeviceEntrySpillManager {
 
   public void deleteSegment(String queryId, String dataSetId, int segmentId) 
throws IOException {
     Path file = null;
+    directoryLocks.readLock(queryId);
     try {
       file = getRegisteredSegmentPath(queryId, dataSetId, segmentId);
       Files.deleteIfExists(file);
@@ -107,6 +124,8 @@ public final class DeviceEntrySpillManager {
               DataNodeQueryMessages
                   
.LOG_FAILED_TO_CLEAN_DEVICEENTRY_SPILL_DIRECTORY_FOR_QUERY_ARG_53D9C1FC,
               file));
+    } finally {
+      directoryLocks.readUnlock(queryId);
     }
   }
 
diff --git 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/SegmentDeviceEntrySourceTest.java
 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/SegmentDeviceEntrySourceTest.java
index 23de82dec00..9c4b2c2d262 100644
--- 
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/SegmentDeviceEntrySourceTest.java
+++ 
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/metadata/spill/SegmentDeviceEntrySourceTest.java
@@ -44,6 +44,7 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 
+import static org.awaitility.Awaitility.await;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThrows;
@@ -256,6 +257,39 @@ public class SegmentDeviceEntrySourceTest {
     
assertFalse(Files.exists(queryDirectory.resolve("device-entry").resolve(queryId)));
   }
 
+  @Test
+  public void testLastOwnerCleanupPreservesNewOwner() throws Exception {
+    String queryId = "q-register-during-cleanup";
+    DeviceEntrySpillManager manager = DeviceEntrySpillManager.getInstance();
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    try {
+      for (int i = 0; i < 8; i++) {
+        Path oldOwner = manager.register(queryId, new PlanNodeId("old"));
+        Future<?> cleanup =
+            executor.submit(
+                () -> {
+                  manager.deregisterOwner(queryId, oldOwner);
+                  return null;
+                });
+        // The old owner disappears before cleanup deletes the query directory.
+        await()
+            .pollInSameThread()
+            .pollInterval(0, TimeUnit.MILLISECONDS)
+            .atMost(10, TimeUnit.SECONDS)
+            .until(() -> cleanup.isDone() || Files.notExists(oldOwner));
+        Path newOwner = manager.register(queryId, new PlanNodeId("new"));
+        cleanup.get(10, TimeUnit.SECONDS);
+
+        assertTrue(Files.isDirectory(newOwner));
+        manager.deregisterOwner(queryId, newOwner);
+        assertFalse(Files.exists(newOwner.getParent()));
+      }
+    } finally {
+      executor.shutdownNow();
+      assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+    }
+  }
+
   @Test
   public void testQueryCleanupDeletesAllOwners() throws Exception {
     String queryId = "q-deferred-cleanup";
diff --git 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/HashLock.java
 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/HashLock.java
index a79653503ac..6c98e501057 100644
--- 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/HashLock.java
+++ 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/HashLock.java
@@ -18,6 +18,8 @@
  */
 package org.apache.iotdb.commons.concurrent;
 
+import org.apache.iotdb.commons.i18n.CommonMessages;
+
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 /**
@@ -29,15 +31,18 @@ public class HashLock {
 
   private static final int DEFAULT_LOCK_NUM = 100;
 
-  private ReentrantReadWriteLock[] locks;
-  private int lockSize;
+  private final ReentrantReadWriteLock[] locks;
+  private final int lockSize;
 
   public HashLock() {
-    this.lockSize = DEFAULT_LOCK_NUM;
-    init();
+    this(DEFAULT_LOCK_NUM);
   }
 
-  private void init() {
+  public HashLock(int lockSize) {
+    if (lockSize <= 0) {
+      throw new IllegalArgumentException(CommonMessages.SIZE_MUST_BE_POSITIVE);
+    }
+    this.lockSize = lockSize;
     locks = new ReentrantReadWriteLock[lockSize];
     for (int i = 0; i < lockSize; i++) {
       locks[i] = new ReentrantReadWriteLock();
diff --git 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/IoTDBConstant.java
 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/IoTDBConstant.java
index df55a3af8a3..98315a6039a 100644
--- 
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/IoTDBConstant.java
+++ 
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/IoTDBConstant.java
@@ -372,7 +372,7 @@ public class IoTDBConstant {
 
   public static final String TIER_SEPARATOR = ";";
 
-  public static final String OBJECT_STORAGE_DIR = "object_storage";
+  public static final String OBJECT_STORAGE_DIR = "OBJECT_STORAGE";
 
   public static final String TTL_INFINITE = "INF";
 
diff --git 
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/concurrent/HashLockTest.java
 
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/concurrent/HashLockTest.java
new file mode 100644
index 00000000000..f1fae08c5cc
--- /dev/null
+++ 
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/concurrent/HashLockTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.commons.concurrent;
+
+import org.junit.Test;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class HashLockTest {
+
+  @Test
+  public void testRejectsNonPositiveLockSize() {
+    assertThrows(IllegalArgumentException.class, () -> new HashLock(0));
+    assertThrows(IllegalArgumentException.class, () -> new HashLock(-1));
+  }
+
+  @Test
+  public void testCustomLockSizeSeparatesKeys() throws Exception {
+    HashLock lock = new HashLock(1024);
+    ExecutorService executor = Executors.newSingleThreadExecutor();
+    lock.writeLock(0);
+    try {
+      // Keys 0 and 100 collide with the default size.
+      Future<?> reader =
+          executor.submit(
+              () -> {
+                lock.readLock(100);
+                lock.readUnlock(100);
+              });
+      reader.get(10, TimeUnit.SECONDS);
+    } finally {
+      lock.writeUnlock(0);
+      executor.shutdownNow();
+      assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+    }
+  }
+}

Reply via email to