Apache Lucene open-source search software
Fix possible lost signal in `ControlledRealTimeReopenThread` (#15830)
Viliam Durinaf3cc239898f9
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex c86ec77b26f..0f1332626f8 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -161,6 +161,8 @@ Bug Fixes* GITHUB#14971: Fix CachedExecutor thread pool leak in ConcurrentMergeSchedulerwhen IndexWriter initialization fails. (Su Beom)+* GITHUB#15830: Fix possible lost signal in `ControlledRealTimeReopenThread` (Viliam Durina)+* GITHUB#15838: Fix luke terms export failure on Windows when field names contain characters forbidden in file name (Binlong Gao)Changes in Runtime Behaviordiff --git a/lucene/core/src/java/org/apache/lucene/search/ControlledRealTimeReopenThread.java b/lucene/core/src/java/org/apache/lucene/search/ControlledRealTimeReopenThread.javaindex 4164e77bf94..230b664961b 100644--- a/lucene/core/src/java/org/apache/lucene/search/ControlledRealTimeReopenThread.java+++ b/lucene/core/src/java/org/apache/lucene/search/ControlledRealTimeReopenThread.java@@ -16,18 +16,20 @@*/package org.apache.lucene.search;+import static java.util.concurrent.TimeUnit.NANOSECONDS;+import java.io.Closeable;import java.io.IOException;-import java.util.concurrent.TimeUnit;-import java.util.concurrent.locks.Condition;-import java.util.concurrent.locks.ReentrantLock;+import java.time.Duration;+import java.util.concurrent.Semaphore;+import java.util.concurrent.atomic.AtomicLong;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.util.ThreadInterruptedException;/**- * Utility class that runs a thread to manage periodicc reopens of a {@link ReferenceManager}, with- * methods to wait for a specific index changes to become visible. When a given search request needs- * to see a specific index change, call the {#waitForGeneration} to wait for that change to be+ * A thread that manages periodic reopening of a {@link ReferenceManager}, with methods to wait for+ * a specific index generation to become visible. When a given search request needs to see a+ * specific index change, call {@link #waitForGeneration(long)} to wait for that change to be* visible. Note that this will only scale well if most searches do not need to wait for a specific* index generation.*@@ -38,45 +40,54 @@ public class ControlledRealTimeReopenThread<T> extends Thread implements Closeabprivate final long targetMaxStaleNS;private final long targetMinStaleNS;private final IndexWriter writer;+private volatile boolean finish;- private volatile long waitingGen;+ private final AtomicLong waitingGen = new AtomicLong(0);private volatile long searchingGen;- private long refreshStartGen;- private final ReentrantLock reopenLock = new ReentrantLock();- private final Condition reopenCond = reopenLock.newCondition();+ /// Releasing a permit to this semaphore is a signal to the background thread to check again.+ private final Semaphore reloadRequests = new Semaphore(0);++ private final Object waitingRoom = new Object();/**- * Create ControlledRealTimeReopenThread, to periodically reopen the {@link ReferenceManager}.+ * Create a new thread instance.+ *+ * <p>Potentially mark it as {@linkplain #setDaemon(boolean) a daemon} and {@link #start()} it+ * subsequently. Call {@link #close()} to cleanly stop this thread.*- * @param targetMaxStaleSec Maximum time until a new reader must be opened; this sets the upper- * bound on how slowly reopens may occur, when no caller is waiting for a specific generation- * to become visible.- * @param targetMinStaleSec Mininum time until a new reader can be opened; this sets the lower- * bound on how quickly reopens may occur, when a caller is waiting for a specific generation- * to become visible.+ * @param targetMaxStale Maximum time until a new reader must be opened; this sets the upper bound+ * on how slowly reopens may occur, when no caller is waiting for a specific generation to+ * become visible.+ * @param targetMinStale Minimum time until a new reader can be opened; if a refresh occurred+ * recently, it will wait at least this time until another refresh, even if a thread is+ * waiting for it.*/public ControlledRealTimeReopenThread(IndexWriter writer,ReferenceManager<T> manager,- double targetMaxStaleSec,- double targetMinStaleSec) {- if (targetMaxStaleSec < targetMinStaleSec) {+ Duration targetMaxStale,+ Duration targetMinStale) {+ this.writer = writer;+ this.manager = manager;+ this.targetMaxStaleNS = targetMaxStale.toNanos();+ this.targetMinStaleNS = targetMinStale.toNanos();++ if (targetMaxStaleNS < targetMinStaleNS) {throw new IllegalArgumentException("targetMaxScaleSec (= "- + targetMaxStaleSec+ + targetMaxStale+ ") < targetMinStaleSec (="- + targetMinStaleSec+ + targetMinStale+ ")");}- this.writer = writer;- this.manager = manager;- this.targetMaxStaleNS = (long) (1000000000 * targetMaxStaleSec);- this.targetMinStaleNS = (long) (1000000000 * targetMinStaleSec);+manager.addListener(new HandleRefresh());}private class HandleRefresh implements ReferenceManager.RefreshListener {+ private long refreshStartGen;+@Overridepublic void beforeRefresh() {// Save the gen as of when we started the reopen; the@@ -87,26 +98,20 @@ public class ControlledRealTimeReopenThread<T> extends Thread implements Closeab@Overridepublic void afterRefresh(boolean didRefresh) {- synchronized (ControlledRealTimeReopenThread.this) {+ synchronized (waitingRoom) {searchingGen = refreshStartGen;- ControlledRealTimeReopenThread.this.notifyAll();+ waitingRoom.notifyAll();}}}+ /** Stop this thread. Blocks until it terminates. */@Override- public synchronized void close() {- // System.out.println("NRT: set finish");-+ public void close() {finish = true;- // So thread wakes up and notices it should finish:- reopenLock.lock();- try {- reopenCond.signal();- } finally {- reopenLock.unlock();- }+ // Wake up the background thread.+ reloadRequests.release();try {join();@@ -116,14 +121,18 @@ public class ControlledRealTimeReopenThread<T> extends Thread implements Closeab// Max it out so any waiting search threads will return:searchingGen = Long.MAX_VALUE;- notifyAll();++ // Wake up waiters.+ synchronized (waitingRoom) {+ waitingRoom.notifyAll();+ }}/*** Waits for the target generation to become visible in the searcher. If the current searcher is- * older than the target generation, this method will block until the searcher is reopened, by- * another via {@link ReferenceManager#maybeRefresh} or until the {@link ReferenceManager} is- * closed.+ * older than the target generation, this method will block until the searcher is reopened by+ * another thread calling {@link ReferenceManager#maybeRefresh}, or until the {@link+ * ReferenceManager} is closed.** @param targetGen the generation to wait for*/@@ -133,103 +142,78 @@ public class ControlledRealTimeReopenThread<T> extends Thread implements Closeab/*** Waits for the target generation to become visible in the searcher, up to a maximum specified- * milli-seconds. If the current searcher is older than the target generation, this method will- * block until the searcher has been reopened by another thread via {@link+ * milliseconds. If the current searcher is older than the target generation, this method will+ * block until the searcher has been reopened by another thread calling {@link* ReferenceManager#maybeRefresh}, the given waiting time has elapsed, or until the {@link* ReferenceManager} is closed.*- * <p>NOTE: if the waiting time elapses before the requested target generation is available the- * current {@link SearcherManager} is returned instead.+ * <p>NOTE: if the waiting time elapses before the requested target generation is available, false+ * is returned.** @param targetGen the generation to wait for* @param maxMS maximum milliseconds to wait, or -1 to wait indefinitely- * @return true if the targetGeneration is now available, or false if maxMS wait time was exceeded+ * @return true if the targetGen is now available, or false if maxMS wait time was exceeded or+ * this instance was closed. True might also be returned if this call returned due to a {@link+ * #close()}*/- public synchronized boolean waitForGeneration(long targetGen, int maxMS)- throws InterruptedException {- if (targetGen > searchingGen) {- // Notify the reopen thread that the waitingGen has- // changed, so it may wake up and realize it should- // not sleep for much or any longer before reopening:- reopenLock.lock();-- // Need to find waitingGen inside lock as it's used to determine- // stale time- waitingGen = Math.max(waitingGen, targetGen);-- try {- reopenCond.signal();- } finally {- reopenLock.unlock();- }+ public boolean waitForGeneration(long targetGen, int maxMS) throws InterruptedException {+ synchronized (waitingRoom) {+ if (targetGen > searchingGen) {+ waitingGen.updateAndGet(v -> Math.max(v, targetGen));- long startMS = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());+ // Notify the reopen thread that the waitingGen has+ // changed, so it may wake up and realize it should+ // not sleep for much or any longer before reopening:+ reloadRequests.release();- while (targetGen > searchingGen) {- if (maxMS < 0) {- wait();- } else {- long msLeft = (startMS + maxMS) - TimeUnit.NANOSECONDS.toMillis(System.nanoTime());- if (msLeft <= 0) {- return false;+ long startNS = System.nanoTime();++ while (targetGen > searchingGen) {+ if (maxMS < 0) {+ waitingRoom.wait();} else {- wait(msLeft);+ long msLeft = maxMS - NANOSECONDS.toMillis(System.nanoTime() - startNS);+ if (msLeft <= 0) {+ return false;+ } else {+ waitingRoom.wait(msLeft);+ }}}}- }- return true;+ return true;+ }}@Overridepublic void run() {- // TODO: maybe use private thread ticktock timer, in- // case clock shift messes up nanoTime?long lastReopenStartNS = System.nanoTime();- // System.out.println("reopen: start");while (!finish) {- // TODO: try to guestimate how long reopen might- // take based on past data?+ // TODO: try to guesstimate how long reopen might take based on past data?- // Loop until we've waiting long enough before the- // next reopen:- while (!finish) {+ // True if we have someone waiting for reopened searcher:+ boolean hasWaiting = waitingGen.get() > searchingGen;+ final long nextReopenStartNS =+ lastReopenStartNS + (hasWaiting ? targetMinStaleNS : targetMaxStaleNS);- // Need lock before finding out if has waiting- reopenLock.lock();+ final long sleepNS = nextReopenStartNS - System.nanoTime();+ if (sleepNS > 0) {try {- // True if we have someone waiting for reopened searcher:- boolean hasWaiting = waitingGen > searchingGen;- final long nextReopenStartNS =- lastReopenStartNS + (hasWaiting ? targetMinStaleNS : targetMaxStaleNS);-- final long sleepNS = nextReopenStartNS - System.nanoTime();-- if (sleepNS > 0) {- reopenCond.awaitNanos(sleepNS);- } else {- break;- }- } catch (InterruptedException _) {- Thread.currentThread().interrupt();- return;- } finally {- reopenLock.unlock();+ reloadRequests.tryAcquire(sleepNS, NANOSECONDS);+ reloadRequests.drainPermits();+ } catch (InterruptedException e) {+ throw new ThreadInterruptedException(e);+ }+ } else {+ lastReopenStartNS = System.nanoTime();+ try {+ manager.maybeRefreshBlocking();+ } catch (IOException ioe) {+ throw new RuntimeException(ioe);}- }-- if (finish) {- break;- }-- lastReopenStartNS = System.nanoTime();- try {- manager.maybeRefreshBlocking();- } catch (IOException ioe) {- throw new RuntimeException(ioe);}}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java b/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.javaindex 2c40a4e7486..454f752beae 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java@@ -17,6 +17,7 @@package org.apache.lucene.search;import java.io.IOException;+import java.time.Duration;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;@@ -230,8 +231,9 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearc@Overrideprotected void doAfterWriter(final ExecutorService es) throws Exception {- final double minReopenSec = 0.01 + 0.05 * random().nextDouble();- final double maxReopenSec = minReopenSec * (1.0 + 10 * random().nextDouble());+ final Duration minReopenSec = Duration.ofMillis((long) (1 + 5 * random().nextDouble()));+ final Duration maxReopenSec =+ Duration.ofMillis((long) (minReopenSec.toMillis() * (100 + 10 * random().nextDouble())));if (VERBOSE) {System.out.println(@@ -378,7 +380,8 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearcmanager.release(searcher);}final ControlledRealTimeReopenThread<IndexSearcher> thread =- new ControlledRealTimeReopenThread<>(writer, manager, 0.01, 0.01);+ new ControlledRealTimeReopenThread<>(+ writer, manager, Duration.ofMillis(1), Duration.ofMillis(1));thread.start(); // start reopeningif (VERBOSE) {System.out.println("waiting now for generation " + lastGen);@@ -501,7 +504,7 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearc// test behaving badly// should be high enough- int maxStaleSecs = 20;+ Duration maxStale = Duration.ofSeconds(20);// build crap data just to store it.String s = " abcdefghijklmnopqrstuvwxyz ";@@ -522,7 +525,7 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearcfinal IndexWriter iw = new IndexWriter(dir, config);SearcherManager sm = new SearcherManager(iw, new SearcherFactory());ControlledRealTimeReopenThread<IndexSearcher> controlledRealTimeReopenThread =- new ControlledRealTimeReopenThread<>(iw, sm, maxStaleSecs, 0);+ new ControlledRealTimeReopenThread<>(iw, sm, maxStale, Duration.ofSeconds(0));controlledRealTimeReopenThread.setDaemon(true);controlledRealTimeReopenThread.start();@@ -559,7 +562,7 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearclong l = iw.addDocument(d);controlledRealTimeReopenThread.waitForGeneration(l);long wait = System.nanoTime() - start;- assertTrue("waited too long for generation " + wait, wait < (maxStaleSecs * 1_000_000_000L));+ assertTrue("waited too long for generation " + wait, wait < (maxStale.toNanos()));IndexSearcher searcher = sm.acquire();TopDocs td = searcher.search(new TermQuery(new Term("count", i + "")), 10);sm.release(searcher);@@ -580,7 +583,8 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearcDirectory dir = newDirectory();IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());SearcherManager mgr = new SearcherManager(w, new SearcherFactory());- nrtDeletesThread = new ControlledRealTimeReopenThread<>(w, mgr, 0.1, 0.01);+ nrtDeletesThread =+ new ControlledRealTimeReopenThread<>(w, mgr, Duration.ofMillis(10), Duration.ofMillis(1));nrtDeletesThread.setName("NRTDeletes Reopen Thread");nrtDeletesThread.setDaemon(true);nrtDeletesThread.start();