Skip to content

Stop index pruning from dropping an index it could not reach - #5819

Closed
ahkcs wants to merge 1 commit into
opensearch-project:mainfrom
ahkcs:fix/index-pruning-keep-unreachable
Closed

ahkcs wants to merge 1 commit into
opensearch-project:mainfrom
ahkcs:fix/index-pruning-keep-unreachable

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Index pruning (#5766) probes each index with _field_caps plus an index_filter and keeps the ones that come back. An index whose shards are unavailable can't be probed, and field caps reports no failure for it. The index is just missing from the response, which looks the same as an index proven to hold nothing in range:

GET osdp-*/_field_caps?fields=@timestamp  {"index_filter": {...}}
  indices:        ['osdp-main', 'osdp-textconflict']   # osdp-broken silently missing
  failed_indices: None
  failures:       null

So the unreachable index was pruned out of the expression (#5808). The search that ran next covered every shard it was given, which means:

Every PPL query from Dashboards sends request-level time bounds, which is what turns pruning on, so this is the main path. Measured on a two-node cluster over a 4-shard pattern of 990 documents, with one node stopped:

before after
PPL, pruning on 750, no warning, no error 750 + PARTIAL_RESULT warning
PPL, pruning on, allow_partial_search_results=false 750, no error rejected
equivalent DSL search, same setting HTTP 503 HTTP 503

The fix

Keep any index the probe can't have ruled out. One probe can't tell the two cases apart, but a second _field_caps call with no index filter can:

index filtered probe unfiltered probe conclusion
in range present present keep
healthy, out of range absent present was read, nothing in range → prune
shard unassigned absent absent never read → keep

unsearchable = resolved − unfiltered, then keep = candidates ∪ unsearchable. The search then reaches the missing shard, and #5807 reports it.

  • Readability is judged by a probe, not the routing table. A cluster state request needs cluster:monitor/state, which an index-scoped role doesn't have. The first version of this fix read the routing table: TimeBoundsPruningSecurityIT went red, and those users would have had pruning silently disabled plus a MISSING_PRIVILEGES audit event on every query. A unit test now asserts no cluster state request is issued.
  • No added round trip. The unfiltered probe is sent alongside the filtered one and read only when pruning would narrow. It does add one field-caps request per index to every prunable query.
  • An index deleted mid-query isn't named. Kept indices are re-resolved first. Naming one that retention deleted after the first resolve would fail the search with index_not_found, and the old, out-of-range indices are exactly the ones retention deletes.
  • Remote clusters are no longer pruned. _field_caps and _resolve/index both omit an unreachable remote without error, so local-*,remote:* could narrow to local indices and drop the remote silently. This predates this PR (Prune indices by request-level time bounds before the schema is resolved #5766), but it's the same failure.
  • An index that doesn't map the time field is still pruned. The unfiltered probe lists it, since fields never decides which indices come back, and a range on an unmapped field can't match anything, so dropping it is correct.

Known gap (raised by @dai-chen in #5807)

The probe works per index, not per shard. Suppose an index has one readable shard with nothing in range and another shard, holding the in-range documents, that is unassigned. The unfiltered probe sees the index and the filtered probe doesn't, so it's still pruned. That requires the in-range documents to sit only on the missing shard. It's unusual under default routing, but possible when the range holds very few documents.

The complete fix is for _field_caps to report the shards it couldn't reach; today it returns failed_indices: null. That belongs in core. This PR closes the index-level case, which covers the observed failure (a node drop leaving a whole index unreadable), and I'm happy to open the core issue alongside it.

Testing

  • IndexPrunerTest (38), including checks that no cluster state request is issued, both probes are sent before either is read, an index deleted after resolving is not named, and a remote expression is not pruned.
  • ShardFailureWarningSecurityIT gains an out-of-range index and two cases, run as an index-scoped user:
query expected
source=shard_sec_* | stats count(), no bounds 3 + PARTIAL_RESULT, "1 of 3 shards"
source=shard_sec_* | stats count(), with bounds 2 + PARTIAL_RESULT, "1 of 2 shards" (the old index is pruned, the unreadable one kept)
source=shard_sec_* | fields legacy_only, with bounds HTTP 400 Field [legacy_only] not found. (the out-of-range index is still pruned)
  • The bounds-driven cases carry @RequiresCapability(TIME_BOUNDS_PRUNING) and pin pruning on, like TimeBoundsPruningSecurityIT.
  • executeQueryAsUserWithBounds and the pruning setting helpers move into SecurityTestBase, sharing one request helper with executeQueryAsUser.

Related Issues

Resolves #5808

Check List

  • New functionality includes testing.
  • New functionality has been documented. n/a, behavior fix.
  • API changes companion pull request created, if applicable. n/a.
  • Commits are signed per the DCO using --signoff.
  • Public documentation issue/PR created, if applicable. n/a.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 240400d)

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 unreadableIndices method removes indices from the unreadable set that are not in the re-resolved set. If an index is deleted between the initial resolve and the re-resolve, it will be removed from unreadable. However, if the index was also in the candidates set (from the match probe), it will still be included in the final keep set at line 87, potentially naming a deleted index in the search request. This contradicts the stated goal of not naming deleted indices.

Set<String> unreadableIndices(FieldCapabilitiesResponse readableProbe) {
  Set<String> unreadable = names(resolved());
  unreadable.removeAll(new HashSet<>(Arrays.asList(readableProbe.getIndices())));
  if (!unreadable.isEmpty()) {
    // Re-resolve: naming an index deleted since would fail the search.
    unreadable.retainAll(names(resolve()));
  }
  return unreadable;
}
Possible Issue

At line 93, if keep.size() equals the resolved index count, the method returns the original indexName without pruning. However, keep may contain indices that were deleted after resolving (if they were in candidates but not caught by the re-resolve check). This means the unpruned expression could still resolve to a different set of indices than what keep represents, leading to inconsistent behavior.

  return new IndexName(String.join(",", keep));
}
log.info("Index pruning declined: keeping unreadable indices left nothing to drop");
return indexName;

@codecov

codecov Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.22222% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 63.43%. Comparing base (f48b2b1) to head (240400d).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...opensearch/sql/opensearch/request/IndexPruner.java 97.22% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5819      +/-   ##
============================================
+ Coverage     63.40%   63.43%   +0.02%     
- Complexity     8898     8902       +4     
============================================
  Files           950      950              
  Lines         40386    40415      +29     
  Branches       4553     4560       +7     
============================================
+ Hits          25608    25636      +28     
  Misses        13932    13932              
- Partials        846      847       +1     
Flag Coverage Δ
sql-engine 63.43% <97.22%> (+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.

@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit bdf1089

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 240400d
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Avoid unnecessary probe result retrieval

The readable.actionGet(PROBE_TIMEOUT) call is made unconditionally even when
candidates is empty or equals all resolved indices. This wastes resources on a probe
whose result won't be used. Consider checking if pruning would occur before
retrieving the readable probe result.

opensearch/src/main/java/org/opensearch/sql/opensearch/request/IndexPruner.java [84-96]

-Set<String> unreadable = indexExpr.unreadableIndices(readable.actionGet(PROBE_TIMEOUT));
-Set<String> keep = new LinkedHashSet<>(Arrays.asList(candidates));
-keep.addAll(unreadable);
-if (!unreadable.isEmpty()) {
-  log.info(
-      "Index pruning kept {} unreadable indices: {}", unreadable.size(), cap(unreadable));
-}
-if (indexExpr.isPrunedBy(keep.size())) {
-  return new IndexName(String.join(",", keep));
+if (indexExpr.isPrunedBy(candidates.length)) {
+  Set<String> unreadable = indexExpr.unreadableIndices(readable.actionGet(PROBE_TIMEOUT));
+  Set<String> keep = new LinkedHashSet<>(Arrays.asList(candidates));
+  keep.addAll(unreadable);
+  if (!unreadable.isEmpty()) {
+    log.info(
+        "Index pruning kept {} unreadable indices: {}", unreadable.size(), cap(unreadable));
+  }
+  if (indexExpr.isPrunedBy(keep.size())) {
+    return new IndexName(String.join(",", keep));
+  }
 }
Suggestion importance[1-10]: 3

__

Why: While the suggestion correctly identifies that readable.actionGet() could be deferred, the current implementation sends both probes immediately (line 81) to maximize parallelism, which is valuable. The suggested optimization would reduce parallelism and only provide marginal benefit in edge cases where pruning doesn't occur.

Low

Previous suggestions

Suggestions up to commit bdf1089
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle readability probe failures gracefully

The probe(null, timeField) call could throw an exception if the field capabilities
request fails, but this exception is not caught. According to the test
shouldNotPruneWhenTheReadabilityProbeFails, failures should be handled gracefully by
falling back to the original index expression rather than propagating the exception.

opensearch/src/main/java/org/opensearch/sql/opensearch/request/IndexPruner.java [160-169]

 Set<String> indicesNotProvenEmpty(String timeField) {
-  Set<String> readable = new HashSet<>(Arrays.asList(probe(null, timeField).getIndices()));
-  Set<String> missing = new LinkedHashSet<>();
-  for (ResolveIndexAction.ResolvedIndex index : resolved().getIndices()) {
-    if (!readable.contains(index.getName())) {
-      missing.add(index.getName());
+  try {
+    Set<String> readable = new HashSet<>(Arrays.asList(probe(null, timeField).getIndices()));
+    Set<String> missing = new LinkedHashSet<>();
+    for (ResolveIndexAction.ResolvedIndex index : resolved().getIndices()) {
+      if (!readable.contains(index.getName())) {
+        missing.add(index.getName());
+      }
     }
+    return missing;
+  } catch (Exception e) {
+    log.warn("Failed to probe readable indices, treating all as readable", e);
+    return new LinkedHashSet<>();
   }
-  return missing;
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that probe(null, timeField) can throw an exception, and the test shouldNotPruneWhenTheReadabilityProbeFails expects graceful handling. However, the exception is currently caught at line 67 in the outer prune method's try-catch block, which returns the original indexName. Adding explicit exception handling here would make the code more robust and clearer.

Medium

Pruning probes each index with field caps and an index filter, keeping the ones
that come back. An index whose shards cannot be read does not come back either,
and field caps reports no failure for it, so pruning dropped it. The search then
covered every shard it was given, so neither the PARTIAL_RESULT warning nor
search.default_allow_partial_results=false could see the loss. Measured on a
two-node cluster over a 4-shard pattern of 990 documents with one node stopped:
stats count() returned 750 with no warning and no error.

Keep any resolved index that an unfiltered field caps probe cannot read either;
a readable index answers that probe whatever the time range. The search then
reaches the missing shard and reports it. Readability is judged by a probe
rather than the routing table, because cluster state needs
cluster:monitor/state, which an index-scoped role lacks.

- The unfiltered probe is sent alongside the filtered one, so it adds no round
  trip. Its answer is read only when pruning would narrow.
- Kept indices are re-resolved first, so an index deleted mid-query is not
  named and cannot fail the search with index_not_found.
- An expression naming a remote cluster is no longer pruned: field caps and
  resolve both omit an unreachable remote without error.

Known gap: the probe works per index, not per shard. An index readable through a
shard holding nothing in range, while the shard holding in-range documents is
unassigned, still looks prunable. Closing it needs field caps to report the
shards it could not reach.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the fix/index-pruning-keep-unreachable branch from bdf1089 to 240400d Compare October 6, 2026 22:17
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 240400d

@ahkcs

ahkcs commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Moved the fix to the core side:
opensearch-project/OpenSearch#23262

@ahkcs ahkcs closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Index pruning silently drops an index it cannot reach, hiding missing shards

1 participant