You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ja...@apache.org on 2024/09/03 10:32:15 UTC

(lucene) 02/03: Less contention on TotalHitCountCollectorManager

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

javanna pushed a commit to branch intra_segment_concurrency
in repository https://gitbox.apache.org/repos/asf/lucene.git

commit d480868d6c7c860b93cb007f1b9d6503364f375a
Author: Luca Cavanna <ja...@apache.org>
AuthorDate: Tue Sep 3 11:15:08 2024 +0200

    Less contention on TotalHitCountCollectorManager
---
 lucene/MIGRATE.md                                  |  6 --
 .../org/apache/lucene/search/IndexSearcher.java    | 63 ++++++---------
 .../search/TotalHitCountCollectorManager.java      | 93 +++++++++++-----------
 .../lucene/search/TestTotalHitCountCollector.java  |  2 +-
 4 files changed, 69 insertions(+), 95 deletions(-)

diff --git a/lucene/MIGRATE.md b/lucene/MIGRATE.md
index 9c1bce27beb..d7d9b34f91b 100644
--- a/lucene/MIGRATE.md
+++ b/lucene/MIGRATE.md
@@ -826,9 +826,3 @@ With the introduction of intra-segment query concurrency support, the `IndexSear
 method accepts now two additional int arguments to identify the min and max doc id of the range that the leaf partition 
 being searched targets: `IndexSearcher#searchLeaf(LeafReaderContext, int, int, Weight, Collector)`.
 Subclasses of `IndexSearcher` that override the `searchLeaf` method need to be updated accordingly.
-
-### TotalHitCountCollectorManager creation
-
-`TotalHitCountCollectorManager` requires now a `boolean` flag upon creation, to indicate whether leaf partitions 
-are being searched or not. This is to remove needless overhead for the default case where slices don't target 
-segment partitions, which is a scenario that requires additional synchronization at the `Collector` level
diff --git a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
index 95c451eac52..54d187465fe 100644
--- a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
+++ b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java
@@ -121,7 +121,7 @@ public class IndexSearcher {
    * method from constructor, which is a bad practice. Always non-null, regardless of whether an
    * executor is provided or not.
    */
-  private final CachingLeafSlicesSupplier leafSlicesSupplier;
+  private final Supplier<LeafSlice[]> leafSlicesSupplier;
 
   // Used internally for load balancing threads executing for the query
   private final TaskExecutor taskExecutor;
@@ -524,9 +524,7 @@ public class IndexSearcher {
         return countTerm1 + countTerm2 - count(queries[2]);
       }
     }
