Jackie-Jiang commented on code in PR #19894:
URL: https://github.com/apache/pinot/pull/19894#discussion_r4622048798


##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/text/lucene/parsers/BoundedRegexpQueryParser.java:
##########
@@ -0,0 +1,157 @@
+/**
+ * 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.pinot.segment.local.segment.index.text.lucene.parsers;
+
+import java.util.List;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.queryparser.classic.ParseException;
+import org.apache.lucene.queryparser.classic.QueryParser;
+import org.apache.lucene.queryparser.classic.Token;
+import org.apache.lucene.queryparser.complexPhrase.ComplexPhraseQueryParser;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
+import org.apache.pinot.segment.local.utils.LuceneRegexpAutomaton;
+
+
+/// Classic Lucene query parser with a limit on regular expression 
construction.
+/// Like Lucene's parser, each instance should be used by one thread.
+public final class BoundedRegexpQueryParser extends QueryParser {
+  private final MultiTermClauses _multiTermClauses = new MultiTermClauses();
+
+  public BoundedRegexpQueryParser(String field, Analyzer analyzer) {
+    super(field, analyzer);
+  }
+
+  @Override
+  protected Query newRegexpQuery(Term term) {
+    LuceneRegexpAutomaton.validateConstructionBudget(term.text());
+    return super.newRegexpQuery(term);
+  }
+
+  @Override
+  protected Query getFieldQuery(String field, String text, boolean quoted)
+      throws ParseException {
+    Query query = super.getFieldQuery(field, text, quoted);
+    _multiTermClauses.track(this, text, quoted, query);
+    return query;
+  }
+
+  @Override
+  protected void addClause(List<BooleanClause> clauses, int conjunction, int 
modifier, Query query) {
+    if (!_multiTermClauses.add(clauses, conjunction, modifier, query)) {
+      super.addClause(clauses, conjunction, modifier, query);
+    }
+  }
+
+  /// Complex phrase parser with the same construction limit as the classic 
parser.
+  /// Each instance should be used by one thread.
+  public static final class ComplexPhrase extends ComplexPhraseQueryParser {
+    private final MultiTermClauses _multiTermClauses = new MultiTermClauses();
+    private int _parseDepth;
+
+    public ComplexPhrase(String field, Analyzer analyzer) {
+      super(field, analyzer);
+    }
+
+    @Override
+    public Query parse(String expression)
+        throws ParseException {
+      _parseDepth++;
+      try {
+        return super.parse(expression);
+      } finally {
+        _parseDepth--;
+      }
+    }
+
+    @Override
+    protected Query getFieldQuery(String field, String text, boolean quoted)
+        throws ParseException {
+      Query query = super.getFieldQuery(field, text, quoted);
+      // Lucene re-enters parse() for the contents of each quoted phrase. Only 
those clauses are rewritten as spans.
+      if (_parseDepth > 1) {
+        _multiTermClauses.track(this, text, quoted, query);
+      }
+      return query;
+    }
+
+    @Override
+    protected void addClause(List<BooleanClause> clauses, int conjunction, int 
modifier, Query query) {
+      if (!_multiTermClauses.add(clauses, conjunction, modifier, query)) {
+        super.addClause(clauses, conjunction, modifier, query);
+      }
+    }
+
+    @Override
+    protected Query newRegexpQuery(Term term) {
+      LuceneRegexpAutomaton.validateConstructionBudget(term.text());
+      return super.newRegexpQuery(term);
+    }
+  }
+
+  /// Restores Lucene 9's flattening of adjacent plain terms without splitting 
analyzer input.
+  private static final class MultiTermClauses {
+    private static final int NO_CONJUNCTION = 0;
+    private static final int NO_MODIFIER = 0;
+
+    private BooleanQuery _group;
+
+    private void track(QueryParser parser, String text, boolean quoted, Query 
query) {
+      _group = null;
+      if (quoted || parser.getSplitOnWhitespace() || !(query instanceof 
BooleanQuery group)) {
+        return;
+      }
+      // MultiTerm analyzes a string longer than the last token it consumed. 
Compare decoded lengths so
+      // escaped whitespace inside an individual term does not turn into 
separate clauses.
+      Token token = parser.getToken(0);
+      if (token.kind == TERM && text.length() > decodedLength(token.image)
+          && group.clauses().stream().allMatch(clause -> clause.query() 
instanceof TermQuery)) {

Review Comment:
   [P1] Preserve clause flattening when analysis produces synonyms
   
   The all-`TermQuery` restriction restores only part of Lucene 9's behavior. 
With an analyzer emitting `foo`/`qux` at the same position, query `foo bar 
baz*` using `parser=MATCH,minimumShouldMatch=2` previously produced three outer 
clauses: `Synonym(foo,qux)`, `bar`, and `baz*`. Document `foo bar` matched two 
of them.
   
   This code retains the synonym and `bar` inside a nested group, leaving two 
outer clauses. Recursive minimum-should-match now requires both inner clauses 
and `baz*`, incorrectly excluding that document. The COMPLEX parser also fails 
for `"foo bar baz*"` because the nested `SynonymQuery` reaches an unsupported 
rewrite branch; previously the synonym was a top-level phrase position.
   
   Please restore flattening of the analyzed group's outer clauses for 
non-`TermQuery` children too, retaining each nested alternative as one clause, 
and add same-position synonym coverage for MATCH and COMPLEX. Lucene 9's 
`QueryParserBase.addMultiTermClauses` handles this in its non-TermQuery branch.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/LuceneRegexpAutomaton.java:
##########
@@ -0,0 +1,104 @@
+/**
+ * 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.pinot.segment.local.utils;
+
+import org.apache.lucene.util.automaton.Automaton;
+import org.apache.lucene.util.automaton.Operations;
+import org.apache.lucene.util.automaton.RegExp;
+
+
+/// Bounds Lucene regular expression construction and compiles deterministic 
automata for the FST matchers.
+/// All compilation state is local to the caller.
+public final class LuceneRegexpAutomaton {
+  private static final int MAX_CONSTRUCTION_WORK = 
Operations.DEFAULT_DETERMINIZE_WORK_LIMIT;
+
+  private LuceneRegexpAutomaton() {
+  }
+
+  @SuppressWarnings("deprecation") // Preserve the complement syntax supported 
by existing FST queries.
+  public static Automaton compile(String expression) {
+    RegExp regex = new RegExp(expression, RegExp.ALL | 
RegExp.DEPRECATED_COMPLEMENT);
+    validateConstructionBudget(regex);
+    return Operations.determinize(regex.toAutomaton(), 
Operations.DEFAULT_DETERMINIZE_WORK_LIMIT);
+  }
+
+  /// Checks a pattern using Lucene text query syntax before building its 
automaton.
+  public static void validateConstructionBudget(String expression) {
+    validateConstructionBudget(new RegExp(expression, RegExp.ALL));
+  }
+
+  private static void validateConstructionBudget(RegExp regex) {
+    // Lucene expands counted repetitions before determinizing. Estimate that 
work on the parsed tree first.
+    estimate(regex);
+  }
+
+  private static ConstructionCost estimate(RegExp regex) {
+    return switch (regex.kind) {
+      case REGEXP_REPEAT_MIN, REGEXP_REPEAT_MINMAX -> 
estimateRepetition(regex);
+      case REGEXP_CONCATENATION, REGEXP_UNION, REGEXP_INTERSECTION -> {
+        ConstructionCost left = estimate(regex.exp1);
+        ConstructionCost right = estimate(regex.exp2);
+        long work = regex.kind == RegExp.Kind.REGEXP_INTERSECTION
+            ? left.work() * right.work() : left.work() + right.work();
+        boolean acceptsEmpty = regex.kind == RegExp.Kind.REGEXP_UNION
+            ? left.acceptsEmpty() || right.acceptsEmpty()
+            : left.acceptsEmpty() && right.acceptsEmpty();
+        yield new ConstructionCost(work, acceptsEmpty);
+      }
+      case REGEXP_OPTIONAL, REGEXP_REPEAT -> new 
ConstructionCost(estimate(regex.exp1).work() + 1, true);
+      case REGEXP_COMPLEMENT, REGEXP_DEPRECATED_COMPLEMENT -> {
+        ConstructionCost child = estimate(regex.exp1);
+        yield new ConstructionCost(child.work() + 1, !child.acceptsEmpty());

Review Comment:
   [P2] Bound materialized complement automata before repetition
   
   Complement eagerly determinizes its child, but this estimate charges only 
`child.work() + 1`. Pattern `(~(~((a|b)*a(a|b){10}))){384}` passes with 
estimated cost 9,984, although the repeated child requires at least 2,048 
states. Repetition consequently copies at least 786,432 states plus transitions 
before the final determinization limit applies.
   
   Lucene 9.12 checked the actual child state count before repetition. The 
original billion-repeat case is fixed, but this construction-budget bypass 
remains in FST/IFST queries. Please bound materialized intermediate automata 
before subsequent expansion, or conservatively account for complement's 
determinization growth, and add a regression for repeated complements.
   
   Verified against [Lucene 10.6 RegExp 
construction](https://github.com/apache/lucene/blob/releases/lucene/10.6.0/lucene/core/src/java/org/apache/lucene/util/automaton/RegExp.java#L691-L705)
 and 
[Operations.complement](https://github.com/apache/lucene/blob/releases/lucene/10.6.0/lucene/core/src/java/org/apache/lucene/util/automaton/Operations.java#L359-L365).



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/LuceneHnswRuntimeControlUtils.java:
##########
@@ -111,65 +168,28 @@ private static final class 
RuntimeControlledKnnCollectorManager implements KnnCo
     }
 
     @Override
-    public KnnCollector newCollector(int visitLimit, LeafReaderContext 
context) {
+    public KnnCollector newCollector(int visitLimit, KnnSearchStrategy 
searchStrategy, LeafReaderContext context) {
       int effectiveVisitLimit = _efSearch > 0 ? Math.min(visitLimit, 
_efSearch) : visitLimit;
       if (_useBoundedQueue) {
-        AbstractKnnCollector leafCollector = new TopKnnCollector(_k, 
effectiveVisitLimit);
+        AbstractKnnCollector leafCollector = new TopKnnCollector(_k, 
effectiveVisitLimit, searchStrategy);
         KnnCollector collector = _globalScoreQueue != null
             ? new MultiLeafKnnCollector(_k, _globalScoreQueue, leafCollector)

Review Comment:
   [P2] Honor Lucene's per-leaf candidate count
   
   Lucene 10.6 can require more than `k` candidates per leaf before accepting a 
completed filtered ANN search. With two equally sized leaves and `k=10`, 
`perLeafTopK` is 30, but this collector returns at most 10. The manager 
inherits `isOptimistic() == false`, so sufficiently large filtered searches 
fall back to exact scans even when ANN completed normally and `efSearch` is 
unset.
   
   This is reachable through mutable HNSW indexes with multiple leaves and 
upsert filters. Lucene 9.12 accepted completed ANN based on 
`TotalHits.Relation.EQUAL_TO` without this per-leaf quota check.
   
   Please implement the per-leaf collector protocol while preserving runtime 
controls, and verify that completed ANN avoids exact fallback. See [Lucene 10.6 
result 
acceptance](https://github.com/apache/lucene/blob/releases/lucene/10.6.0/lucene/core/src/java/org/apache/lucene/search/AbstractKnnVectorQuery.java#L268-L297)
 and the [built-in optimistic collector 
manager](https://github.com/apache/lucene/blob/releases/lucene/10.6.0/lucene/core/src/java/org/apache/lucene/search/knn/TopKnnCollectorManager.java#L43-L58).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to