Skip to content

[Backport 3.9] Prune indices by request-level time bounds before the schema is resolved (#5766, #5852) - #5863

Merged
ahkcs merged 2 commits into
opensearch-project:3.9from
ahkcs:backport/backport-5766-to-3.9
Oct 12, 2026
Merged

ahkcs merged 2 commits into
opensearch-project:3.9from
ahkcs:backport/backport-5766-to-3.9

Conversation

@ahkcs

@ahkcs ahkcs commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

Description

Backport of #5766 to 3.9, together with its follow-up fix #5852 (comma-separated sources with request-level time bounds returned 404). #5852 fixes a bug introduced by #5766 and doesn't apply without it, so both go in one PR.

Both commits cherry-pick cleanly and match main.

Verified on this branch: spotlessCheck, unit tests for common, core, ppl, opensearch and opensearch-sql-plugin, and :integ-test:compileTestJava.

Related Issues

Backport of #5766 and #5852

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • Commits are signed per the DCO using --signoff.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

ahkcs added 2 commits October 12, 2026 14:09
…h-project#5852)

* Encode time bounds once for a comma-separated source

With request-level time bounds, AstBuilder encoded the bounds onto every
source of a comma-separated list, and Relation then joined the sources with
commas. TimeBounds uses a comma as its own separator and decodes only the
last block, so `source=a,b` decoded to a garbled name and failed with
"no such index". For a cross-cluster source the `cluster:` strip then cut at
the colon in the timestamp, giving "no such index [55:54]".

Encode the bounds onto the last source only, so the joined name ends in a
single block and decodes to every source with its bounds.

Signed-off-by: Kai Huang <[email protected]>

* Cover comma-separated sources with time bounds end to end

A request with time bounds over a comma-separated source returns its rows, and pruning still drops the out-of-range index from every entry of the list.

Signed-off-by: Kai Huang <[email protected]>

---------

Signed-off-by: Kai Huang <[email protected]>
(cherry picked from commit 866dafc)
Signed-off-by: Kai Huang <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Possible Issue

The prune method returns the original name when bounds is null or pruning is disabled, but it also returns the original name when the node client is absent (via orElse(name)). If the node client is unavailable, pruning silently fails and the full expression is queried. This could lead to unexpected behavior where queries that should be pruned are not, potentially hitting PIT context limits. The silent fallback may mask configuration or deployment issues where the node client is expected but unavailable.

/** {@code name} narrowed to {@code bounds}, or unchanged when pruning is off or declines. */
private String prune(String name, @Nullable TimeBounds bounds) {
  if (bounds == null
      || !Boolean.TRUE.equals(settings.getSettingValue(Settings.Key.QUERY_PRUNING_ENABLED))) {
    return name;
  }
  return client
      .getNodeClient()
      .map(
          node -> {
            String pruned =
                new IndexPruner(node)
                    .prune(
                        new OpenSearchRequest.IndexName(name),
                        timeRangeQuery(bounds),
                        bounds.getTimeField())
                    .toString();
            if (!pruned.equals(name)) {
              log.info("Pruned index expression from {} to {}", name, pruned);
            }
            return pruned;
          })
      .orElse(name);
}
Logic Error

In relation(List<UnresolvedExpression>), only the last element of tableSources is modified with time bounds. For comma-separated sources like logs-*,cape:logs-*, the method creates a new list, modifies only the last element, and constructs a Relation. However, the comment and test suggest all sources should be narrowed. The current implementation only encodes bounds into the final source name, not each individual source. This contradicts the stated behavior that "every source of a comma-separated list" should be narrowed.

private Relation relation(List<UnresolvedExpression> tableSources) {
  if (timeBounds == null) {
    return new Relation(tableSources);
  }
  // Only the last: the sources are joined with commas, and the joined name must end in one block.
  List<UnresolvedExpression> sources = new ArrayList<>(tableSources);
  int last = sources.size() - 1;
  sources.set(last, withTimeBounds(sources.get(last)));
  return new Relation(sources);
}

@github-actions

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Prevent false positive bound detection

The decode method uses lastIndexOf(OPEN) which could match a < character that appears
naturally in a table name rather than as the encoding delimiter. This could cause
incorrect parsing if a legitimate table name contains < followed by the pattern.
Consider adding validation that the decoded bounds can successfully re-encode to the
original string.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [57-78]

 public static Decoded decode(String tableName) {
   if (tableName == null
       || tableName.isEmpty()
       || tableName.charAt(tableName.length() - 1) != CLOSE) {
     return new Decoded(tableName, null);
   }
   int open = tableName.lastIndexOf(OPEN);
   if (open < 1) {
     return new Decoded(tableName, null);
   }
+  String[] parts =
+      tableName.substring(open + 1, tableName.length() - 1).split(String.valueOf(SEPARATOR), -1);
+  if (parts.length != 3) {
+    return new Decoded(tableName, null);
+  }
+  String name = tableName.substring(0, open);
+  try {
+    TimeBounds bounds = new TimeBounds(parts[0], parts[1], parts[2]);
+    // Verify round-trip to prevent false positives
+    if (!bounds.encodeInto(name).equals(tableName)) {
+      return new Decoded(tableName, null);
+    }
+    return new Decoded(name, bounds);
+  } catch (IllegalArgumentException e) {
+    return new Decoded(name, null);
+  }
+}
Suggestion importance[1-10]: 6

__

Why: The suggestion addresses a valid edge case where a table name could naturally contain < characters that might be misinterpreted as encoding delimiters. Adding round-trip validation would prevent false positives. However, the isEncodable() check already prevents encoding when delimiters are present in the values, which partially mitigates this issue.

Low
Handle pruning exceptions explicitly

The pruning operation could fail silently if IndexPruner.prune throws an exception
inside the map lambda. The exception would be swallowed by the Optional chain, and
the original name would be returned without any indication of failure. Wrap the
pruning logic in a try-catch to ensure exceptions are logged.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/OpenSearchStorageEngine.java [75-97]

 private String prune(String name, @Nullable TimeBounds bounds) {
   if (bounds == null
       || !Boolean.TRUE.equals(settings.getSettingValue(Settings.Key.QUERY_PRUNING_ENABLED))) {
     return name;
   }
   return client
       .getNodeClient()
       .map(
           node -> {
-            String pruned =
-                new IndexPruner(node)
-                    .prune(
-                        new OpenSearchRequest.IndexName(name),
-                        timeRangeQuery(bounds),
-                        bounds.getTimeField())
-                    .toString();
-            if (!pruned.equals(name)) {
-              log.info("Pruned index expression from {} to {}", name, pruned);
+            try {
+              String pruned =
+                  new IndexPruner(node)
+                      .prune(
+                          new OpenSearchRequest.IndexName(name),
+                          timeRangeQuery(bounds),
+                          bounds.getTimeField())
+                      .toString();
+              if (!pruned.equals(name)) {
+                log.info("Pruned index expression from {} to {}", name, pruned);
+              }
+              return pruned;
+            } catch (Exception e) {
+              log.warn("Index pruning failed for {}, using original expression", name, e);
+              return name;
             }
-            return pruned;
           })
       .orElse(name);
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion to add explicit exception handling in the prune method is reasonable for better observability. However, looking at the IndexPruner.prune method at line 51-81, it already has a try-catch block that logs warnings and returns the original name on failure. Adding another try-catch here would be redundant, though it could provide more specific context about where the failure occurred.

Low
Possible issue
Validate field capabilities response completeness

The probeMatching method returns a FieldCapabilitiesResponse but only getIndices()
is used. If the response contains no indices or the field capabilities indicate the
field doesn't exist in any index, this could lead to incorrect pruning decisions.
Verify that the field exists in at least one of the returned indices before
proceeding with pruning.

opensearch/src/main/java/org/opensearch/sql/opensearch/request/IndexPruner.java [70-73]

-String[] candidates = indexExpr.probeMatching(filter, timeField).getIndices();
-if (0 < candidates.length && indexExpr.isPrunedBy(candidates.length)) {
+FieldCapabilitiesResponse response = indexExpr.probeMatching(filter, timeField);
+String[] candidates = response.getIndices();
+if (0 < candidates.length && !response.get().isEmpty() && indexExpr.isPrunedBy(candidates.length)) {
   return new IndexName(String.join(",", candidates));
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion to validate that the field exists in the response is reasonable, but the implementation using response.get().isEmpty() is questionable since get() returns a map of field capabilities. The concern about empty responses is valid, though the existing code in IndexPruner already handles failures by catching exceptions and falling back to the original expression.

Low

@codecov

codecov Bot commented Oct 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.39130% with 26 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.89%. Comparing base (bb7514f) to head (169364c).
⚠️ Report is 1 commits behind head on 3.9.

Files with missing lines Patch % Lines
...ql/opensearch/storage/OpenSearchStorageEngine.java 48.14% 13 Missing and 1 partial ⚠️
...n/java/org/opensearch/sql/executor/TimeBounds.java 79.31% 3 Missing and 3 partials ⚠️
...c/main/java/org/opensearch/sql/ppl/PPLService.java 20.00% 4 Missing ⚠️
...java/org/opensearch/sql/ppl/parser/AstBuilder.java 92.85% 1 Missing and 1 partial ⚠️

❌ Your project check has failed because the head coverage (62.89%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##                3.9    #5863      +/-   ##
============================================
+ Coverage     62.86%   62.89%   +0.02%     
- Complexity     8782     8819      +37     
============================================
  Files           938      939       +1     
  Lines         40145    40235      +90     
  Branches       4519     4531      +12     
============================================
+ Hits          25238    25304      +66     
- Misses        14106    14125      +19     
- Partials        801      806       +5     
Flag Coverage Δ
sql-engine 62.89% <77.39%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ahkcs
ahkcs merged commit 7a6ef35 into opensearch-project:3.9 Oct 12, 2026
45 of 47 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants