Apache Lucene open-source search software
DiversifyingChildren speedup (#15902)
Alessandro Benedetti920e82481167
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 90db96c0d55..7f0922f5b03 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -304,6 +304,8 @@ Optimizations* GITHUB#15886: Cache frozen FieldType to skip redundant schema validation. (Tim Brooks)+* GITHUB#15902: Improve DiversifyingChildren performance by using primitive arrays(Alessandro Benedetti)+Bug Fixes---------------------* GITHUB#15754: Fix HTMLStripCharFilter to prevent tags from incorrectly consuming subsequentdiff --git a/lucene/join/src/java/org/apache/lucene/search/join/DiversifyingNearestChildrenKnnCollector.java b/lucene/join/src/java/org/apache/lucene/search/join/DiversifyingNearestChildrenKnnCollector.javaindex 53b7cfae92c..59cb58d2288 100644--- a/lucene/join/src/java/org/apache/lucene/search/join/DiversifyingNearestChildrenKnnCollector.java+++ b/lucene/join/src/java/org/apache/lucene/search/join/DiversifyingNearestChildrenKnnCollector.java@@ -124,7 +124,11 @@ class DiversifyingNearestChildrenKnnCollector extends AbstractKnnCollector {*/private static class NodeIdCachingHeap {private final int maxSize;- private ParentChildScore[] heapNodes;++ // Parallel primitive arrays; index 0 is unused (heap is 1-based).+ private int[] childNodes;+ private int[] parentNodes;+ private float[] scores;private int size = 0;// Used to keep track of nodeId -> positionInHeap. This way when new scores are added for a@@ -143,33 +147,43 @@ class DiversifyingNearestChildrenKnnCollector extends AbstractKnnCollector {// NOTE: we add +1 because all access to heap is 1-based not 0-based. heap[0] is unused.heapSize = maxSize + 1;this.maxSize = maxSize;+ this.childNodes = new int[heapSize];+ this.parentNodes = new int[heapSize];+ this.scores = new float[heapSize];this.nodeIdHeapIndex = new IntIntHashMap(maxSize);- this.heapNodes = new ParentChildScore[heapSize];}public final int topNode() {- return heapNodes[1].child;+ return childNodes[1];}public final float topScore() {- return heapNodes[1].score;+ return scores[1];+ }++ private void growArrays() {+ childNodes = ArrayUtil.grow(childNodes);+ parentNodes = ArrayUtil.grow(parentNodes);+ scores = ArrayUtil.grow(scores);}private void pushIn(int nodeId, int parentId, float score) {size++;- if (size == heapNodes.length) {- heapNodes = ArrayUtil.grow(heapNodes, (size * 3 + 1) / 2);+ if (size == childNodes.length) {+ growArrays();}- heapNodes[size] = new ParentChildScore(nodeId, parentId, score);+ childNodes[size] = nodeId;+ parentNodes[size] = parentId;+ scores[size] = score;upHeap(size);}private void updateElement(int heapIndex, int nodeId, int parentId, float score) {- ParentChildScore oldValue = heapNodes[heapIndex];- assert oldValue.parent == parentId- : "attempted to update heap element value but with a different node id";- float oldScore = heapNodes[heapIndex].score;- heapNodes[heapIndex] = new ParentChildScore(nodeId, parentId, score);+ assert parentNodes[heapIndex] == parentId+ : "attempted to update heap element value but with a different parent id";+ float oldScore = scores[heapIndex];+ childNodes[heapIndex] = nodeId;+ scores[heapIndex] = score;// Since we are a min heap, if the new value is less, we need to make sure to bubble it upif (score < oldScore) {upHeap(heapIndex);@@ -191,20 +205,22 @@ class DiversifyingNearestChildrenKnnCollector extends AbstractKnnCollector {if (closed) {throw new IllegalStateException();}- int index = nodeIdHeapIndex.indexOf(parentNode);- if (index >= 0) {- int previousNodeIndex = nodeIdHeapIndex.indexGet(index);- if (heapNodes[previousNodeIndex].score < score) {- updateElement(previousNodeIndex, node, parentNode, score);+ // Fast reject: heap is full and the new score cannot beat the current minimum.+ // All stored scores are >= scores[1] (min-heap property), so no existing-parent+ // update is possible either. Skip the hash map lookup entirely.+ if (size >= maxSize && (score < scores[1] || (score == scores[1] && node > childNodes[1]))) {+ return false;+ }+ int cursor = nodeIdHeapIndex.indexOf(parentNode);+ if (cursor >= 0) {+ int existingIndex = nodeIdHeapIndex.indexGet(cursor);+ if (scores[existingIndex] < score) {+ updateElement(existingIndex, node, parentNode, score);return true;}return false;}if (size >= maxSize) {- if (score < heapNodes[1].score- || (score == heapNodes[1].score && node > heapNodes[1].child)) {- return false;- }updateTop(node, parentNode, score);return true;}@@ -215,17 +231,21 @@ class DiversifyingNearestChildrenKnnCollector extends AbstractKnnCollector {private void popToDrain() {closed = true;if (size > 0) {- heapNodes[1] = heapNodes[size]; // move last to first+ childNodes[1] = childNodes[size]; // move last to first+ parentNodes[1] = parentNodes[size];+ scores[1] = scores[size];size--;- downHeapWithoutCacheUpdate(1); // adjust heap+ downHeapWithoutIndexUpdate(1); // adjust heap} else {throw new IllegalStateException("The heap is empty");}}private void updateTop(int nodeId, int parentId, float score) {- nodeIdHeapIndex.remove(heapNodes[1].parent);- heapNodes[1] = new ParentChildScore(nodeId, parentId, score);+ nodeIdHeapIndex.remove(parentNodes[1]);+ childNodes[1] = nodeId;+ parentNodes[1] = parentId;+ scores[1] = score;downHeap(1);}@@ -234,75 +254,89 @@ class DiversifyingNearestChildrenKnnCollector extends AbstractKnnCollector {return size;}+ /**+ * Returns true if the element at heap position {@code k} should be evicted before the element+ * at position {@code j} (i.e. a is "less than" b in the min-heap ordering). Lower score loses+ * first; ties are broken by higher child id losing first.+ */+ private boolean isLessThan(float scoreK, int childIdK, float scoreJ, int childIdJ) {+ if (scoreK != scoreJ) return scoreK < scoreJ;+ return childIdK > childIdJ;+ }+private void upHeap(int origPos) {int i = origPos;- ParentChildScore bottomNode = heapNodes[i];+ int savedChild = childNodes[i];+ int savedParent = parentNodes[i];+ float savedScore = scores[i];int j = i >>> 1;- while (j > 0 && bottomNode.compareTo(heapNodes[j]) < 0) {- heapNodes[i] = heapNodes[j];- nodeIdHeapIndex.put(heapNodes[i].parent, i);+ while (j > 0 && isLessThan(savedScore, savedChild, scores[j], childNodes[j])) {+ childNodes[i] = childNodes[j];+ parentNodes[i] = parentNodes[j];+ scores[i] = scores[j];+ nodeIdHeapIndex.put(parentNodes[i], i);i = j;j = j >>> 1;}- nodeIdHeapIndex.put(bottomNode.parent, i);- heapNodes[i] = bottomNode;+ nodeIdHeapIndex.put(savedParent, i);+ childNodes[i] = savedChild;+ parentNodes[i] = savedParent;+ scores[i] = savedScore;}private int downHeap(int i) {- ParentChildScore node = heapNodes[i];- int j = i << 1; // find smaller child+ int savedChild = childNodes[i];+ int savedParent = parentNodes[i];+ float savedScore = scores[i];+ int j = i << 1; // left childint k = j + 1;- if (k <= size && heapNodes[k].compareTo(heapNodes[j]) < 0) {+ if (k <= size && isLessThan(scores[k], childNodes[k], scores[j], childNodes[j])) {j = k;}- while (j <= size && heapNodes[j].compareTo(node) < 0) {- heapNodes[i] = heapNodes[j];- nodeIdHeapIndex.put(heapNodes[i].parent, i);+ while (j <= size && isLessThan(scores[j], childNodes[j], savedScore, savedChild)) {+ childNodes[i] = childNodes[j];+ parentNodes[i] = parentNodes[j];+ scores[i] = scores[j];+ nodeIdHeapIndex.put(parentNodes[i], i);i = j;j = i << 1;k = j + 1;- if (k <= size && heapNodes[k].compareTo(heapNodes[j]) < 0) {+ if (k <= size && isLessThan(scores[k], childNodes[k], scores[j], childNodes[j])) {j = k;}}- nodeIdHeapIndex.put(node.parent, i);- heapNodes[i] = node; // install saved value+ nodeIdHeapIndex.put(savedParent, i);+ childNodes[i] = savedChild;+ parentNodes[i] = savedParent;+ scores[i] = savedScore;return i;}- private int downHeapWithoutCacheUpdate(int i) {- ParentChildScore node = heapNodes[i];- int j = i << 1; // find smaller child+ // Used only during popToDrain: the index map is never read again after closed=true,+ // so we skip the map updates for speed.+ private void downHeapWithoutIndexUpdate(int i) {+ int savedChild = childNodes[i];+ int savedParent = parentNodes[i];+ float savedScore = scores[i];+ int j = i << 1; // left childint k = j + 1;- if (k <= size && heapNodes[k].compareTo(heapNodes[j]) < 0) {+ if (k <= size && isLessThan(scores[k], childNodes[k], scores[j], childNodes[j])) {j = k;}- while (j <= size && heapNodes[j].compareTo(node) < 0) {- heapNodes[i] = heapNodes[j];+ while (j <= size && isLessThan(scores[j], childNodes[j], savedScore, savedChild)) {+ childNodes[i] = childNodes[j];+ parentNodes[i] = parentNodes[j];+ scores[i] = scores[j];i = j;j = i << 1;k = j + 1;- if (k <= size && heapNodes[k].compareTo(heapNodes[j]) < 0) {+ if (k <= size && isLessThan(scores[k], childNodes[k], scores[j], childNodes[j])) {j = k;}}- heapNodes[i] = node; // install saved value- return i;- }- }-- /** Keeps track of child node, parent node, and the stored score. */- private record ParentChildScore(int child, int parent, float score)- implements Comparable<ParentChildScore> {-- @Override- public int compareTo(ParentChildScore o) {- int fc = Float.compare(score, o.score);- if (fc == 0) {- // lower numbers are the tiebreakers, lower ids are preferred.- return Integer.compare(o.child, child);- }- return fc;+ childNodes[i] = savedChild;+ parentNodes[i] = savedParent;+ scores[i] = savedScore;}}}diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestDiversifyingNearestChildrenKnnCollectorPerformance.java b/lucene/join/src/test/org/apache/lucene/search/join/TestDiversifyingNearestChildrenKnnCollectorPerformance.javanew file mode 100644index 00000000000..99a1384144b--- /dev/null+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestDiversifyingNearestChildrenKnnCollectorPerformance.java@@ -0,0 +1,153 @@+/*+ * 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.lucene.search.join;++import java.io.IOException;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.util.BitSet;++/**+ * Tests for {@link DiversifyingNearestChildrenKnnCollector}.+ *+ * <p>Correctness tests verify behaviour of the collector in various scenarios, including edge+ * cases.+ */+public class TestDiversifyingNearestChildrenKnnCollectorPerformance extends LuceneTestCase {++ /** Builds a BitSet whose set bits are the parent doc ids in a contiguous block-join layout. */+ private static BitSet parentBitSet(int numParents, int childrenPerParent) throws IOException {+ int[] parentDocIds = new int[numParents];+ for (int p = 1; p <= numParents; p++) {+ // layout: [child_0 … child_{C-1}, parent_C], repeated+ // e.g. with 3 children per parent: [0,1,2,3, 4,5,6,7, 8,9,10,11, ...] → parent doc ids are+ // 3,7,11,...+ parentDocIds[p - 1] = p * (childrenPerParent + 1) - 1;+ }+ int totalDocs = numParents * (childrenPerParent + 1); // children + 1 parent per block+ return BitSet.of(+ new TestToParentJoinKnnResults.IntArrayDocIdSetIterator(parentDocIds, numParents),+ totalDocs + 1);+ }++ /** Collects all children in order and returns topDocs. */+ private static TopDocs collectAll(int k, BitSet parents, int[] childIds, float[] scores) {+ DiversifyingNearestChildrenKnnCollector collector =+ new DiversifyingNearestChildrenKnnCollector(k, Integer.MAX_VALUE, parents);+ for (int i = 0; i < childIds.length; i++) {+ collector.collect(childIds[i], scores[i]);+ }+ return collector.topDocs();+ }++ private int[] buildChildIds(int numParents, int childrenPerParent) {+ int totalChildren = numParents * childrenPerParent;+ int[] childIds = new int[totalChildren];+ for (int childIndex = 0; childIndex < childrenPerParent; childIndex++) {+ childIds[childIndex] = childIndex;+ }++ for (int childIndex = childrenPerParent; childIndex < totalChildren; childIndex++) {+ int parentCounter = childIndex / childrenPerParent;+ int previousParentDocId = (parentCounter) * (childrenPerParent + 1) - 1;+ int offset = (childIndex + 1) % childrenPerParent;+ if (offset == 0) {+ offset = childrenPerParent;+ }+ childIds[childIndex] = previousParentDocId + offset;+ }+ return childIds;+ }++ private float[] buildChildScores(int numParents, int childrenPerParent) {+ int totalChildren = numParents * childrenPerParent;+ float[] scores = new float[totalChildren];+ for (int childIndex = 0; childIndex < totalChildren; childIndex++) {+ scores[childIndex] = (childIndex + 1) * 0.1f;+ }+ return scores;+ }++ public void testCollect_shouldReturnSameAsBruteForceOrdering() throws IOException {+ int numParents = 200;+ int childrenPerParent = 10;+ BitSet parents = parentBitSet(numParents, childrenPerParent);++ int totalChildren = numParents * childrenPerParent;+ int[] childIds = buildChildIds(numParents, childrenPerParent);+ float[] scores = buildChildScores(numParents, childrenPerParent);++ // Brute-force: best (child, score) per parent, sorted by score desc, take top-k+ int[] bestChild = new int[numParents];+ float[] bestScore = new float[numParents];+ java.util.Arrays.fill(bestScore, Float.NEGATIVE_INFINITY);+ for (int ci = 0; ci < totalChildren; ci++) {+ int p = ci / childrenPerParent;+ if (scores[ci] > bestScore[p]) {+ bestScore[p] = scores[ci];+ bestChild[p] = childIds[ci];+ }+ }++ for (int k : new int[] {10, 50, 100}) {+ TopDocs topDocs = collectAll(k, parents, childIds, scores);+ assertEquals("size k=" + k, Math.min(k, numParents), topDocs.scoreDocs.length);+ int parentIndex = numParents - 1;+ for (int i = 0; i < topDocs.scoreDocs.length; i++) {+ int actualDocId = topDocs.scoreDocs[i].doc;+ float actualScore = topDocs.scoreDocs[i].score;+ assertEquals("wrong result set for k=" + k, bestChild[parentIndex], actualDocId);+ assertEquals("wrong result set for k=" + k, bestScore[parentIndex], actualScore, 0f);+ parentIndex--;+ }+ }+ }++ /**+ * When the heap is full (size == k) and a better candidate arrives for a new parent, the+ * worst-scoring entry must be evicted. Tests the {@code updateTop} / overflow path.+ */+ public void testOverflowEvictsLowestScore() throws IOException {+ // k=3, 6 parents → last 3 parents must evict first 3 if their scores are higher+ int topK = 3;+ int numParents = 6;+ int childrenPerParent = 1;+ BitSet parents = parentBitSet(numParents, childrenPerParent);++ // Scores: first k parents get low scores, next k get high scores+ int[] childIds = buildChildIds(numParents, childrenPerParent);+ float[] scores = new float[numParents];+ for (int p = 0; p < numParents; p++) {+ scores[p] = p < topK ? 0.1f * (p + 1) : 0.9f - 0.1f * (p - topK);+ }++ TopDocs topDocs = collectAll(topK, parents, childIds, scores);+ assertEquals(topK, topDocs.scoreDocs.length);++ // All returned scores must be >= the lowest score of the high-score group+ float minHighScore = Float.MAX_VALUE;+ for (int p = topK; p < numParents; p++) {+ minHighScore = Math.min(minHighScore, scores[p]);+ }+ for (var sd : topDocs.scoreDocs) {+ assertTrue(+ "evicted result has lower score than expected: " + sd.score,+ sd.score >= minHighScore - 1e-6f);+ }+ }+}