-    return search(
-        new ConstantScoreQuery(query),
-        new TotalHitCountCollectorManager(leafSlicesSupplier.hasSegmentPartitions()));
+    return search(new ConstantScoreQuery(query), new TotalHitCountCollectorManager());
   }
 
   /**
@@ -1262,7 +1260,6 @@ public class IndexSearcher {
    */
   private static class CachingLeafSlicesSupplier implements Supplier<LeafSlice[]> {
     private volatile LeafSlice[] leafSlices;
-    private volatile boolean hasSegmentPartitions;
 
     private final Function<List<LeafReaderContext>, LeafSlice[]> sliceProvider;
 
@@ -1274,49 +1271,35 @@ public class IndexSearcher {
       this.leaves = Objects.requireNonNull(leaves, "list of LeafReaderContext cannot be null");
     }
 
-    private boolean hasSegmentPartitions() {
-      computeSlices();
-      return hasSegmentPartitions;
-    }
-
     @Override
     public LeafSlice[] get() {
       if (leafSlices == null) {
-        computeSlices();
-      }
-      return leafSlices;
-    }
-
-    private void computeSlices() {
-      synchronized (this) {
-        if (leafSlices == null) {
-          leafSlices =
-              Objects.requireNonNull(
-                  sliceProvider.apply(leaves), "slices computed by the provider is null");
-          /*
-           * Enforce that there aren't multiple leaf partitions within the same leaf slice pointing to the
-           * same leaf context. It is a requirement that {@link Collector#getLeafCollector(LeafReaderContext)}
-           * gets called once per leaf context. Also, it does not make sense to partition a segment to then search
-           * those partitions as part of the same slice, because the goal of partitioning is parallel searching
-           * which happens at the slice level.
-           */
-          boolean hasPartitions = false;
-          for (LeafSlice leafSlice : leafSlices) {
-            Set<LeafReaderContext> distinctLeaves = new HashSet<>();
-            for (LeafReaderContextPartition leafPartition : leafSlice.partitions) {
-              if (leafPartition.minDocId > 0) {
-                hasPartitions = true;
+        synchronized (this) {
+          if (leafSlices == null) {
+            leafSlices =
+                Objects.requireNonNull(
+                    sliceProvider.apply(leaves), "slices computed by the provider is null");
+            /*
+             * Enforce that there aren't multiple leaf partitions within the same leaf slice pointing to the
+             * same leaf context. It is a requirement that {@link Collector#getLeafCollector(LeafReaderContext)}
+             * gets called once per leaf context. Also, it does not make sense to partition a segment to then search
+             * those partitions as part of the same slice, because the goal of partitioning is parallel searching
+             * which happens at the slice level.
+             */
+            for (LeafSlice leafSlice : leafSlices) {
+              Set<LeafReaderContext> distinctLeaves = new HashSet<>();
+              for (LeafReaderContextPartition leafPartition : leafSlice.partitions) {
+                distinctLeaves.add(leafPartition.ctx);
+              }
+              if (leafSlice.partitions.length != distinctLeaves.size()) {
+                throw new IllegalStateException(
+                    "The same slice targets multiple leaf partitions of the same leaf reader context. A physical segment should rather get partitioned to be searched concurrently from as many slices as the number of leaf partitions it is split into.");
               }
-              distinctLeaves.add(leafPartition.ctx);
-            }
-            if (leafSlice.partitions.length != distinctLeaves.size()) {
-              throw new IllegalStateException(
-                  "The same slice targets multiple leaf partitions of the same leaf reader context. A physical segment should rather get partitioned to be searched concurrently from as many slices as the number of leaf partitions it is split into.");
             }
           }
-          this.hasSegmentPartitions = hasPartitions;
         }
       }
+      return leafSlices;
     }
   }
 }
diff --git a/lucene/core/src/java/org/apache/lucene/search/TotalHitCountCollectorManager.java b/lucene/core/src/java/org/apache/lucene/search/TotalHitCountCollectorManager.java
index 54f791eec0c..50956725cb1 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TotalHitCountCollectorManager.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TotalHitCountCollectorManager.java
@@ -18,9 +18,13 @@ package org.apache.lucene.search;
 
 import java.io.IOException;
 import java.util.Collection;
-import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
 import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.util.ThreadInterruptedException;
 
 /**
  * Collector manager based on {@link TotalHitCountCollector} that allows users to parallelize
@@ -32,48 +36,30 @@ import org.apache.lucene.index.LeafReaderContext;
 public class TotalHitCountCollectorManager
     implements CollectorManager<TotalHitCountCollector, Integer> {
 
-  private final boolean leafPartitions;
-
   /**
-   * Internal state shared across the different collectors that this collector manager creates. It
-   * tracks leaves seen as an argument of {@link Collector#getLeafCollector(LeafReaderContext)}
-   * calls, to ensure correctness: if the first partition of a segment early terminates, count has
-   * been already retrieved for the entire segment hence subsequent partitions of the same segment
-   * should also early terminate. If the first partition of a segment computes hit counts,
+   * Internal state shared across the different collectors that this collector manager creates. This
+   * is necessary to support intra-segment concurrency. We track leaves seen as an argument of
+   * {@link Collector#getLeafCollector(LeafReaderContext)} calls, to ensure correctness: if the
+   * first partition of a segment early terminates, count has been already retrieved for the entire
+   * segment hence subsequent partitions of the same segment should also early terminate without
+   * further incrementing hit count. If the first partition of a segment computes hit counts,
    * subsequent partitions of the same segment should do the same, to prevent their counts from
    * being retrieved from {@link LRUQueryCache} (which returns counts for the entire segment while
-   * we need only that of the current leaf partition).
+   * we'd need only that of the current leaf partition).
    */
-  private final Map<LeafReaderContext, Boolean> seenContexts = new HashMap<>();
-
-  public TotalHitCountCollectorManager(boolean leafPartitions) {
-    this.leafPartitions = leafPartitions;
-  }
+  private final Map<Object, Future<Boolean>> earlyTerminatedMap = new ConcurrentHashMap<>();
 
   @Override
   public TotalHitCountCollector newCollector() throws IOException {
-    if (leafPartitions) {
-      return new LeafPartitionAwareTotalHitCountCollector(seenContexts);
-    }
-    return new TotalHitCountCollector();
+    return new LeafPartitionAwareTotalHitCountCollector(earlyTerminatedMap);
   }
 
   @Override
   public Integer reduce(Collection<TotalHitCountCollector> collectors) throws IOException {
-    // TODO this makes the collector manager instance reusable across multiple searches. It isn't a
-    // strict requirement
-    // but it is currently supported as collector managers normally don't hold state, while
-    // collectors do.
-    // This currently works but would not allow to perform incremental reductions in the future. It
-    // would be easy enough
-    // to expose an additional method to the CollectorManager interface to explicitly clear state,
-    // which index searcher
-    // calls before starting a new search. That feels like overkill at the moment because there is
-    // no real usecase for it.
-    // An alternative is to document the requirement to not reuse collector managers across
-    // searches, that would be a
-    // breaking change. Perhaps not needed for now.
-    seenContexts.clear();
+    // Make the same collector manager instance reusable across multiple searches. It isn't a strict
+    // requirement but it is generally supported as collector managers normally don't hold state, as
+    // opposed to collectors.
+    earlyTerminatedMap.clear();
     int totalHits = 0;
     for (TotalHitCountCollector collector : collectors) {
       totalHits += collector.getTotalHits();
@@ -82,36 +68,47 @@ public class TotalHitCountCollectorManager
   }
 
   private static class LeafPartitionAwareTotalHitCountCollector extends TotalHitCountCollector {
-    private final Map<LeafReaderContext, Boolean> seenContexts;
+    private final Map<Object, Future<Boolean>> earlyTerminatedMap;
 
-    LeafPartitionAwareTotalHitCountCollector(Map<LeafReaderContext, Boolean> seenContexts) {
-      this.seenContexts = seenContexts;
+    LeafPartitionAwareTotalHitCountCollector(Map<Object, Future<Boolean>> earlyTerminatedMap) {
+      this.earlyTerminatedMap = earlyTerminatedMap;
     }
 
     @Override
     public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
-      // TODO we could synchronize on context instead, but then the set would need to be made
-      // thread-safe as well, probably overkill?
-      Boolean earlyTerminated;
-      synchronized (seenContexts) {
-        earlyTerminated = seenContexts.get(context);
-        // first time we see this leaf
-        if (earlyTerminated == null) {
+      Future<Boolean> earlyTerminated = earlyTerminatedMap.get(context.id());
+      if (earlyTerminated == null) {
+        CompletableFuture<Boolean> firstEarlyTerminated = new CompletableFuture<>();
+        Future<Boolean> previousEarlyTerminated =
+            earlyTerminatedMap.putIfAbsent(context.id(), firstEarlyTerminated);
+        if (previousEarlyTerminated == null) {
+          // first thread for a given leaf gets to decide what the next threads targeting the same
+          // leaf do
           try {
             LeafCollector leafCollector = super.getLeafCollector(context);
-            seenContexts.put(context, false);
+            firstEarlyTerminated.complete(false);
             return leafCollector;
           } catch (CollectionTerminatedException e) {
-            seenContexts.put(context, true);
+            firstEarlyTerminated.complete(true);
             throw e;
           }
         }
+        earlyTerminated = previousEarlyTerminated;
       }
-      if (earlyTerminated) {
-        // previous partition of the same leaf early terminated
-        throw new CollectionTerminatedException();
+
+      try {
+        if (earlyTerminated.get()) {
+          // first partition of the same leaf early terminated, do the same for subsequent ones
+          throw new CollectionTerminatedException();
+        }
+      } catch (InterruptedException e) {
+        Thread.currentThread().interrupt();
+        throw new ThreadInterruptedException(e);
+      } catch (ExecutionException e) {
+        throw new RuntimeException(e);
       }
-      // previous partition of the same leaf computed hit counts, do the same for subsequent ones
+
+      // first partition of the same leaf computed hit counts, do the same for subsequent ones
       return createLeafCollector();
     }
   }
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTotalHitCountCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestTotalHitCountCollector.java
index 6596136009d..eb2afb58e34 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTotalHitCountCollector.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTotalHitCountCollector.java
@@ -41,7 +41,7 @@ public class TestTotalHitCountCollector extends LuceneTestCase {
     writer.close();
 
     IndexSearcher searcher = newSearcher(reader, true, true, random().nextBoolean());
-    TotalHitCountCollectorManager collectorManager = new TotalHitCountCollectorManager(true);
+    TotalHitCountCollectorManager collectorManager = new TotalHitCountCollectorManager();
     int totalHits = searcher.search(new MatchAllDocsQuery(), collectorManager);
     assertEquals(5, totalHits);