Skip to content

Apache Lucene open-source search software

Make BitSetIterator#docIDRunEnd linear (#16849)

Costin Leau12d316cb8546
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index b74458263d3..4ad3b46d420 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -766,6 +766,10 @@ Bug Fixes
e.g. when searching UNSIGNED_BYTE and SEVEN_BIT scalar-quantized fields in one JVM.
(Lantao Jin)
+* GITHUB#16849: Fix quadratic cost of BitSetIterator#docIDRunEnd() over long runs of set bits,
+ e.g. a dense cached filter on a segment with deletions, which made DenseConjunctionBulkScorer
+ rescan the run for every 4096-doc window since 10.5.0 (Costin Leau)
+
Build
---------------------
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/DenseFilterRunEndBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/DenseFilterRunEndBenchmark.java
new file mode 100644
index 00000000000..2df5c3fe231
--- /dev/null
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/DenseFilterRunEndBenchmark.java
@@ -0,0 +1,209 @@
+/*
+ * 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.benchmark.jmh;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.search.BulkScorer;
+import org.apache.lucene.search.ConstantScoreScorerSupplier;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.DocIdStream;
+import org.apache.lucene.search.LeafCollector;
+import org.apache.lucene.search.Scorable;
+import org.apache.lucene.search.ScoreMode;
+import org.apache.lucene.util.BitSetIterator;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.FixedBitSet;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * Scores a dense filter backed by a {@link BitSetIterator}, the shape of a filter cached by {@code
+ * LRUQueryCache} as a {@link FixedBitSet}. A dense constant-score iterator is scored by {@code
+ * DenseConjunctionBulkScorer}, which calls {@link DocIdSetIterator#docIDRunEnd()} once per window.
+ *
+ * <p>Shapes:
+ *
+ * <ul>
+ * <li>{@code liveDocs}: the segment has deletions, so windows stay at 4096 docs and do not jump
+ * to the end of the run via {@code collectRange}.
+ * <li>{@code liveDocsSlice}: same, but only the first 1/16th of the doc ID space is scored, like
+ * a doc-partitioned slice or an early-terminated search.
+ * <li>{@code conjunction}: no deletions, but a second clause (here the collector's competitive
+ * iterator) does not fully match the window, which also keeps windows at 4096 docs.
+ * </ul>
+ *
+ * <p>Filters:
+ *
+ * <ul>
+ * <li>{@code all}: every doc matches, e.g. a time range that covers the whole segment.
+ * <li>{@code prefix}: one run over the first 90% of the docs, e.g. a time range on a segment
+ * sorted by time.
+ * <li>{@code striped}: one non-matching doc every 1000 docs, a control with short runs.
+ * </ul>
+ */
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@Warmup(iterations = 3, time = 2)
+@Measurement(iterations = 5, time = 3)
+@Fork(
+ value = 1,
+ jvmArgsAppend = {"-Xmx2g", "-Xms2g", "-XX:+AlwaysPreTouch"})
+public class DenseFilterRunEndBenchmark {
+
+ private static final String LIVE_DOCS = "liveDocs";
+ private static final String LIVE_DOCS_SLICE = "liveDocsSlice";
+ private static final String CONJUNCTION = "conjunction";
+
+ @Param({"1000000", "10000000", "50000000"})
+ public int maxDoc;
+
+ @Param({"all", "prefix", "striped"})
+ public String filter;
+
+ @Param({LIVE_DOCS, LIVE_DOCS_SLICE, CONJUNCTION})
+ public String shape;
+
+ private FixedBitSet filterBits;
+ private long filterCost;
+ private FixedBitSet liveDocs;
+ private FixedBitSet competitiveBits;
+ private int max;
+ private int expectedCount;
+
+ @Setup(Level.Trial)
+ public void setup() throws IOException {
+ filterBits = new FixedBitSet(maxDoc);
+ switch (filter) {
+ case "all" -> filterBits.set(0, maxDoc);
+ case "prefix" -> filterBits.set(0, maxDoc / 10 * 9);
+ case "striped" -> {
+ filterBits.set(0, maxDoc);
+ for (int i = 999; i < maxDoc; i += 1000) {
+ filterBits.clear(i);
+ }
+ }
+ default -> throw new IllegalArgumentException("Unknown filter: " + filter);
+ }
+ filterCost = filterBits.cardinality();
+
+ switch (shape) {
+ case LIVE_DOCS, LIVE_DOCS_SLICE -> {
+ // ~0.1% deleted docs
+ liveDocs = new FixedBitSet(maxDoc);
+ liveDocs.set(0, maxDoc);
+ for (int i = 517; i < maxDoc; i += 1009) {
+ liveDocs.clear(i);
+ }
+ }
+ case CONJUNCTION -> {
+ // One non-competitive doc every 64 docs: dense, but never a long run.
+ competitiveBits = new FixedBitSet(maxDoc);
+ competitiveBits.set(0, maxDoc);
+ for (int i = 63; i < maxDoc; i += 64) {
+ competitiveBits.clear(i);
+ }
+ }
+ default -> throw new IllegalArgumentException("Unknown shape: " + shape);
+ }
+ max = LIVE_DOCS_SLICE.equals(shape) ? maxDoc / 16 : maxDoc;
+
+ String bulkScorerName = bulkScorer().getClass().getSimpleName();
+ if (bulkScorerName.equals("DenseConjunctionBulkScorer") == false) {
+ throw new AssertionError("Expected DenseConjunctionBulkScorer, got " + bulkScorerName);
+ }
+ expectedCount = expectedCount();
+ int actual = score();
+ if (actual != expectedCount) {
+ throw new AssertionError("count=" + actual + ", expected=" + expectedCount);
+ }
+ }
+
+ private BulkScorer bulkScorer() throws IOException {
+ return ConstantScoreScorerSupplier.fromIterator(
+ new BitSetIterator(filterBits, filterCost), 1f, ScoreMode.COMPLETE_NO_SCORES, maxDoc)
+ .bulkScorer();
+ }
+
+ private int expectedCount() {
+ FixedBitSet expected = new FixedBitSet(maxDoc);
+ expected.set(0, max);
+ expected.and(filterBits);
+ if (liveDocs != null) {
+ expected.and(liveDocs);
+ }
+ if (competitiveBits != null) {
+ expected.and(competitiveBits);
+ }
+ return expected.cardinality();
+ }
+
+ @Benchmark
+ public int score() throws IOException {
+ DocIdSetIterator competitiveIterator =
+ competitiveBits == null ? null : new BitSetIterator(competitiveBits, maxDoc);
+ CountingCollector collector = new CountingCollector(competitiveIterator);
+ Bits acceptDocs = liveDocs;
+ bulkScorer().score(collector, acceptDocs, 0, max);
+ return collector.count;
+ }
+
+ private static class CountingCollector implements LeafCollector {
+ private final DocIdSetIterator competitiveIterator;
+ int count;
+
+ CountingCollector(DocIdSetIterator competitiveIterator) {
+ this.competitiveIterator = competitiveIterator;
+ }
+
+ @Override
+ public void setScorer(Scorable scorer) {}
+
+ @Override
+ public void collect(int doc) {
+ count++;
+ }
+
+ @Override
+ public void collect(DocIdStream stream) throws IOException {
+ for (int streamCount = stream.count(); streamCount != 0; streamCount = stream.count()) {
+ count += streamCount;
+ }
+ }
+
+ @Override
+ public void collectRange(int min, int max) {
+ count += max - min;
+ }
+
+ @Override
+ public DocIdSetIterator competitiveIterator() {
+ return competitiveIterator;
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/util/BitSetIterator.java b/lucene/core/src/java/org/apache/lucene/util/BitSetIterator.java
index 37f85beaec7..609616ecf8d 100644
--- a/lucene/core/src/java/org/apache/lucene/util/BitSetIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/util/BitSetIterator.java
@@ -23,6 +23,10 @@ import org.apache.lucene.search.DocIdSetIterator;
/**
* A {@link DocIdSetIterator} which iterates over set bits in a bit set.
*
+ * <p>The bit set should not be modified while iterating since {@link #docIDRunEnd()} caches the end
+ * of the current run across calls. In case of modifications, call {@link #setDocId(int)} to reset
+ * it.
+ *
* @lucene.internal
*/
public class BitSetIterator extends AbstractDocIdSetIterator {
@@ -51,9 +55,13 @@ public class BitSetIterator extends AbstractDocIdSetIterator {
return getBitSet(iterator, SparseFixedBitSet.class);
}
+ // 16 DenseConjunctionBulkScorer windows, so callers using a prefix of a run don't scan it all
+ static final int MAX_RUN_END_SCAN = 1 << 16;
+
private final BitSet bits;
private final int length;
private final long cost;
+ private int runStart = -1, runEnd = -1;
/** Sole constructor. */
public BitSetIterator(BitSet bits, long cost) {
@@ -73,6 +81,7 @@ public class BitSetIterator extends AbstractDocIdSetIterator {
/** Set the current doc id that this iterator is on. */
public void setDocId(int docId) {
this.doc = docId;
+ runStart = runEnd = -1;
}
@Override
@@ -96,12 +105,18 @@ public class BitSetIterator extends AbstractDocIdSetIterator {
@Override
public int docIDRunEnd() {
assert doc != NO_MORE_DOCS;
- int next = doc + 1;
- if (next >= length) {
- return length;
+ // Called once per window by DenseConjunctionBulkScorer: resume from the known run end and
+ // bound the scan, otherwise a long run is rescanned on every call, which is quadratic.
+ if (doc < runStart || doc >= runEnd) {
+ runStart = doc;
+ runEnd = doc + 1;
+ }
+ int upTo = doc + Math.min(length - doc, MAX_RUN_END_SCAN);
+ if (runEnd < upTo) {
+ int end = bits.nextClearBit(runEnd, upTo);
+ runEnd = end == NO_MORE_DOCS ? upTo : end;
}
- int end = bits.nextClearBit(next);
- return end == NO_MORE_DOCS ? length : end;
+ return runEnd;
}
@Override
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDenseConjunctionBulkScorer.java b/lucene/core/src/test/org/apache/lucene/search/TestDenseConjunctionBulkScorer.java
index e482b8e129c..8436c203f37 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDenseConjunctionBulkScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDenseConjunctionBulkScorer.java
@@ -24,6 +24,7 @@ import java.util.function.IntPredicate;
import org.apache.lucene.tests.search.AssertingBulkScorer;
import org.apache.lucene.tests.search.RandomApproximationQuery.RandomTwoPhaseView;
import org.apache.lucene.tests.util.LuceneTestCase;
+import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.BitSetIterator;
import org.apache.lucene.util.FixedBitSet;
@@ -1394,4 +1395,121 @@ public class TestDenseConjunctionBulkScorer extends LuceneTestCase {
scorer.score(collector, null, 0, DocIdSetIterator.NO_MORE_DOCS);
assertEquals(expected.cardinality(), collector.count);
}
+
+ public void testLongRunWithLiveDocsIsScannedOnce() throws IOException {
+ int maxDoc = 1 << 20;
+ ScanCountingBitSet clause = new ScanCountingBitSet(maxDoc);
+ clause.in.set(0, maxDoc);
+ FixedBitSet acceptDocs = new FixedBitSet(maxDoc);
+ acceptDocs.set(0, maxDoc);
+ acceptDocs.clear(maxDoc / 2);
+ BulkScorer scorer =
+ new DenseConjunctionBulkScorer(
+ Collections.singletonList(new BitSetIterator(clause, maxDoc)),
+ Collections.emptyList(),
+ maxDoc,
+ 0f);
+ CountingLeafCollector collector = new CountingLeafCollector();
+ scorer.score(collector, acceptDocs, 0, DocIdSetIterator.NO_MORE_DOCS);
+ assertEquals(maxDoc - 1, collector.count);
+ // Windows are WINDOW_SIZE docs because of deleted docs, the run must not be rescanned for
+ // every window.
+ assertTrue("scanned " + clause.scannedBits + " bits", clause.scannedBits <= 2L * maxDoc);
+ }
+
+ public void testLongRunWithSparseClauseIsScannedOnce() throws IOException {
+ int maxDoc = 1 << 20;
+ ScanCountingBitSet clause1 = new ScanCountingBitSet(maxDoc);
+ clause1.in.set(0, maxDoc);
+ FixedBitSet clause2 = new FixedBitSet(maxDoc);
+ for (int i = 0; i < maxDoc; i += 2) {
+ clause2.set(i);
+ }
+ BulkScorer scorer =
+ new DenseConjunctionBulkScorer(
+ Arrays.asList(
+ new BitSetIterator(clause1, maxDoc),
+ new BitSetIterator(clause2, clause2.cardinality())),
+ Collections.emptyList(),
+ maxDoc,
+ 0f);
+ CountingLeafCollector collector = new CountingLeafCollector();
+ scorer.score(collector, null, 0, DocIdSetIterator.NO_MORE_DOCS);
+ assertEquals(maxDoc / 2, collector.count);
+ // Windows are WINDOW_SIZE docs because clause2 has no long runs, the run of clause1 must not
+ // be rescanned for every window.
+ assertTrue("scanned " + clause1.scannedBits + " bits", clause1.scannedBits <= 2L * maxDoc);
+ }
+
+ /** A {@link BitSet} that counts how many bits {@link #nextClearBit(int, int)} scans. */
+ private static class ScanCountingBitSet extends BitSet {
+ final FixedBitSet in;
+ long scannedBits;
+
+ ScanCountingBitSet(int length) {
+ in = new FixedBitSet(length);
+ }
+
+ @Override
+ public int nextClearBit(int start, int upperBound) {
+ int res = in.nextClearBit(start, upperBound);
+ scannedBits += (res == DocIdSetIterator.NO_MORE_DOCS ? upperBound : res + 1) - start;
+ return res;
+ }
+
+ @Override
+ public void set(int i) {
+ in.set(i);
+ }
+
+ @Override
+ public boolean getAndSet(int i) {
+ return in.getAndSet(i);
+ }
+
+ @Override
+ public void clear(int i) {
+ in.clear(i);
+ }
+
+ @Override
+ public void clear(int startIndex, int endIndex) {
+ in.clear(startIndex, endIndex);
+ }
+
+ @Override
+ public int cardinality() {
+ return in.cardinality();
+ }
+
+ @Override
+ public int approximateCardinality() {
+ return in.approximateCardinality();
+ }
+
+ @Override
+ public int prevSetBit(int index) {
+ return in.prevSetBit(index);
+ }
+
+ @Override
+ public int nextSetBit(int start, int end) {
+ return in.nextSetBit(start, end);
+ }
+
+ @Override
+ public boolean get(int index) {
+ return in.get(index);
+ }
+
+ @Override
+ public int length() {
+ return in.length();
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return in.ramBytesUsed();
+ }
+ }
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java b/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
index c076f4b00ca..702df9c9e58 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestLRUQueryCache.java
@@ -1244,7 +1244,13 @@ public class TestLRUQueryCache extends LuceneTestCase {
assertEquals(maxDocId - minDocId, cacheAndCount.count());
DocIdSetIterator iterator = cacheAndCount.iterator();
assertEquals(minDocId, iterator.advance(0));
- assertEquals(maxDocId, iterator.docIDRunEnd());
+ // docIDRunEnd may return a prefix of the run
+ int runEnd = iterator.docIDRunEnd();
+ while (runEnd < maxDocId) {
+ assertEquals(runEnd, iterator.advance(runEnd));
+ runEnd = iterator.docIDRunEnd();
+ }
+ assertEquals(maxDocId, runEnd);
assertEquals(DocIdSetIterator.NO_MORE_DOCS, iterator.advance(maxDocId));
queryCache.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestBitSetIterator.java b/lucene/core/src/test/org/apache/lucene/util/TestBitSetIterator.java
index a12477df769..87a23abc59c 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestBitSetIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestBitSetIterator.java
@@ -126,9 +126,67 @@ public class TestBitSetIterator extends LuceneTestCase {
}
}
+ public void testDocIDRunEndScanIsBounded() {
+ final int max = BitSetIterator.MAX_RUN_END_SCAN;
+ final int n = 2 * max + 5;
+ final FixedBitSet fbs = new FixedBitSet(n);
+ fbs.set(0, n);
+ final BitSetIterator it = new BitSetIterator(fbs, n);
+ assertEquals(0, it.nextDoc());
+ assertEquals(max, it.docIDRunEnd());
+ assertEquals(10, it.advance(10));
+ assertEquals(10 + max, it.docIDRunEnd());
+ assertEquals(2 * max, it.advance(2 * max));
+ assertEquals(n, it.docIDRunEnd());
+ }
+
+ public void testDocIDRunEndAfterMovingBackwards() {
+ final FixedBitSet fbs = new FixedBitSet(1_000);
+ fbs.set(0, 100);
+ fbs.set(101, 300);
+ final BitSetIterator it = new BitSetIterator(fbs, fbs.cardinality());
+ assertEquals(150, it.advance(150));
+ assertEquals(300, it.docIDRunEnd());
+ it.setDocId(50);
+ assertEquals(100, it.docIDRunEnd());
+ }
+
+ public void testDocIDRunEndAfterSetDocIdOnModifiedBitSet() {
+ final FixedBitSet fbs = new FixedBitSet(1_000);
+ fbs.set(0, 300);
+ final BitSetIterator it = new BitSetIterator(fbs, fbs.cardinality());
+ assertEquals(50, it.advance(50));
+ assertEquals(300, it.docIDRunEnd());
+ fbs.clear(100);
+ it.setDocId(it.docID());
+ assertEquals(100, it.docIDRunEnd());
+ }
+
+ public void testRandomDocIDRunEndLongRuns() {
+ final Random r = random();
+ final int iters = TEST_NIGHTLY ? 50 : 10;
+ for (int iter = 0; iter < iters; iter++) {
+ final int n = TestUtil.nextInt(r, 1, 4 * BitSetIterator.MAX_RUN_END_SCAN);
+ final BitSet bits = r.nextBoolean() ? new FixedBitSet(n) : new SparseFixedBitSet(n);
+ final int numRuns = TestUtil.nextInt(r, 1, 10);
+ for (int run = 0; run < numRuns; run++) {
+ final int start = r.nextInt(n);
+ final int end = TestUtil.nextInt(r, start, n);
+ for (int d = start; d < end; d++) {
+ bits.set(d);
+ }
+ }
+ final BitSetIterator it = new BitSetIterator(bits, n);
+ for (int d = it.nextDoc(); d != NO_MORE_DOCS; d = it.advance(d + 1 + r.nextInt(5_000))) {
+ assertTrue(bits.get(d));
+ assertEquals(expectedDocIDRunEnd(bits, d), it.docIDRunEnd());
+ }
+ }
+ }
+
private static int expectedDocIDRunEnd(BitSet bits, int doc) {
int end = doc + 1;
- final int len = bits.length();
+ final int len = doc + Math.min(bits.length() - doc, BitSetIterator.MAX_RUN_END_SCAN);
while (end < len && bits.get(end)) {
end++;
}