xiangfu0 commented on code in PR #19894:
URL: https://github.com/apache/pinot/pull/19894#discussion_r4622391525


##########
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:
   Fixed in 
[7d5d9d074a](https://github.com/apache/pinot/pull/19894/commits/7d5d9d074a08306b77c4e60568bcdac74f9b8895).
 Restored Lucene 9’s outer-clause flattening for analyzer-generated groups. A 
same-position synonym stays one clause. The regression checks MATCH 
minimum-should-match and an ordered COMPLEX phrase against a real index.



##########
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:
   Fixed in 
[7d5d9d074a](https://github.com/apache/pinot/pull/19894/commits/7d5d9d074a08306b77c4e60568bcdac74f9b8895).
 Filtered ANN now uses Lucene’s per-leaf quota on both passes when `efSearch` 
is unset. A two-leaf regression with tied scores checks that completed ANN 
avoids exact fallback. It also covers the sparse-filter exact path and verifies 
that an explicit visit limit avoids a redundant seeded pass.



##########
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:
   Fixed in 
[7d5d9d074a](https://github.com/apache/pinot/pull/19894/commits/7d5d9d074a08306b77c4e60568bcdac74f9b8895).
 The budget now validates the complement’s child before materializing it, then 
accounts for its actual state count, transition count, and empty-string 
acceptance before counted repetition. FST and IFST tests cover rejection and 
valid matching.



-- 
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