Copilot commented on code in PR #3695:
URL: https://github.com/apache/celeborn/pull/3695#discussion_r3295740759


##########
worker/src/test/java/org/apache/celeborn/service/deploy/worker/shuffledb/RocksDBRecoverySuiteJ.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.celeborn.service.deploy.worker.shuffledb;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.celeborn.common.CelebornConf;
+import org.apache.celeborn.common.util.JavaUtils;
+import org.apache.celeborn.common.util.ThreadUtils;
+import org.apache.celeborn.service.deploy.worker.WorkerSource;
+
+public class RocksDBRecoverySuiteJ {
+
+  private File dbDir;
+  private File dbFile;
+  private CelebornConf defaultConf;
+  private CelebornConf confWithRecovery;
+  private WorkerSource workerSource;
+  private StoreVersion version;
+
+  @Before
+  public void setUp() throws IOException {
+    dbDir = Files.createTempDirectory("rocksdb-recovery-test").toFile();
+    dbFile = new File(dbDir, "test-db");
+    defaultConf = new CelebornConf();
+    confWithRecovery = new CelebornConf();
+    confWithRecovery.set("celeborn.metadata.autoRecovery.enabled", "true");
+    workerSource = new WorkerSource(defaultConf);
+    version = new StoreVersion(1, 0);
+  }
+
+  @After
+  public void tearDown() throws IOException {
+    workerSource.destroy();
+    JavaUtils.deleteRecursively(dbDir);
+  }
+
+  @Test
+  public void testRecoveryAfterCorruption() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, defaultConf);
+    assertNotNull(db);
+
+    byte[] key = "test-key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "test-value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+
+    byte[] result = db.get(key);
+    assertNotNull(result);
+    assertEquals("test-value", new String(result, StandardCharsets.UTF_8));
+
+    db.close();
+
+    // Corrupt the DB by overwriting SST files
+    corruptDbFiles(dbFile);
+
+    // Reopen — initRockDB will wipe and recreate since files are corrupt
+    db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, workerSource, 
defaultConf);
+    assertNotNull(db);
+
+    // Data is gone after wipe-and-recreate, but DB is functional
+    byte[] newKey = "new-key".getBytes(StandardCharsets.UTF_8);
+    byte[] newValue = "new-value".getBytes(StandardCharsets.UTF_8);
+    db.put(newKey, newValue);
+
+    result = db.get(newKey);
+    assertNotNull(result);
+    assertEquals("new-value", new String(result, StandardCharsets.UTF_8));
+    db.close();
+  }
+
+  @Test
+  public void testConcurrentRecoveryOnlyReopensOnce() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, confWithRecovery);
+    assertNotNull(db);
+
+    byte[] key = "key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+
+    RocksDB rocksDB = (RocksDB) db;
+    assertEquals(0, rocksDB.getDbGeneration());
+
+    int threadCount = 8;
+    CyclicBarrier barrier = new CyclicBarrier(threadCount);
+    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+
+    // Force a recovery to simulate a RocksDBException scenario
+    rocksDB.forceRecovery();
+    long genAfterFirstRecovery = rocksDB.getDbGeneration();

Review Comment:
   This comment says the test is simulating a `RocksDBException` scenario, but 
the test only calls `forceRecovery()` directly (no exception is triggered). 
That’s a bit misleading when reading the test intent.
   



##########
worker/src/main/java/org/apache/celeborn/service/deploy/worker/shuffledb/RocksDB.java:
##########
@@ -17,63 +17,217 @@
 
 package org.apache.celeborn.service.deploy.worker.shuffledb;
 
