Protect reftable readers during stale reload

When an externally updated `tables.list` causes `addReftable()` to fail,
the system triggers a stack reload. Previously, this reload occurred
before obtaining the cached-reader lock.

This lock inversion was unsafe. The reload operation could close a table
that was concurrently being read by a ref lookup, which resulted in a
`ClosedChannelException`.

Fix this by acquiring the cached-reader lock before reloading the stack.
This ensures that tables remain open and safe to access while concurrent
threads are actively reading them.

This is similar to fix [1] and it applies the same guard to the stale
reload from addReftable().

Hold the reader lock across the add, stale reload, and cache clear so
reload cannot close a table until the concurrent readers finish.

[1] https://eclipse.gerrithub.io/c/eclipse-jgit/jgit/+/1216979

Bug: Issue 460019541
Change-Id: I9d210becf5b5665deecfdcf5a87c6a8c26198d07
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java
index 5756b41..e5d82d1 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java
@@ -40,9 +40,12 @@
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
 
 import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.internal.storage.reftable.ReftableDatabase;
 import org.eclipse.jgit.lib.AnyObjectId;
 import org.eclipse.jgit.lib.Constants;
 import org.eclipse.jgit.lib.NullProgressMonitor;
@@ -181,6 +184,88 @@ public RefUpdate.Result call() throws Exception {
 		}
 	}
 
+	/**
+	 * Reproduce a stale reload closing the cached reader needed for a ref lookup.
+	 *
+	 * <p>The test has three phases:
+	 * <ul>
+	 * <li>Look up master and cache the table reader used for that lookup.</li>
+	 * <li>Use another repository to replace the reftable files, making the cached
+	 * reader stale.</li>
+	 * <li>Make {@code addReftable()} fail, so it reloads the files, then look up master
+	 * again. The lookup must return master's object ID.</li>
+	 * </ul>
+	 *
+	 * <p>This test covers the regression where {@code addReftable()} reloaded before
+	 * taking the ref database's cached-reader lock. Reload could close the cached
+	 * reader before the final lookup used it, causing
+	 * {@link java.nio.channels.ClosedChannelException}.
+	 */
+	@Test
+	public void testFailedAddDoesNotCloseCachedReader() throws Exception {
+		FileReftableDatabase refDb = (FileReftableDatabase) db
+				.getRefDatabase();
+		refDb.setAutoRefresh(true);
+
+		// This first checks auto-refresh, then opens and caches a reader for the
+		// current reftable files.
+		Ref master = refDb.exactRef("refs/heads/master");
+		ReftableDatabase reftableDb = refDb.getReftableDatabase();
+
+		try (FileRepository other = new FileRepository(db.getDirectory())) {
+			// Let's use a second repository object for the same directory to change
+			// the reftable files without updating refDb's in-memory view of them.
+			RefUpdate update = other.updateRef("refs/heads/new");
+			update.setNewObjectId(master.getObjectId());
+			assertEquals(Result.NEW, update.update());
+			// This replaces the old table files on disk. refDb still has a reader
+			// for one of those old files, so its view is now stale.
+			((FileReftableDatabase) other.getRefDatabase()).compactFully();
+		}
+
+		// Prepare a task that calls `addReftable()`:
+		// - It makes refDb reload its stale table list.
+		// - That reload closes refDb's old table reader.
+		// Without the lock, concurrent exactRef() uses that closed cached reader
+		// and throws ClosedChannelException.
+		Thread reloader = new Thread(new FutureTask<>(
+				() -> refDb.addReftable(w -> {
+					// noop
+				})));
+
+		// Use the real reader lock to coordinate the main thread and the reloader.
+		// exactRef() uses it while reading a cached table.
+		// The reloader must wait here before reload() can close that table.
+		ReentrantLock readerLock = reftableDb.getLock();
+		readerLock.lock();
+		try {
+			reloader.start();
+			// Wait until the reloader is blocked on readerLock. Without the fix,
+			// reload() already closed the cached reader before it gets here. With
+			// the fix, reload() has not happened yet.
+			waitForQueuedThread(readerLock, reloader);
+
+			// refDb.exactRef() would auto-refresh again and hide the gap before it
+			// uses the cached reader.
+			assertEquals(master.getObjectId(),
+					reftableDb.exactRef(master.getName()).getObjectId());
+		} finally {
+			readerLock.unlock();
+			reloader.join();
+		}
+	}
+
+	private static void waitForQueuedThread(ReentrantLock lock,
+			Thread thread) throws InterruptedException {
+		long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+		while (!lock.hasQueuedThread(thread)) {
+			if (System.nanoTime() >= deadline) {
+				throw new AssertionError("reloader did not reach the reader lock");
+			}
+			Thread.sleep(10);
+		}
+	}
+
 	@Test
 	public void testCompactFully() throws Exception {
 		ObjectId c1 = db.resolve("master^^");
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/FileReftableDatabase.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/FileReftableDatabase.java
index c46a17b..17241e0 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/FileReftableDatabase.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/FileReftableDatabase.java
@@ -402,15 +402,30 @@ public void create() throws IOException {
 				true);
 	}
 
-	private boolean addReftable(FileReftableStack.Writer w) throws IOException {
-		if (!reftableStack.addReftable(w)) {
-			reftableStack.reload();
+	// Visible for testing
+	boolean addReftable(FileReftableStack.Writer w) throws IOException {
+		// reload() can close a table reader used by reftableDatabase's cached
+		// merged table. Hold its reader lock so a ref lookup cannot use that table
+		// while reload() runs.
+		ReentrantLock lock = getLock();
+		lock.lock();
+		try {
+			if (!reftableStack.addReftable(w)) {
+				reftableStack.reload();
+				reftableDatabase.clearCache();
+				return false;
+			}
 			reftableDatabase.clearCache();
-			return false;
-		}
-		reftableDatabase.clearCache();
 
-		return true;
+			return true;
+		} finally {
+			lock.unlock();
+		}
+	}
+
+	// Visible for testing
+	ReftableDatabase getReftableDatabase() {
+		return reftableDatabase;
 	}
 
 	private class FileReftableBatchRefUpdate extends ReftableBatchRefUpdate {