Apache Lucene open-source search software
LUCENE-9350: Don't hold references to large automata on FuzzyQuery (#1467)
Alan Woodwardc6d4aeab3f9c
diff --git a/lucene/core/src/java/org/apache/lucene/search/FuzzyAutomatonBuilder.java b/lucene/core/src/java/org/apache/lucene/search/FuzzyAutomatonBuilder.javanew file mode 100644index 00000000000..42e4b0710a2--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/search/FuzzyAutomatonBuilder.java@@ -0,0 +1,88 @@+/*+ * 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;++import org.apache.lucene.util.UnicodeUtil;+import org.apache.lucene.util.automaton.CompiledAutomaton;+import org.apache.lucene.util.automaton.LevenshteinAutomata;+import org.apache.lucene.util.automaton.TooComplexToDeterminizeException;++/**+ * Builds a set of CompiledAutomaton for fuzzy matching on a given term,+ * with specified maximum edit distance, fixed prefix and whether or not+ * to allow transpositions.+ */+class FuzzyAutomatonBuilder {++ private final String term;+ private final int maxEdits;+ private final LevenshteinAutomata levBuilder;+ private final String prefix;+ private final int termLength;++ FuzzyAutomatonBuilder(String term, int maxEdits, int prefixLength, boolean transpositions) {+ if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) {+ throw new IllegalArgumentException("max edits must be 0.." + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + ", inclusive; got: " + maxEdits);+ }+ if (prefixLength < 0) {+ throw new IllegalArgumentException("prefixLength cannot be less than 0");+ }+ this.term = term;+ this.maxEdits = maxEdits;+ int[] codePoints = stringToUTF32(term);+ this.termLength = codePoints.length;+ prefixLength = Math.min(prefixLength, codePoints.length);+ int[] suffix = new int[codePoints.length - prefixLength];+ System.arraycopy(codePoints, prefixLength, suffix, 0, suffix.length);+ this.levBuilder = new LevenshteinAutomata(suffix, Character.MAX_CODE_POINT, transpositions);+ this.prefix = UnicodeUtil.newString(codePoints, 0, prefixLength);+ }++ CompiledAutomaton[] buildAutomatonSet() {+ CompiledAutomaton[] compiled = new CompiledAutomaton[maxEdits + 1];+ for (int i = 0; i <= maxEdits; i++) {+ try {+ compiled[i] = new CompiledAutomaton(levBuilder.toAutomaton(i, prefix), true, false);+ }+ catch (TooComplexToDeterminizeException e) {+ throw new FuzzyTermsEnum.FuzzyTermsException(term, e);+ }+ }+ return compiled;+ }++ CompiledAutomaton buildMaxEditAutomaton() {+ try {+ return new CompiledAutomaton(levBuilder.toAutomaton(maxEdits, prefix), true, false);+ } catch (TooComplexToDeterminizeException e) {+ throw new FuzzyTermsEnum.FuzzyTermsException(term, e);+ }+ }++ int getTermLength() {+ return this.termLength;+ }++ private static int[] stringToUTF32(String text) {+ int[] termText = new int[text.codePointCount(0, text.length())];+ for (int cp, i = 0, j = 0; i < text.length(); i += Character.charCount(cp)) {+ termText[j++] = cp = text.codePointAt(i);+ }+ return termText;+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java b/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.javaindex c4b4d1b6ada..5dee8b45896 100644--- a/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/FuzzyQuery.java@@ -18,14 +18,13 @@ package org.apache.lucene.search;import java.io.IOException;+import java.util.Objects;import org.apache.lucene.index.SingleTermsEnum;import org.apache.lucene.index.Term;import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;-import org.apache.lucene.util.Accountable;import org.apache.lucene.util.AttributeSource;-import org.apache.lucene.util.RamUsageEstimator;import org.apache.lucene.util.automaton.CompiledAutomaton;import org.apache.lucene.util.automaton.LevenshteinAutomata;@@ -53,9 +52,7 @@ import org.apache.lucene.util.automaton.LevenshteinAutomata;* not match an indexed term "ab", and FuzzyQuery on term "a" with maxEdits=2 will not* match an indexed term "abc".*/-public class FuzzyQuery extends MultiTermQuery implements Accountable {-- private static final long BASE_RAM_BYTES = RamUsageEstimator.shallowSizeOfInstance(AutomatonQuery.class);+public class FuzzyQuery extends MultiTermQuery {public final static int defaultMaxEdits = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;public final static int defaultPrefixLength = 0;@@ -67,10 +64,6 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {private final boolean transpositions;private final int prefixLength;private final Term term;- private final int termLength;- private final CompiledAutomaton[] automata;-- private final long ramBytesUsed;/*** Create a new FuzzyQuery that will match terms with an edit distance@@ -106,22 +99,7 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {this.prefixLength = prefixLength;this.transpositions = transpositions;this.maxExpansions = maxExpansions;- int[] codePoints = FuzzyTermsEnum.stringToUTF32(term.text());- this.termLength = codePoints.length;- this.automata = FuzzyTermsEnum.buildAutomata(term.text(), codePoints, prefixLength, transpositions, maxEdits);setRewriteMethod(new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(maxExpansions));- this.ramBytesUsed = calculateRamBytesUsed(term, this.automata);- }-- private static long calculateRamBytesUsed(Term term, CompiledAutomaton[] automata) {- long bytes = BASE_RAM_BYTES + term.ramBytesUsed();- for (CompiledAutomaton a : automata) {- bytes += a.ramBytesUsed();- }- bytes += 4 * Integer.BYTES;- bytes += Long.BYTES;- bytes += 1;- return bytes;}/**@@ -173,8 +151,9 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {/*** Returns the compiled automata used to match terms*/- public CompiledAutomaton[] getAutomata() {- return automata;+ public CompiledAutomaton getAutomata() {+ FuzzyAutomatonBuilder builder = new FuzzyAutomatonBuilder(term.text(), maxEdits, prefixLength, transpositions);+ return builder.buildMaxEditAutomaton();}@Override@@ -183,7 +162,7 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {if (maxEdits == 0 || prefixLength >= term.text().length()) {visitor.consumeTerms(this, term);} else {- automata[automata.length - 1].visit(visitor, this, field);+ visitor.consumeTermsMatching(this, term.field(), () -> getAutomata().runAutomaton);}}}@@ -193,7 +172,7 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {if (maxEdits == 0 || prefixLength >= term.text().length()) { // can only match if it's exactreturn new SingleTermsEnum(terms.iterator(), term.bytes());}- return new FuzzyTermsEnum(terms, atts, getTerm(), termLength, maxEdits, automata);+ return new FuzzyTermsEnum(terms, atts, getTerm(), maxEdits, prefixLength, transpositions);}/**@@ -237,22 +216,9 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {if (getClass() != obj.getClass())return false;FuzzyQuery other = (FuzzyQuery) obj;- // Note that we don't need to compare termLength or automata because they- // are entirely determined by the other fields- if (maxEdits != other.maxEdits)- return false;- if (prefixLength != other.prefixLength)- return false;- if (maxExpansions != other.maxExpansions)- return false;- if (transpositions != other.transpositions)- return false;- if (term == null) {- if (other.term != null)- return false;- } else if (!term.equals(other.term))- return false;- return true;+ return Objects.equals(maxEdits, other.maxEdits) && Objects.equals(prefixLength, other.prefixLength)+ && Objects.equals(maxExpansions, other.maxExpansions) && Objects.equals(transpositions, other.transpositions)+ && Objects.equals(term, other.term);}/**@@ -274,8 +240,4 @@ public class FuzzyQuery extends MultiTermQuery implements Accountable {}}- @Override- public long ramBytesUsed() {- return ramBytesUsed;- }}diff --git a/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java b/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.javaindex 91a44d5245c..4c49d8accd7 100644--- a/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java+++ b/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java@@ -18,6 +18,7 @@ package org.apache.lucene.search;import java.io.IOException;+import java.util.function.Supplier;import org.apache.lucene.index.ImpactsEnum;import org.apache.lucene.index.PostingsEnum;@@ -25,14 +26,14 @@ import org.apache.lucene.index.Term;import org.apache.lucene.index.TermState;import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.util.Attribute;+import org.apache.lucene.util.AttributeImpl;+import org.apache.lucene.util.AttributeReflector;import org.apache.lucene.util.AttributeSource;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.BytesRefBuilder;import org.apache.lucene.util.UnicodeUtil;-import org.apache.lucene.util.automaton.Automaton;import org.apache.lucene.util.automaton.CompiledAutomaton;-import org.apache.lucene.util.automaton.LevenshteinAutomata;-import org.apache.lucene.util.automaton.TooComplexToDeterminizeException;/** Subclass of TermsEnum for enumerating all terms that are similar* to the specified filter term.@@ -57,21 +58,21 @@ public final class FuzzyTermsEnum extends TermsEnum {private final MaxNonCompetitiveBoostAttribute maxBoostAtt;private final CompiledAutomaton[] automata;+ private final Terms terms;+ private final int termLength;+ private final Term term;private float bottom;private BytesRef bottomTerm;private BytesRef queuedBottom;- private final int termLength;// Maximum number of edits we will accept. This is either 2 or 1 (or, degenerately, 0) passed by the user originally,// but as we collect terms, we can lower this (e.g. from 2 to 1) if we detect that the term queue is full, and all// collected terms are ed=1:private int maxEdits;- private final Terms terms;- private final Term term;/*** Constructor for enumeration of all terms from specified <code>reader</code> which share a prefix of@@ -88,43 +89,44 @@ public final class FuzzyTermsEnum extends TermsEnum {* @throws IOException if there is a low-level IO error*/public FuzzyTermsEnum(Terms terms, Term term, int maxEdits, int prefixLength, boolean transpositions) throws IOException {- this(terms, term, stringToUTF32(term.text()), maxEdits, prefixLength, transpositions);- }-- private FuzzyTermsEnum(Terms terms, Term term, int[] codePoints, int maxEdits, int prefixLength, boolean transpositions) throws IOException {- this(terms, new AttributeSource(), term, codePoints.length, maxEdits,- buildAutomata(term.text(), codePoints, prefixLength, transpositions, maxEdits));+ this(terms, new AttributeSource(), term, () -> new FuzzyAutomatonBuilder(term.text(), maxEdits, prefixLength, transpositions));}/*** Constructor for enumeration of all terms from specified <code>reader</code> which share a prefix of* length <code>prefixLength</code> with <code>term</code> and which have at most {@code maxEdits} edits.* <p>- * After calling the constructor the enumeration is already pointing to the first- * valid term if such a term exists.- *+ * After calling the constructor the enumeration is already pointing to the first+ * valid term if such a term exists.+ ** @param terms Delivers terms.- * @param atts {@link AttributeSource} created by the rewrite method of {@link MultiTermQuery}- * that contains information about competitive boosts during rewrite+ * @param atts An AttributeSource used to share automata between segments* @param term Pattern term.* @param maxEdits Maximum edit distance.- * @param automata An array of levenshtein automata to match against terms,- * see {@link #buildAutomata(String, int[], int, boolean, int)}+ * @param prefixLength the length of the required common prefix+ * @param transpositions whether transpositions should count as a single edit* @throws IOException if there is a low-level IO error*/- public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, int termLength,- final int maxEdits, CompiledAutomaton[] automata) throws IOException {+ FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, int maxEdits, int prefixLength, boolean transpositions) throws IOException {+ this(terms, atts, term, () -> new FuzzyAutomatonBuilder(term.text(), maxEdits, prefixLength, transpositions));+ }++ private FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, Supplier<FuzzyAutomatonBuilder> automatonBuilder) throws IOException {- this.maxEdits = maxEdits;this.terms = terms;- this.term = term;this.atts = atts;- this.termLength = termLength;+ this.term = term;this.maxBoostAtt = atts.addAttribute(MaxNonCompetitiveBoostAttribute.class);this.boostAtt = atts.addAttribute(BoostAttribute.class);- this.automata = automata;+ atts.addAttributeImpl(new AutomatonAttributeImpl());+ AutomatonAttribute aa = atts.addAttribute(AutomatonAttribute.class);+ aa.init(automatonBuilder);++ this.automata = aa.getAutomata();+ this.termLength = aa.getTermLength();+ this.maxEdits = this.automata.length - 1;bottom = maxBoostAtt.getMaxNonCompetitiveBoost();bottomTerm = maxBoostAtt.getCompetitiveTerm();@@ -145,47 +147,6 @@ public final class FuzzyTermsEnum extends TermsEnum {public float getBoost() {return boostAtt.getBoost();}-- static CompiledAutomaton[] buildAutomata(String text, int[] termText, int prefixLength, boolean transpositions, int maxEdits) {- CompiledAutomaton[] compiled = new CompiledAutomaton[maxEdits + 1];- Automaton[] automata = buildAutomata(termText, prefixLength, transpositions, maxEdits);- for (int i = 0; i <= maxEdits; i++) {- try {- compiled[i] = new CompiledAutomaton(automata[i], true, false);- }- catch (TooComplexToDeterminizeException e) {- throw new FuzzyTermsException(text, e);- }- }- return compiled;- }-- static int[] stringToUTF32(String text) {- int[] termText = new int[text.codePointCount(0, text.length())];- for (int cp, i = 0, j = 0; i < text.length(); i += Character.charCount(cp)) {- termText[j++] = cp = text.codePointAt(i);- }- return termText;- }-- private static Automaton[] buildAutomata(int[] termText, int prefixLength, boolean transpositions, int maxEdits) {- if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) {- throw new IllegalArgumentException("max edits must be 0.." + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + ", inclusive; got: " + maxEdits);- }- if (prefixLength < 0) {- throw new IllegalArgumentException("prefixLength cannot be less than 0");- }- Automaton[] automata = new Automaton[maxEdits + 1];- int termLength = termText.length;- prefixLength = Math.min(prefixLength, termLength);- String suffix = UnicodeUtil.newString(termText, prefixLength, termText.length - prefixLength);- LevenshteinAutomata builder = new LevenshteinAutomata(suffix, transpositions);- String prefix = UnicodeUtil.newString(termText, 0, prefixLength);- for (int i = 0; i <= maxEdits; i++) {- automata[i] = builder.toAutomaton(i, prefix);- }- return automata;- }/*** return an automata-based enum for matching up to editDistance from@@ -274,7 +235,7 @@ public final class FuzzyTermsEnum extends TermsEnum {final float bottom = maxBoostAtt.getMaxNonCompetitiveBoost();final BytesRef bottomTerm = maxBoostAtt.getCompetitiveTerm();- if (term != null && (bottom != this.bottom || bottomTerm != this.bottomTerm)) {+ if (bottom != this.bottom || bottomTerm != this.bottomTerm) {this.bottom = bottom;this.bottomTerm = bottomTerm;// clone the term before potentially doing something with it@@ -364,4 +325,60 @@ public final class FuzzyTermsEnum extends TermsEnum {}}+ /**+ * Used for sharing automata between segments+ *+ * Levenshtein automata are large and expensive to build; we don't want to build+ * them directly on the query because this can blow up caches that use queries+ * as keys; we also don't want to rebuild them for every segment. This attribute+ * allows the FuzzyTermsEnum to build the automata once for its first segment+ * and then share them for subsequent segment calls.+ */+ private interface AutomatonAttribute extends Attribute {+ CompiledAutomaton[] getAutomata();+ int getTermLength();+ void init(Supplier<FuzzyAutomatonBuilder> builder);+ }++ private static class AutomatonAttributeImpl extends AttributeImpl implements AutomatonAttribute {++ private CompiledAutomaton[] automata;+ private int termLength;++ @Override+ public CompiledAutomaton[] getAutomata() {+ return automata;+ }++ @Override+ public int getTermLength() {+ return termLength;+ }++ @Override+ public void init(Supplier<FuzzyAutomatonBuilder> supplier) {+ if (automata != null) {+ return;+ }+ FuzzyAutomatonBuilder builder = supplier.get();+ this.termLength = builder.getTermLength();+ this.automata = builder.buildAutomatonSet();+ }++ @Override+ public void clear() {+ this.automata = null;+ }++ @Override+ public void reflectWith(AttributeReflector reflector) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void copyTo(AttributeImpl target) {+ throw new UnsupportedOperationException();+ }+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.javaindex 327227afe15..e3c4ff7097f 100644--- a/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/MultiTermQuery.java@@ -286,9 +286,9 @@ public abstract class MultiTermQuery extends Query {* (should instead return {@link TermsEnum#EMPTY} if no* terms match). The TermsEnum must already be* positioned to the first matching term.- * The given {@link AttributeSource} is passed by the {@link RewriteMethod} to- * provide attributes, the rewrite method uses to inform about e.g. maximum competitive boosts.- * This is currently only used by {@link TopTermsRewrite}+ * The given {@link AttributeSource} is passed by the {@link RewriteMethod} to+ * share information between segments, for example {@link TopTermsRewrite} uses+ * it to share maximum competitive boosts*/protected abstract TermsEnum getTermsEnum(Terms terms, AttributeSource atts) throws IOException;diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.javaindex a95ad39cf59..99376e30305 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java@@ -24,6 +24,8 @@ import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.function.Supplier;import com.carrotsearch.randomizedtesting.RandomizedTest;import org.apache.lucene.analysis.MockAnalyzer;@@ -36,15 +38,15 @@ import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.MultiReader;import org.apache.lucene.index.RandomIndexWriter;import org.apache.lucene.index.Term;-import org.apache.lucene.index.Terms;-import org.apache.lucene.index.TermsEnum;import org.apache.lucene.search.BooleanClause.Occur;import org.apache.lucene.search.similarities.ClassicSimilarity;import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.LuceneTestCase;import org.apache.lucene.util.TestUtil;+import org.apache.lucene.util.automaton.ByteRunAutomaton;import org.apache.lucene.util.automaton.LevenshteinAutomata;import org.apache.lucene.util.automaton.Operations;@@ -515,54 +517,13 @@ public class TestFuzzyQuery extends LuceneTestCase {final String value = randomRealisticMultiByteUnicode(length);FuzzyTermsEnum.FuzzyTermsException expected = expectThrows(FuzzyTermsEnum.FuzzyTermsException.class, () -> {- new FuzzyQuery(new Term("field", value)).getTermsEnum(new Terms() {- @Override- public TermsEnum iterator() {- return TermsEnum.EMPTY;- }-- @Override- public long size() {- return 0;- }-- @Override- public long getSumTotalTermFreq() {- throw new UnsupportedOperationException();- }-- @Override- public long getSumDocFreq() {- throw new UnsupportedOperationException();- }-- @Override- public int getDocCount() {- throw new UnsupportedOperationException();- }-- @Override- public boolean hasFreqs() {- throw new UnsupportedOperationException();- }-- @Override- public boolean hasOffsets() {- throw new UnsupportedOperationException();- }-- @Override- public boolean hasPositions() {- throw new UnsupportedOperationException();- }-- @Override- public boolean hasPayloads() {- throw new UnsupportedOperationException();- }- });+ new FuzzyAutomatonBuilder(value, 2, 0, true).buildMaxEditAutomaton();});assertThat(expected.getMessage(), containsString(value));++ expected = expectThrows(FuzzyTermsEnum.FuzzyTermsException.class,+ () -> new FuzzyAutomatonBuilder(value, 2, 0, true).buildAutomatonSet());+ assertThat(expected.getMessage(), containsString(value));}private void addDoc(String text, RandomIndexWriter writer) throws IOException {@@ -777,4 +738,31 @@ public class TestFuzzyQuery extends LuceneTestCase {}return ref;}++ public void testVisitor() {+ FuzzyQuery q = new FuzzyQuery(new Term("field", "blob"), 2);+ AtomicBoolean visited = new AtomicBoolean(false);+ q.visit(new QueryVisitor() {+ @Override+ public void consumeTermsMatching(Query query, String field, Supplier<ByteRunAutomaton> automaton) {+ visited.set(true);+ ByteRunAutomaton a = automaton.get();+ assertMatches(a, "blob");+ assertMatches(a, "bolb");+ assertMatches(a, "blobby");+ assertNoMatches(a, "bolbby");+ }+ });+ assertTrue(visited.get());+ }++ private static void assertMatches(ByteRunAutomaton automaton, String text) {+ BytesRef b = new BytesRef(text);+ assertTrue(automaton.run(b.bytes, b.offset, b.length));+ }++ private static void assertNoMatches(ByteRunAutomaton automaton, String text) {+ BytesRef b = new BytesRef(text);+ assertFalse(automaton.run(b.bytes, b.offset, b.length));+ }}