You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@jackrabbit.apache.org by "nfsantos (via GitHub)" <gi...@apache.org> on 2023/12/26 11:15:13 UTC

[PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

nfsantos opened a new pull request, #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258

   (no comment)


-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444327454


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {

Review Comment:
   I added the special handling of '/' recently, mainly to simplify the query in this case. But even before adding this special case, the logic handling the download of subpaths was doing the right thing when the includedPaths was '/', but it would do unnecessary queries to download the ancestors of '/' and would use a filters to match '/' on the query for the children, which is unnecessary. 
   But yes, now it is handled and if '/' is one of the includedPath, it will use a simple query without any filters that downloads everything.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos merged PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258


-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444338077


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -101,12 +100,22 @@ public long getDocumentsDownloaded() {
      * filtering in the indexing job. This feature may significantly reduce the number of documents downloaded from
      * Mongo.
      * The performance gains may not be proportional to the reduction in the number of documents downloaded because Mongo
-     * still has to traverse all the documents. This is the case because the regex expression used for path filtering
+     * still has to traverse all the documents. This is required because the regex expression used for path filtering
      * starts with a wildcard (because the _id starts with the depth of the path, so the regex expression must ignore
      * this part). Because of the wildcard at the start, Mongo cannot use of the index on _id.
      */
     public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = "oak.indexer.pipelined.mongoRegexPathFiltering";
     public static final boolean DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = false;
+
+    /**
+     * Maximum number of elements in the included/excluded paths list used for regex path filtering. If after
+     * merging and de-deduplication of the paths of all the path filters the number of included or excluded paths exceeds
+     * this value, then disable path filtering to avoid creating Mongo queries with large number of filters
+     */
+    public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = "oak.indexer.pipelined.mongoRegexPathFilteringMaxPaths";
+    public static final int DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = 20;

Review Comment:
   The maximum size of a query is limited by the maximum size of a bson document, which is 16MB. I did not make a test myself, but I found several posts on StackOverflow that say that it is possible to have hundreds of fields in the arrays passed to `$in` and `$nin`. But we should anyway have a much lower limit in the tens because otherwise the performance would degrade.
   
   I'm wondering if we should have hard limits to the number of included/excluded paths. Or just log a warning if there are more than, let's say, 100. I would go with a warning, because there may be valid reasons to have many included/excluded paths and Mongo might actually handle it correctly, so we do not want to restrict our freedom in the future. But a warning would already be useful, as if something would fail, the warning would point to the potential problem. What do you think?



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442950518


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;
         }
-        return extractIncludedPaths(pathFilters);
+        LOG.info("Computing included/excluded paths for Mongo regex path filtering. PathFilters: {}", pathFilters.stream()
+                .map(pf -> "PF{includedPaths=" + pf.getIncludedPaths() + ", excludedPaths=" + pf.getExcludedPaths() + "}")
+                .collect(Collectors.joining(", ")));
+        MongoFilterPaths mongoFilterPaths = buildMongoFilter(pathFilters);
+        LOG.info("Paths used for regex filtering on Mongo: {}", mongoFilterPaths);
+        return mongoFilterPaths;
     }
 
-    /**
-     * Aggregates the included paths from the path filters. The final list will not contain duplicates or overlapping
-     * paths (i.e., /a and /a/b).
-     *
-     * @param pathFilters Empty set if path filtering should be disabled, otherwise the paths that should be included
-     *                    in the Mongo query filters
-     */
-    // Package private for testing
-    static Set<String> extractIncludedPaths(List<PathFilter> pathFilters) {
-        // Path filtering is enabled only if there are no excludedPaths.
-        if (pathFilters == null) {
-            return Set.of();
+    static MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return null;
         }
-        Set<String> includedPaths = new HashSet<>();
-        Set<String> excludedPaths = new HashSet<>();
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
         for (PathFilter pathFilter : pathFilters) {
-            includedPaths.addAll(pathFilter.getIncludedPaths());
-            excludedPaths.addAll(pathFilter.getExcludedPaths());
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
         }
-        // Sort by natural order, so that parent paths appear before any children. This makes it easier to compute the
-        // common ancestors of included paths
-        List<String> sortedIncludedPaths = includedPaths.stream()
-                .sorted()
-                .collect(Collectors.toList());
-
-        LOG.info("Paths considered for regex filtering. IncludedPaths: {}, excludedPaths: {}", sortedIncludedPaths, excludedPaths);
-        if (sortedIncludedPaths.contains("/")) {
-            LOG.info("Disabling regex path filtering because root path is in the includedPaths: {}", sortedIncludedPaths);
-            return Set.of();
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        ArrayList<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens

Review Comment:
   I added a configuration setting to limit on the number of paths that can be used to build regex path filters. By default, the value is 20. This is limit is applied after merging and de-duplicating the paths in all the path filters, so the algorithm to de-duplicate the paths might still be exposed to the quadratic complexity when using many paths. I tested in my M1 mac, with 10k unique paths it takes two seconds to de-duplicate the list of paths. I think it's ok, it would be very hard to have a index definition with more than 10k paths, probably other parts of the system would break before getting to this point.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442946432


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;

Review Comment:
   Done.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442695195


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;
         }
-        return extractIncludedPaths(pathFilters);
+        LOG.info("Computing included/excluded paths for Mongo regex path filtering. PathFilters: {}", pathFilters.stream()
+                .map(pf -> "PF{includedPaths=" + pf.getIncludedPaths() + ", excludedPaths=" + pf.getExcludedPaths() + "}")
+                .collect(Collectors.joining(", ")));
+        MongoFilterPaths mongoFilterPaths = buildMongoFilter(pathFilters);
+        LOG.info("Paths used for regex filtering on Mongo: {}", mongoFilterPaths);
+        return mongoFilterPaths;
     }
 
-    /**
-     * Aggregates the included paths from the path filters. The final list will not contain duplicates or overlapping
-     * paths (i.e., /a and /a/b).
-     *
-     * @param pathFilters Empty set if path filtering should be disabled, otherwise the paths that should be included
-     *                    in the Mongo query filters
-     */
-    // Package private for testing
-    static Set<String> extractIncludedPaths(List<PathFilter> pathFilters) {
-        // Path filtering is enabled only if there are no excludedPaths.
-        if (pathFilters == null) {
-            return Set.of();
+    static MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return null;
         }
-        Set<String> includedPaths = new HashSet<>();
-        Set<String> excludedPaths = new HashSet<>();
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
         for (PathFilter pathFilter : pathFilters) {
-            includedPaths.addAll(pathFilter.getIncludedPaths());
-            excludedPaths.addAll(pathFilter.getExcludedPaths());
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
         }
-        // Sort by natural order, so that parent paths appear before any children. This makes it easier to compute the
-        // common ancestors of included paths
-        List<String> sortedIncludedPaths = includedPaths.stream()
-                .sorted()
-                .collect(Collectors.toList());
-
-        LOG.info("Paths considered for regex filtering. IncludedPaths: {}, excludedPaths: {}", sortedIncludedPaths, excludedPaths);
-        if (sortedIncludedPaths.contains("/")) {
-            LOG.info("Disabling regex path filtering because root path is in the includedPaths: {}", sortedIncludedPaths);
-            return Set.of();
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        ArrayList<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens

Review Comment:
   Features are often used in surprising ways... What if we don't filter if the list is larger than a 20? With 20 times 100, it would be 10'000, which should still be OK. But above that, it might not.
   
   Also, the MongoDB query might become long even if just one path is too very long (not sure if there is a limit). So maybe we should restrict on the length as well.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444270579


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -101,12 +100,22 @@ public long getDocumentsDownloaded() {
      * filtering in the indexing job. This feature may significantly reduce the number of documents downloaded from
      * Mongo.
      * The performance gains may not be proportional to the reduction in the number of documents downloaded because Mongo
-     * still has to traverse all the documents. This is the case because the regex expression used for path filtering
+     * still has to traverse all the documents. This is required because the regex expression used for path filtering
      * starts with a wildcard (because the _id starts with the depth of the path, so the regex expression must ignore
      * this part). Because of the wildcard at the start, Mongo cannot use of the index on _id.
      */
     public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = "oak.indexer.pipelined.mongoRegexPathFiltering";
     public static final boolean DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = false;
+
+    /**
+     * Maximum number of elements in the included/excluded paths list used for regex path filtering. If after
+     * merging and de-deduplication of the paths of all the path filters the number of included or excluded paths exceeds
+     * this value, then disable path filtering to avoid creating Mongo queries with large number of filters
+     */
+    public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = "oak.indexer.pipelined.mongoRegexPathFilteringMaxPaths";
+    public static final int DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = 20;

Review Comment:
   It would be good to verify what is the maximum number of entries that MongoDB supports... I could imagine it's less than 20 includedPath + 20 excludedPaths...
   
   And I wonder if there is a limit on the length of the paths, not just the number of paths.



##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {

Review Comment:
   I see we have a special handling for "includedPaths includes /" below. So that's good.
   
   Just FYI, right now we only have one customer, ethos14-prod-deu6/ns-team-aem-cm-prd-n117045/cm-p118752-e1205293, with:
   
       "includedPaths": ["/"],
   
   With the change we did for the index definition generator https://oakutils.appspot.com/generate/index - to always add "includedPaths" - we might get more of those in the future.
   
   So yes, it might make sense to support "/". But it's already supported, so that's good.



##########
oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedIT.java:
##########
@@ -418,14 +515,23 @@ private PipelinedStrategy createStrategy(Backend backend, Predicate<String> path
     private void createContent(NodeStore rwNodeStore) throws CommitFailedException {
         @NotNull NodeBuilder rootBuilder = rwNodeStore.getRoot().builder();
         @NotNull NodeBuilder contentDamBuilder = rootBuilder.child("content").child("dam");
-        contentDamBuilder.child("2023").child("01").setProperty("p1", "v202301");
-        contentDamBuilder.child("2022").child("02").setProperty("p1", "v202202");
-        contentDamBuilder.child("2023").child("01").setProperty("p1", "v202301");
         contentDamBuilder.child("1000").child("12").setProperty("p1", "v100012");
+        contentDamBuilder.child("2022").child("01").setProperty("p1", "v202201");
+        contentDamBuilder.child("2022").child("01").child("01").setProperty("p1", "v20220101");
+        contentDamBuilder.child("2022").child("02").setProperty("p1", "v202202");
+        contentDamBuilder.child("2022").child("02").child("01").setProperty("p1", "v20220201");
+        contentDamBuilder.child("2022").child("02").child("02").setProperty("p1", "v20220202");
+        contentDamBuilder.child("2022").child("02").child("03").setProperty("p1", "v20220203");
+        contentDamBuilder.child("2022").child("02").child("04").setProperty("p1", "v20220204");
+        contentDamBuilder.child("2022").child("03").setProperty("p1", "v202203");
+        contentDamBuilder.child("2022").child("04").setProperty("p1", "v202204");
         contentDamBuilder.child("2023").setProperty("p2", "v2023");
+        contentDamBuilder.child("2023").child("01").setProperty("p1", "v202301");
+        contentDamBuilder.child("2023").child("01").setProperty("p1", "v202301");
         contentDamBuilder.child("2023").child("02").child("28").setProperty("p1", "v20230228");
 
         // Node with very long name
+//        @NotNull NodeBuilder node = contentDamBuilder.child("long_path_test");

Review Comment:
   ```suggestion
   ```



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "steffenvan (via GitHub)" <gi...@apache.org>.
steffenvan commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444268200


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return MongoFilterPaths.DOWNLOAD_ALL;
+        }
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
+        for (PathFilter pathFilter : pathFilters) {
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
+        }
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        List<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens
+        // Idea for linear time algorithm: after adding a path to the includedPathsRoots, advance in the list of candidates
+        // skipping all paths that are children of the path just added. Since the list is sorted alphabetically, the children
+        // of a path will be next to it in the list
+        for (String candidateIncludedPath : sortedCandidateIncludedPaths) {
+            if (finalIncludedPathsRoots.stream().noneMatch(ancestor -> PathUtils.isAncestor(ancestor, candidateIncludedPath))) {
+                finalIncludedPathsRoots.add(candidateIncludedPath);
+            }
+        }
+
+        List<String> finalExcludedPaths = new ArrayList<>();
+        // Keep an excluded path only if it is not needed by any filter.
+        for (String candidateExcludedPath : candidateExcludedPaths) {
+            boolean notNeeded = pathFilters.stream().allMatch(pathFilter -> pathFilter.filter(candidateExcludedPath) == PathFilter.Result.EXCLUDE);
+            if (notNeeded) {
+                finalExcludedPaths.add(candidateExcludedPath);
+            }
+        }
+
+        // Do not filter if there are too many includedPaths. The official Mongo documentation recommends
+        // not using more than tens of values in the $in filter to avoid performance degradation.
+        // https://www.mongodb.com/docs/manual/reference/operator/query/in/
+        if (finalIncludedPathsRoots.size() > maxNumberOfPaths) {
+            LOG.info("Number of includedPaths ({}) exceed the maximum allowed ({}), downloading everything",
+                    finalIncludedPathsRoots.size(), maxNumberOfPaths);
+            return MongoFilterPaths.DOWNLOAD_ALL;
+        }
+
+        // Also check the number of excluded paths and disable filtering by them if there are too many.
+        // We do not need to revert to download the full repository in the case where there is a reasonable number of
+        // included paths but too many excluded paths. The excluded paths are always children of the included paths, so
+        // if we do not filter on excludedPaths, we simply download everything inside the included paths. This might be
+        // much less than the full repository.
+        if (finalExcludedPaths.size() > maxNumberOfPaths) {
+            LOG.info("Number of excludedPaths ({}) exceed the maximum allowed ({}), disabling filtering of excludedPaths",
+                    finalExcludedPaths.size(), maxNumberOfPaths);
+            finalExcludedPaths = List.of();
+        }
+
+        if (finalExcludedPaths.isEmpty()) {

Review Comment:
   I know this PR is not supposed to address this, but we do have the recommendation to not have either only `excludedPaths` or `includedPaths`. Not sure if it's helpful, but would logging a warning make sense here? 



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442695195


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;
         }
-        return extractIncludedPaths(pathFilters);
+        LOG.info("Computing included/excluded paths for Mongo regex path filtering. PathFilters: {}", pathFilters.stream()
+                .map(pf -> "PF{includedPaths=" + pf.getIncludedPaths() + ", excludedPaths=" + pf.getExcludedPaths() + "}")
+                .collect(Collectors.joining(", ")));
+        MongoFilterPaths mongoFilterPaths = buildMongoFilter(pathFilters);
+        LOG.info("Paths used for regex filtering on Mongo: {}", mongoFilterPaths);
+        return mongoFilterPaths;
     }
 
-    /**
-     * Aggregates the included paths from the path filters. The final list will not contain duplicates or overlapping
-     * paths (i.e., /a and /a/b).
-     *
-     * @param pathFilters Empty set if path filtering should be disabled, otherwise the paths that should be included
-     *                    in the Mongo query filters
-     */
-    // Package private for testing
-    static Set<String> extractIncludedPaths(List<PathFilter> pathFilters) {
-        // Path filtering is enabled only if there are no excludedPaths.
-        if (pathFilters == null) {
-            return Set.of();
+    static MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return null;
         }
-        Set<String> includedPaths = new HashSet<>();
-        Set<String> excludedPaths = new HashSet<>();
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
         for (PathFilter pathFilter : pathFilters) {
-            includedPaths.addAll(pathFilter.getIncludedPaths());
-            excludedPaths.addAll(pathFilter.getExcludedPaths());
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
         }
-        // Sort by natural order, so that parent paths appear before any children. This makes it easier to compute the
-        // common ancestors of included paths
-        List<String> sortedIncludedPaths = includedPaths.stream()
-                .sorted()
-                .collect(Collectors.toList());
-
-        LOG.info("Paths considered for regex filtering. IncludedPaths: {}, excludedPaths: {}", sortedIncludedPaths, excludedPaths);
-        if (sortedIncludedPaths.contains("/")) {
-            LOG.info("Disabling regex path filtering because root path is in the includedPaths: {}", sortedIncludedPaths);
-            return Set.of();
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        ArrayList<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens

Review Comment:
   Features are often used in surprising ways... What if we don't filter if the list is larger than a 100? With 100 times 100, it would be 10'000, which should still be OK. But above that, it might not.



##########
oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTaskTest.java:
##########
@@ -142,42 +144,101 @@ private List<PathFilter> createIncludedPathFilters(String... paths) {
 
     @Test
     public void ancestorsFilters() {
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.getAncestors(Set.of()));
-        assertEquals(Set.of("/"), PipelinedMongoDownloadTask.getAncestors(Set.of("/")));
-        assertEquals(Set.of("/", "/a"), PipelinedMongoDownloadTask.getAncestors(Set.of("/a")));
-        assertEquals(Set.of("/", "/a", "/b", "/c", "/c/c1", "/c/c1/c2", "/c/c1/c2/c3", "/c/c1/c2/c4"),
-                PipelinedMongoDownloadTask.getAncestors(Set.of("/a", "/b", "/c/c1/c2/c3", "/c/c1/c2/c4"))
+        assertEquals(List.of(), PipelinedMongoDownloadTask.getAncestors(List.of()));
+        assertEquals(List.of("/"), PipelinedMongoDownloadTask.getAncestors(List.of("/")));
+        assertEquals(List.of("/", "/a"), PipelinedMongoDownloadTask.getAncestors(List.of("/a")));
+        assertEquals(List.of("/", "/a", "/b", "/c", "/c/c1", "/c/c1/c2", "/c/c1/c2/c3", "/c/c1/c2/c4"),
+                PipelinedMongoDownloadTask.getAncestors(List.of("/a", "/b", "/c/c1/c2/c3", "/c/c1/c2/c4"))
         );
     }
 
     @Test
-    public void regexFilters() {
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(null));
+    public void regexFilters_includedPaths_only() {
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(null));
 
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(List.of()));
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(List.of()));
 
         List<PathFilter> singlePathFilter = List.of(
                 new PathFilter(List.of("/content/dam"), List.of())
         );
-        assertEquals(Set.of("/content/dam"), PipelinedMongoDownloadTask.extractIncludedPaths(singlePathFilter));
+        assertEquals(new MongoFilterPaths(List.of("/content/dam"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(singlePathFilter));
 
         List<PathFilter> multipleIncludeFilters = createIncludedPathFilters("/content/dam", "/content/dam");
-        assertEquals(Set.of("/content/dam"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFilters));
+        assertEquals(new MongoFilterPaths(List.of("/content/dam"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFilters));
 
-        List<PathFilter> includesRoot = List.of(
-                new PathFilter(List.of("/"), List.of())
-        );
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(includesRoot));
+        List<PathFilter> includesRoot = createIncludedPathFilters("/", "/a/a1/a2");
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(includesRoot));
 
         List<PathFilter> multipleIncludeFiltersDifferent = createIncludedPathFilters("/a/a1", "/a/a1/a2");
-        assertEquals(Set.of("/a/a1"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFiltersDifferent));
+        assertEquals(new MongoFilterPaths(List.of("/a/a1"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFiltersDifferent));
 
         List<PathFilter> multipleIncludeFiltersDifferent2 = createIncludedPathFilters("/a/a1/a2", "/a/a1", "/b", "/c", "/cc");
-        assertEquals(Set.of("/a/a1", "/b", "/c", "/cc"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFiltersDifferent2));
+        assertEquals(new MongoFilterPaths(List.of("/a/a1", "/b", "/c", "/cc"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFiltersDifferent2));
+    }
 
-        List<PathFilter> withExcludeFilter = List.of(
-                new PathFilter(List.of("/"), List.of("/var"))
+    @Test
+    public void regexFilters_included_and_excluded_paths() {

Review Comment:
   This is mixing camel case and snake case... Here we use excluded_paths, in other places it's includedPaths.
   
   I would try to be a bit more consistent. But I understand purely camel case is not nice either, regexFiltersIncludedAndExcludedPaths... but I think still better.



##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;

Review Comment:
   I wonder if we should have a "empty MongoFilterPaths" instance (e.g. MongoFilterPaths.ALL), instead of null comparisons... You can then still have comparisons:
   
       if (filter == MongoFilterPaths.ALL) {
           ...
       }
   
   instead of
   
       if (filter == null) {
           ...
       }
   
   it might be a bit clearer... not sure.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "amit-jain (via GitHub)" <gi...@apache.org>.
amit-jain commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444259634


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {

Review Comment:
   Question: From a quick look it seems that the computation done is largely duplicate of what is done in PathFilter(). Can't we just initialize a new PathFilter by concatenating the includes and excludes from the filters list?



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444382897


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {

Review Comment:
   It is similar but not quite the same. For instance, if there is an index with 
   ```
   IndexA
   includedPaths=/a
   excludedPaths=/a/a1
   
   IndexB
   includedPaths=/a, /b
   excludedPaths=[]
   ```
   Then `/a/a1` should not be excluded. But if we concatenate the included and excluded paths we get:
   ```
   IndexPathsMerged
   includedPaths=/a, /b
   excludedPaths=/a/a1
   ```
   which will exclude `/a/a1`.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444600871


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -101,12 +100,22 @@ public long getDocumentsDownloaded() {
      * filtering in the indexing job. This feature may significantly reduce the number of documents downloaded from
      * Mongo.
      * The performance gains may not be proportional to the reduction in the number of documents downloaded because Mongo
-     * still has to traverse all the documents. This is the case because the regex expression used for path filtering
+     * still has to traverse all the documents. This is required because the regex expression used for path filtering
      * starts with a wildcard (because the _id starts with the depth of the path, so the regex expression must ignore
      * this part). Because of the wildcard at the start, Mongo cannot use of the index on _id.
      */
     public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = "oak.indexer.pipelined.mongoRegexPathFiltering";
     public static final boolean DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING = false;
+
+    /**
+     * Maximum number of elements in the included/excluded paths list used for regex path filtering. If after
+     * merging and de-deduplication of the paths of all the path filters the number of included or excluded paths exceeds
+     * this value, then disable path filtering to avoid creating Mongo queries with large number of filters
+     */
+    public static final String OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = "oak.indexer.pipelined.mongoRegexPathFilteringMaxPaths";
+    public static final int DEFAULT_OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING_MAX_PATHS = 20;

Review Comment:
   > The maximum size of a query is limited by the maximum size of a bson document, which is 16MB.
   
   Great! 
   
   A warning might make sense, but I don't think it's important to have a warning here. I think it's fine.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "steffenvan (via GitHub)" <gi...@apache.org>.
steffenvan commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444260518


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {

Review Comment:
   Do we need to include the root path here, i.e the equivalent of `pathFilters == ["/"]`?



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442950518


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java:
##########
@@ -349,95 +353,132 @@ private void downloadWithNaturalOrdering() throws InterruptedException, TimeoutE
             download(mongoIterable);
 
         } else {
-            downloadAncestors(regexBasePath);
+            downloadAncestors(regexBasePath.included);
 
-            Bson childrenQuery = descendantsFilter(regexBasePath);
-            LOG.info("Downloading using regex path filtering. Downloading children: {}.", childrenQuery);
+            Bson childrenFilter = descendantsFilter(regexBasePath);
+            LOG.info("Downloading from Mongo using filter: {}", childrenFilter);
             FindIterable<NodeDocument> childrenIterable = dbCollection
                     .withReadPreference(readPreference)
-                    .find(childrenQuery)
+                    .find(childrenFilter)
                     .hint(NATURAL_HINT);
             download(childrenIterable);
         }
     }
 
-    private Set<String> getPathsForRegexFiltering() {
+    private MongoFilterPaths getPathsForRegexFiltering() {
         if (!regexPathFiltering) {
             LOG.info("Regex path filtering disabled.");
-            return Set.of();
+            return null;
         }
-        return extractIncludedPaths(pathFilters);
+        LOG.info("Computing included/excluded paths for Mongo regex path filtering. PathFilters: {}", pathFilters.stream()
+                .map(pf -> "PF{includedPaths=" + pf.getIncludedPaths() + ", excludedPaths=" + pf.getExcludedPaths() + "}")
+                .collect(Collectors.joining(", ")));
+        MongoFilterPaths mongoFilterPaths = buildMongoFilter(pathFilters);
+        LOG.info("Paths used for regex filtering on Mongo: {}", mongoFilterPaths);
+        return mongoFilterPaths;
     }
 
-    /**
-     * Aggregates the included paths from the path filters. The final list will not contain duplicates or overlapping
-     * paths (i.e., /a and /a/b).
-     *
-     * @param pathFilters Empty set if path filtering should be disabled, otherwise the paths that should be included
-     *                    in the Mongo query filters
-     */
-    // Package private for testing
-    static Set<String> extractIncludedPaths(List<PathFilter> pathFilters) {
-        // Path filtering is enabled only if there are no excludedPaths.
-        if (pathFilters == null) {
-            return Set.of();
+    static MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return null;
         }
-        Set<String> includedPaths = new HashSet<>();
-        Set<String> excludedPaths = new HashSet<>();
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
         for (PathFilter pathFilter : pathFilters) {
-            includedPaths.addAll(pathFilter.getIncludedPaths());
-            excludedPaths.addAll(pathFilter.getExcludedPaths());
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
         }
-        // Sort by natural order, so that parent paths appear before any children. This makes it easier to compute the
-        // common ancestors of included paths
-        List<String> sortedIncludedPaths = includedPaths.stream()
-                .sorted()
-                .collect(Collectors.toList());
-
-        LOG.info("Paths considered for regex filtering. IncludedPaths: {}, excludedPaths: {}", sortedIncludedPaths, excludedPaths);
-        if (sortedIncludedPaths.contains("/")) {
-            LOG.info("Disabling regex path filtering because root path is in the includedPaths: {}", sortedIncludedPaths);
-            return Set.of();
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        ArrayList<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens

Review Comment:
   I added a configuration set a limit on the number of paths that can be used to build regex path filters. By default, the value is 20. This is limit is applied after merging and de-duplicating the paths in all the path filters, so the algorithm to de-duplicate the paths might still be exposed to the quadratic complexity when using many paths. I tested in my M1 mac, with 10k unique paths it takes two seconds to de-duplicate the list of paths. I think it's ok, it would be very hard to have a index definition with more than 10k paths, probably other parts of the system would break before getting to this point.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444598684


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {
+            return MongoFilterPaths.DOWNLOAD_ALL;
+        }
+        // Merge and deduplicate the included and excluded paths of all filters.
+        // The included paths will also be further de-deuplicated, by removing paths that are children of other path in
+        // the list, that is, by keeping only the top level paths. To make it easy to de-duplicate, we sort the paths
+        // alphabetically.
+        // The list of excluded paths does not need to be sorted, but we do it anyway for consistency when logging the
+        // list of paths.
+        TreeSet<String> sortedCandidateIncludedPaths = new TreeSet<>();
+        TreeSet<String> candidateExcludedPaths = new TreeSet<>();
+        for (PathFilter pathFilter : pathFilters) {
+            sortedCandidateIncludedPaths.addAll(pathFilter.getIncludedPaths());
+            candidateExcludedPaths.addAll(pathFilter.getExcludedPaths());
+        }
+        // Keep only unique included paths. That is, if paths "/a/b" and "/a/b/c" are both in the list, keep only "/a/b"
+        List<String> finalIncludedPathsRoots = new ArrayList<>();
+        LOG.debug("Candidate included paths: {}, candidate excluded paths: {}", sortedCandidateIncludedPaths, candidateExcludedPaths);
+        // The quadratic algorithm below could easily be replaced by linear time algorithm, but it's not worth the added
+        // complexity because the list of paths should never be more than a few tens
+        // Idea for linear time algorithm: after adding a path to the includedPathsRoots, advance in the list of candidates
+        // skipping all paths that are children of the path just added. Since the list is sorted alphabetically, the children
+        // of a path will be next to it in the list
+        for (String candidateIncludedPath : sortedCandidateIncludedPaths) {
+            if (finalIncludedPathsRoots.stream().noneMatch(ancestor -> PathUtils.isAncestor(ancestor, candidateIncludedPath))) {
+                finalIncludedPathsRoots.add(candidateIncludedPath);
+            }
+        }
+
+        List<String> finalExcludedPaths = new ArrayList<>();
+        // Keep an excluded path only if it is not needed by any filter.
+        for (String candidateExcludedPath : candidateExcludedPaths) {
+            boolean notNeeded = pathFilters.stream().allMatch(pathFilter -> pathFilter.filter(candidateExcludedPath) == PathFilter.Result.EXCLUDE);
+            if (notNeeded) {
+                finalExcludedPaths.add(candidateExcludedPath);
+            }
+        }
+
+        // Do not filter if there are too many includedPaths. The official Mongo documentation recommends
+        // not using more than tens of values in the $in filter to avoid performance degradation.
+        // https://www.mongodb.com/docs/manual/reference/operator/query/in/
+        if (finalIncludedPathsRoots.size() > maxNumberOfPaths) {
+            LOG.info("Number of includedPaths ({}) exceed the maximum allowed ({}), downloading everything",
+                    finalIncludedPathsRoots.size(), maxNumberOfPaths);
+            return MongoFilterPaths.DOWNLOAD_ALL;
+        }
+
+        // Also check the number of excluded paths and disable filtering by them if there are too many.
+        // We do not need to revert to download the full repository in the case where there is a reasonable number of
+        // included paths but too many excluded paths. The excluded paths are always children of the included paths, so
+        // if we do not filter on excludedPaths, we simply download everything inside the included paths. This might be
+        // much less than the full repository.
+        if (finalExcludedPaths.size() > maxNumberOfPaths) {
+            LOG.info("Number of excludedPaths ({}) exceed the maximum allowed ({}), disabling filtering of excludedPaths",
+                    finalExcludedPaths.size(), maxNumberOfPaths);
+            finalExcludedPaths = List.of();
+        }
+
+        if (finalExcludedPaths.isEmpty()) {

Review Comment:
   We have documentation for having includedPaths (and queryPaths... but that's when running queries). We don't need documentation for excludedPaths in my view.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "nfsantos (via GitHub)" <gi...@apache.org>.
nfsantos commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1442947021


##########
oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTaskTest.java:
##########
@@ -142,42 +144,101 @@ private List<PathFilter> createIncludedPathFilters(String... paths) {
 
     @Test
     public void ancestorsFilters() {
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.getAncestors(Set.of()));
-        assertEquals(Set.of("/"), PipelinedMongoDownloadTask.getAncestors(Set.of("/")));
-        assertEquals(Set.of("/", "/a"), PipelinedMongoDownloadTask.getAncestors(Set.of("/a")));
-        assertEquals(Set.of("/", "/a", "/b", "/c", "/c/c1", "/c/c1/c2", "/c/c1/c2/c3", "/c/c1/c2/c4"),
-                PipelinedMongoDownloadTask.getAncestors(Set.of("/a", "/b", "/c/c1/c2/c3", "/c/c1/c2/c4"))
+        assertEquals(List.of(), PipelinedMongoDownloadTask.getAncestors(List.of()));
+        assertEquals(List.of("/"), PipelinedMongoDownloadTask.getAncestors(List.of("/")));
+        assertEquals(List.of("/", "/a"), PipelinedMongoDownloadTask.getAncestors(List.of("/a")));
+        assertEquals(List.of("/", "/a", "/b", "/c", "/c/c1", "/c/c1/c2", "/c/c1/c2/c3", "/c/c1/c2/c4"),
+                PipelinedMongoDownloadTask.getAncestors(List.of("/a", "/b", "/c/c1/c2/c3", "/c/c1/c2/c4"))
         );
     }
 
     @Test
-    public void regexFilters() {
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(null));
+    public void regexFilters_includedPaths_only() {
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(null));
 
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(List.of()));
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(List.of()));
 
         List<PathFilter> singlePathFilter = List.of(
                 new PathFilter(List.of("/content/dam"), List.of())
         );
-        assertEquals(Set.of("/content/dam"), PipelinedMongoDownloadTask.extractIncludedPaths(singlePathFilter));
+        assertEquals(new MongoFilterPaths(List.of("/content/dam"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(singlePathFilter));
 
         List<PathFilter> multipleIncludeFilters = createIncludedPathFilters("/content/dam", "/content/dam");
-        assertEquals(Set.of("/content/dam"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFilters));
+        assertEquals(new MongoFilterPaths(List.of("/content/dam"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFilters));
 
-        List<PathFilter> includesRoot = List.of(
-                new PathFilter(List.of("/"), List.of())
-        );
-        assertEquals(Set.of(), PipelinedMongoDownloadTask.extractIncludedPaths(includesRoot));
+        List<PathFilter> includesRoot = createIncludedPathFilters("/", "/a/a1/a2");
+        assertNull(PipelinedMongoDownloadTask.buildMongoFilter(includesRoot));
 
         List<PathFilter> multipleIncludeFiltersDifferent = createIncludedPathFilters("/a/a1", "/a/a1/a2");
-        assertEquals(Set.of("/a/a1"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFiltersDifferent));
+        assertEquals(new MongoFilterPaths(List.of("/a/a1"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFiltersDifferent));
 
         List<PathFilter> multipleIncludeFiltersDifferent2 = createIncludedPathFilters("/a/a1/a2", "/a/a1", "/b", "/c", "/cc");
-        assertEquals(Set.of("/a/a1", "/b", "/c", "/cc"), PipelinedMongoDownloadTask.extractIncludedPaths(multipleIncludeFiltersDifferent2));
+        assertEquals(new MongoFilterPaths(List.of("/a/a1", "/b", "/c", "/cc"), List.of()), PipelinedMongoDownloadTask.buildMongoFilter(multipleIncludeFiltersDifferent2));
+    }
 
-        List<PathFilter> withExcludeFilter = List.of(
-                new PathFilter(List.of("/"), List.of("/var"))
+    @Test
+    public void regexFilters_included_and_excluded_paths() {

Review Comment:
   Changed all the methods to be in camel case. It's the convention for Java.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OAK-10589 - Improve regex path filtering to also handle cases where excludedPaths are defined [jackrabbit-oak]

Posted by "thomasmueller (via GitHub)" <gi...@apache.org>.
thomasmueller commented on code in PR #1258:
URL: https://github.com/apache/jackrabbit-oak/pull/1258#discussion_r1444265459


##########
oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/MongoRegexPathFilterFactory.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.spi.filter.PathFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.TreeSet;
+
+public class MongoRegexPathFilterFactory {
+
+    public static class MongoFilterPaths {
+        // Special value that means "download everything". This is used when regex path filtering is disabled or when
+        // the path filters would require downloading everything. When this is returned, it is preferable to do not
+        // use any filter in the Mongo query, even though using the values in this object as filters would also result
+        // in downloading everything
+        public static final MongoFilterPaths DOWNLOAD_ALL = new MongoFilterPaths(List.of("/"), List.of());
+
+        final List<String> included;
+        final List<String> excluded;
+
+        public MongoFilterPaths(List<String> included, List<String> excluded) {
+            this.included = included;
+            this.excluded = excluded;
+        }
+
+        @Override
+        public String toString() {
+            return "MongoFilterPaths{" +
+                    "included=" + included +
+                    ", excluded=" + excluded +
+                    '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            MongoFilterPaths that = (MongoFilterPaths) o;
+            return Objects.equals(included, that.included) && Objects.equals(excluded, that.excluded);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(included, excluded);
+        }
+    }
+
+    private final static Logger LOG = LoggerFactory.getLogger(MongoRegexPathFilterFactory.class);
+
+    private final int maxNumberOfPaths;
+
+    public MongoRegexPathFilterFactory(int maxNumberOfPaths) {
+        this.maxNumberOfPaths = maxNumberOfPaths;
+    }
+
+    public MongoFilterPaths buildMongoFilter(List<PathFilter> pathFilters) {
+        if (pathFilters == null || pathFilters.isEmpty()) {

Review Comment:
   I see we have a special handling for "includedPaths includes /" below. So that's good.
   
   Just FYI, I only know about one case currently that has this:
   
       "includedPaths": ["/"],
   
   With the change we did for the index definition generator https://oakutils.appspot.com/generate/index - to always add "includedPaths" - we might get more of those in the future.
   
   So yes, it might make sense to support "/". But it's already supported, so that's good.



-- 
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: dev-unsubscribe@jackrabbit.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org