+import java.io.File;
 import java.io.IOException;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 import org.rocksdb.RocksDBException;
 import org.rocksdb.WriteOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import org.apache.celeborn.common.CelebornConf;
 import org.apache.celeborn.common.metrics.source.AbstractSource;
 
 /**
  * RocksDB implementation of the local KV storage used to persist the shuffle 
state.
  *
+ * <p>This class supports automatic recovery from RocksDB failures when {@code 
autoRecoveryEnabled}
+ * is set to {@code true}. When a put/get/delete operation encounters a {@link 
RocksDBException},
+ * the DB instance is closed and reopened. If the safe reopen fails, the 
exception is propagated.
+ * When {@code autoRecoveryEnabled} is {@code false}, exceptions are 
propagated directly without any
+ * recovery attempt.
+ *
+ * <p>Iterators obtained via {@link #iterator()} are invalidated after a 
recovery event and will
+ * throw {@link IllegalStateException} on subsequent use.
+ *
  * <p>Note: code copied from Apache Spark.
  */
 public class RocksDB extends DB {
-  private final org.rocksdb.RocksDB db;
+  private static final Logger logger = LoggerFactory.getLogger(RocksDB.class);
+
+  private volatile ManagedRocksDB db;
   private final WriteOptions SYNC_WRITE_OPTIONS = new 
WriteOptions().setSync(true);
+  private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
+  private final AtomicLong dbGeneration = new AtomicLong(0);
+  private final File dbFile;
+  private final boolean autoRecoveryEnabled;
+  private final CelebornConf conf;
+  private volatile boolean closed = false;
 
-  public RocksDB(org.rocksdb.RocksDB db, AbstractSource source, DBBackend 
dbBackend) {
+  public RocksDB(
+      ManagedRocksDB db,
+      AbstractSource source,
+      DBBackend dbBackend,
+      File dbFile,
+      CelebornConf conf) {
     super(source, dbBackend);
     this.db = db;
+    this.dbFile = dbFile;
+    this.autoRecoveryEnabled = conf.metadataAutoRecoveryEnabled();
+    this.conf = conf;
+  }
+
+  /** Attempts to recover the DB by closing and safely reopening it. */
+  private void tryRecoverDBInstance(long failedGeneration) {
+    if (isClosed()) {
+      return;
+    }
+
+    rwLock.writeLock().lock();
+    try {
+      if (dbGeneration.get() != failedGeneration) {
+        logger.info(
+            "Recovery already attempted by another thread (generation {} -> 
{}); "
+                + "if DB is still unhealthy, the next operation will retry",
+            failedGeneration,
+            dbGeneration.get());
+        return;
+      }
+
+      if (isClosed()) {
+        return;
+      }
+
+      try {
+        if (db != null) {
+          db.close();
+        }
+      } catch (Exception e) {
+        logger.warn("Failed to close RocksDB instance", e);
+      }
+
+      dbGeneration.incrementAndGet();
+
+      try {
+        db = RocksDBProvider.reopenRocksDB(dbFile, conf);
+        logger.info("RocksDB instance recovered at {}", dbFile);
+      } catch (IOException e) {
+        logger.error("Safe reopen failed for RocksDB at {}. ", dbFile, e);
+      }
+    } finally {
+      rwLock.writeLock().unlock();
+    }
+  }
+
+  private void checkState() {
+    if (isClosed()) {
+      throw new IllegalStateException("DB is closed");
+    }
+  }
+
+  private boolean isClosed() {
+    return closed;
+  }
+
+  @FunctionalInterface
+  interface CheckedSupplier<T> {
+    T get() throws RocksDBException;
+  }
+
+  @FunctionalInterface
+  interface CheckedRunnable {
+    void run() throws RocksDBException;
+  }
+
+  private <T> T withRecovery(CheckedSupplier<T> operation) throws 
RocksDBException {
+    checkState();
+    long generation = 0;
+    try {
+      rwLock.readLock().lock();
+      try {
+        if (isClosed()) {
+          throw new IllegalStateException("DB is closed");
+        }
+        generation = dbGeneration.get();
+        return operation.get();
+      } finally {
+        rwLock.readLock().unlock();
+      }
+    } catch (RocksDBException e) {
+      if (autoRecoveryEnabled) {
+        tryRecoverDBInstance(generation);
+      }
+      throw e;

Review Comment:
   The main behavior change is recovery being triggered from the `catch 
(RocksDBException)` path, but the added unit tests only exercise recovery via 
`forceRecovery()` (i.e., they don’t assert that a real `RocksDBException` from 
put/get/delete causes a reopen and that subsequent operations succeed). Adding 
a test that injects a failing underlying RocksDB (e.g., Mockito-mock 
`org.rocksdb.RocksDB#put` to throw once, then verify the next `put/get` works) 
would protect the primary contract of `withRecovery`.



##########
common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala:
##########
@@ -4520,6 +4528,62 @@ object CelebornConf extends Logging {
       .checkValues(Set("LEVELDB", "ROCKSDB"))
       .createWithDefault("ROCKSDB")
 
+  val WORKER_RECOVER_DB_AUTO_RECOVERY: ConfigEntry[Boolean] =
+    buildConf("celeborn.metadata.autoRecovery.enabled")
+      .categories("worker")
+      .doc("If true, the metadata DB will automatically attempt to recover 
from RocksDBException " +
+        "errors during put/get/delete operations. Recovery tries a safe 
reopen. " +
+        "If false, RocksDBException errors are propagated directly to the 
caller.")
+      .version("0.7.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private val rocksDBCompressionTypes: Set[String] = Set(
+    "NO_COMPRESSION",
+    "SNAPPY_COMPRESSION",
+    "ZLIB_COMPRESSION",
+    "BZLIB2_COMPRESSION",
+    "LZ4_COMPRESSION",
+    "LZ4HC_COMPRESSION",
+    "XPRESS_COMPRESSION",
+    "ZSTD_COMPRESSION",
+    "DISABLE_COMPRESSION_OPTION")

Review Comment:
   `rocksDBCompressionTypes` includes `"BZLIB2_COMPRESSION"`, but RocksDB’s 
`org.rocksdb.CompressionType` enum uses `BZIP2_COMPRESSION`. This value will 
pass config validation but later fail at `CompressionType.valueOf(...)` with 
`IllegalArgumentException` if users set it.
   



##########
worker/src/test/java/org/apache/celeborn/service/deploy/worker/shuffledb/RocksDBRecoverySuiteJ.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.celeborn.service.deploy.worker.shuffledb;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.celeborn.common.CelebornConf;
+import org.apache.celeborn.common.util.JavaUtils;
+import org.apache.celeborn.common.util.ThreadUtils;
+import org.apache.celeborn.service.deploy.worker.WorkerSource;
+
+public class RocksDBRecoverySuiteJ {
+
+  private File dbDir;
+  private File dbFile;
+  private CelebornConf defaultConf;
+  private CelebornConf confWithRecovery;
+  private WorkerSource workerSource;
+  private StoreVersion version;
+
+  @Before
+  public void setUp() throws IOException {
+    dbDir = Files.createTempDirectory("rocksdb-recovery-test").toFile();
+    dbFile = new File(dbDir, "test-db");
+    defaultConf = new CelebornConf();
+    confWithRecovery = new CelebornConf();
+    confWithRecovery.set("celeborn.metadata.autoRecovery.enabled", "true");
+    workerSource = new WorkerSource(defaultConf);
+    version = new StoreVersion(1, 0);
+  }
+
+  @After
+  public void tearDown() throws IOException {
+    workerSource.destroy();
+    JavaUtils.deleteRecursively(dbDir);
+  }
+
+  @Test
+  public void testRecoveryAfterCorruption() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, defaultConf);
+    assertNotNull(db);
+
+    byte[] key = "test-key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "test-value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+
+    byte[] result = db.get(key);
+    assertNotNull(result);
+    assertEquals("test-value", new String(result, StandardCharsets.UTF_8));
+
+    db.close();
+
+    // Corrupt the DB by overwriting SST files
+    corruptDbFiles(dbFile);
+
+    // Reopen — initRockDB will wipe and recreate since files are corrupt
+    db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, workerSource, 
defaultConf);
+    assertNotNull(db);
+
+    // Data is gone after wipe-and-recreate, but DB is functional
+    byte[] newKey = "new-key".getBytes(StandardCharsets.UTF_8);
+    byte[] newValue = "new-value".getBytes(StandardCharsets.UTF_8);
+    db.put(newKey, newValue);
+
+    result = db.get(newKey);
+    assertNotNull(result);
+    assertEquals("new-value", new String(result, StandardCharsets.UTF_8));
+    db.close();
+  }
+
+  @Test
+  public void testConcurrentRecoveryOnlyReopensOnce() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, confWithRecovery);
+    assertNotNull(db);
+
+    byte[] key = "key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+
+    RocksDB rocksDB = (RocksDB) db;
+    assertEquals(0, rocksDB.getDbGeneration());
+
+    int threadCount = 8;
+    CyclicBarrier barrier = new CyclicBarrier(threadCount);
+    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+
+    // Force a recovery to simulate a RocksDBException scenario
+    rocksDB.forceRecovery();
+    long genAfterFirstRecovery = rocksDB.getDbGeneration();
+    assertEquals(1, genAfterFirstRecovery);
+
+    // Now launch concurrent threads that all try to trigger recovery at the 
same generation.
+    // genAfterFirstRecovery is captured once so every thread calls 
forceRecovery with the
+    // same stale-generation value; only one can win the write-lock check and 
actually reopen.
+    List<Future<?>> futures = new ArrayList<>();
+    for (int i = 0; i < threadCount; i++) {
+      futures.add(
+          executor.submit(
+              () -> {
+                try {
+                  barrier.await();
+                  rocksDB.forceRecovery(genAfterFirstRecovery);
+                } catch (Exception e) {
+                  throw new RuntimeException(e);
+                }
+              }));
+    }
+
+    try {
+      for (Future<?> f : futures) {
+        f.get();
+      }
+    } finally {
+      ThreadUtils.shutdown(executor);
+    }
+
+    // Generation should have incremented exactly once more (all threads saw 
the same generation
+    // and only one wins the write lock to perform the actual reopen; the rest 
observe the
+    // advanced generation and bail without reopening)
+    assertEquals(genAfterFirstRecovery + 1, rocksDB.getDbGeneration());
+
+    // DB should still be usable
+    db.put(key, value);
+    byte[] result = db.get(key);
+    assertNotNull(result);
+    assertEquals("value", new String(result, StandardCharsets.UTF_8));
+
+    db.close();
+  }
+
+  @Test
+  public void testOperationsAfterCloseDoNotResurrect() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, confWithRecovery);
+    assertNotNull(db);
+
+    byte[] key = "key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+    db.close();
+
+    // All operations after close should throw IllegalStateException
+    DB closedDb = db;
+    assertThrows(IllegalStateException.class, () -> 
closedDb.put("k".getBytes(), "v".getBytes()));
+
+    assertThrows(IllegalStateException.class, () -> 
closedDb.get("k".getBytes()));
+
+    assertThrows(IllegalStateException.class, () -> 
closedDb.delete("k".getBytes()));
+
+    assertThrows(IllegalStateException.class, closedDb::iterator);
+  }
+
+  @Test
+  public void testIteratorInvalidatedAfterRecovery() throws Exception {
+    DB db = DBProvider.initDB(DBBackend.ROCKSDB, dbFile, version, 
workerSource, confWithRecovery);
+    assertNotNull(db);
+
+    byte[] key = "key".getBytes(StandardCharsets.UTF_8);
+    byte[] value = "value".getBytes(StandardCharsets.UTF_8);
+    db.put(key, value);
+
+    // Get an iterator at generation 0
+    DBIterator iter = db.iterator();
+    iter.seek(key);
+    assertTrue(iter.hasNext());
+
+    // Force a recovery so the generation increments
+    RocksDB rocksDB = (RocksDB) db;
+    assertEquals(0, rocksDB.getDbGeneration());
+    rocksDB.forceRecovery();
+    assertEquals(1, rocksDB.getDbGeneration());
+
+    // The stale iterator should throw on hasNext, next, and seek
+    assertThrows(IllegalStateException.class, iter::hasNext);
+    assertThrows(IllegalStateException.class, iter::next);
+    assertThrows(IllegalStateException.class, () -> iter.seek(key));
+
+    // A new iterator should work fine
+    DBIterator newIter = db.iterator();
+    newIter.seek(key);
+    assertTrue(newIter.hasNext());
+    newIter.close();
+
+    db.close();
+  }
+
+  private void corruptDbFiles(File dir) throws IOException {
+    if (dir.isDirectory()) {
+      File[] files = dir.listFiles();
+      if (files != null) {
+        for (File f : files) {
+          if (f.isFile()
+              && (f.getName().endsWith(".sst")
+                  || f.getName().equals("MANIFEST-000001")
+                  || f.getName().equals("CURRENT"))) {

Review Comment:
   `corruptDbFiles` only corrupts the literal file name `MANIFEST-000001`, but 
RocksDB manifest numbers vary (e.g. `MANIFEST-000005`). This can make the 
corruption test flaky because the manifest may not be touched at all. Consider 
corrupting any manifest file by prefix instead.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to