Skip to content

Prune indices by request-level time bounds before the schema is resolved - #5766

Merged
ahkcs merged 35 commits into
opensearch-project:mainfrom
ahkcs:feat/time-range-index-pruning
Sep 16, 2026
Merged

ahkcs merged 35 commits into
opensearch-project:mainfrom
ahkcs:feat/time-range-index-pruning

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Implements the schema-conflict half of Approach 1 that #5727 left open, as Approach 3 of that design: a request-level time range, applied while the table is still being resolved.

A wildcard index expression is expanded — and the mapping of every index it matches merged — before any predicate in the query text has been parsed, so nothing downstream of that resolution can narrow it. #5727 reads its range from the filter already sitting in the pushdown context, which is the broadest coverage available without touching the request contract but runs after the merge. Declaring the range on the request puts it in hand before planning starts:

The bounds travel encoded into the table name, so they reach the storage engine through the name the query already resolves rather than a channel of their own — the trick SystemIndexUtils.restTable already uses for the rest command:

BROWSER  picker 2026-08-01 .. 2026-08-31, dataset prune-demo-*
   |     one parse of the range -> the appended `where` AND the bounds
   v
POST _plugins/_ppl
  { "query": "source = prune-demo-* | where `timestamp` >= '2026-08-01 00:00:00.000'
                                      and `timestamp` <= '2026-08-31 23:59:59.999' | stats count()",
    "time_field": "timestamp", "start_time": "2026-08-01 ...", "end_time": "2026-08-31 ..." }
   v
PPLQueryRequest.getTimeBounds()  ->  TimeBounds
   v
AstBuilder   ENCODE into the outermost source's name (that source only)
   |            prune-demo-*  ->  prune-demo-*<timestamp,2026-08-01 ...,2026-08-31 ...>
   v
planning     OpenSearchSchema.registerTable(name) -> storageEngine.getTable(schema, name)
   v
OpenSearchStorageEngine.getTable    <- the one seam BOTH engines resolve a table through
   |  DECODE   name = prune-demo-*   bounds = timestamp, t0, t1
   |  IndexPruner  ->  _field_caps(fields=[timestamp], index_filter=range)
   |                   8 indices in, 1 can match
   v
new OpenSearchIndex(.., "prune-demo-2026.08")
        ^ the mapping merge is now over ONE index, not eight
   v
1 index / 1 shard read instead of 8, and the rows are identical -- every index
dropped was one the query's own `where` had already excluded

Decoding lands before the mapping merge, which is the ordering problem this PR exists to solve. It is also the one method both engines resolve a table through (Analyzer.visitRelation on V2, OpenSearchSchema.registerTable on Calcite), so nothing between the request and the storage engine has to know the bounds exist.

Following the design's shape:

  • Bounds narrow the outermost source= only. A join's other side, a subsearch's source, a multisearch dataset and a lookup's dimension table are left alone. A client splices its own time filter after the first command, so a secondary source keeps every row; narrowing one would drop indices nothing filtered. Splunk's picker does reach a subsearch, but as a row filter on the subsearch itself — reproducing that is Approach 2 of [FEATURE] Improve PIT usage for large queries over wildcard index patterns #5698, not index selection.
  • Narrowing happens as the table is built, not by mutating a table afterwards: a table's row type is derived from the merge, so once one exists the cost is already paid. Carrying the range in the table name keeps the probe in the module that owns a client to probe with, and needs no new interface, no plan field and no QueryService signature.
  • Bounds are carried as the strings the request sent and handed to _field_caps as-is, so OpenSearch's own date parser reads them and date math works. Re-interpreting them here risks a narrower window than the caller meant, which would drop an index that can match — the divergence hazard the design flags for Approach 1.

Gated by plugins.query.pruning.enabled, which #5759 turns on by default.

Two additions the design leaves implicit

time_field. The design assumes @timestamp. A Dashboards index pattern is routinely configured on another field — OpenSearch Dashboards' own sample-data pattern uses timestamp — and would otherwise never prune. Defaults to @timestamp, so a request that says nothing behaves as designed.

An index that does not map time_field is pruned like any other that cannot match: under a request-level time range a document with no time value is in no window, which is also what the pushed-down-filter path does (index_pruning.yml asserts it). The consequence is deliberate and documented — such an index's rows, and its schema, go with it, so a query naming a field only it maps fails with Field [x] not found. rather than quietly returning nothing.

A format list on the probe range. Passing bounds through raw means the field's own format applies, and OpenSearch's default rejects YYYY-MM-DD HH:mm:ss.SSS — the spelling a client that also writes the bound into the query text produces, since PPL accepts it there. Without this the probe throws, the exception is caught, and pruning silently declines. This was caught only by the ITs; 2 of 8 failed with "nothing was pruned" and the sole symptom was absence. The list is strict_date_optional_time||epoch_millis||yyyy-MM-dd HH:mm:ss.SSS; date math is resolved before any of it applies.

Example

Eight monthly indices. The newest renamed a field's shape — attributes.cluster was an object holding name, and is a plain keyword after the roll — so merging them makes charting by it fail.

Without bounds, every index is merged and the object wins:

POST _plugins/_ppl
{"query": "source=prune-demo-2026.* | where `timestamp` >= '...' and `timestamp` <= '...'
           | chart count() over timestamp by attributes.cluster"}

{"error": {"reason": "Cannot chart by [attributes.cluster] because it is an object.", "status": 400}}

With them, only the index that can hold data in the window is resolved:

{"query": "...", "time_field": "timestamp", "start_time": "now-15m", "end_time": "now"}

{"schema": [{"name": "timestamp"}, {"name": "attributes.cluster"}, {"name": "count()"}],
 "total": 50}
[INFO ][o.o.s.o.s.OpenSearchStorageEngine] Pruned index expression from prune-demo-2026.* to prune-demo-2026.09

A wider picker range prunes proportionally rather than all-or-nothing — prune-demo-2026.* → .07,.08,.09 for two months — and a range no index can match declines rather than pruning everything:

[INFO ][o.o.s.o.r.IndexPruner] Index pruning declined: 0 of 8 indices matched

Testing the changes

Suite Result
core + ppl + opensearch unit 9138 passed / 0 failed
CalciteTimeBoundsPruningIT (new) 10 passed (20 across both pushdown configurations)
TimeBoundsPruningSecurityIT (new) 5 passed
TimeBoundsTest (new) 30 passed — round trip for every bound spelling accepted
AstTimeBoundsTest (new) 6 passed — which sources get narrowed, and which do not
yamlRestTest (incl. #5727's index_pruning.yml) 204 passed
CalcitePPLBasicIT / CalcitePPLLookupIT / CalciteMultisearchCommandIT 47 / 17 / 22 passed

The last row is the regression cover that matters for the encoding: every source a query names goes through the same AstBuilder code path, so source=, lookup and a multisearch dataset are all exercised.

New IT cases: the schema resolves from the in-range indices only (a field only the out-of-range ones map stops resolving); the whole pattern resolves without bounds; row counts are identical with and without; a range covering every index prunes none; bounds are ignored when the setting is off, when unusable, and when the field is unmapped; an index without the time field is pruned along with its schema; and a join's other side and a subsearch's source keep every row.

Also verified live on a security-enabled cluster, since the bounds cross the transport→worker handoff that #5739 and #5758 each had to fix for a different per-request signal — here they ride the object graph, so there is nothing on ThreadContext to drop. TimeBoundsPruningSecurityIT covers it; note integTestWithSecurity cannot run locally at the moment because today's snapshot distro ships jackson-core-2.22.1 while the security plugin's own zip carries 2.22.2 (the existing PartialResultSecurityIT fails identically), so that suite is CI-verified only.

Unusable bounds are dropped rather than rejected: they only decide which indices are read, so failing a query over a parameter it does not need is the worse outcome.

API surface

Three new request-body parameters — start_time, end_time, time_field — and nothing else:

  • No new endpoint. POST /_plugins/_ppl is unchanged.
  • No transport or BWC work. The body already travels as one JSON string in TransportPPLQueryRequest.writeTo, so there is no StreamOutput change and no version gate. fetch_size is the precedent: a planning-affecting body field read straight off jsonContent, which the transport already carries. (partial_result is not — it has its own writeOptionalBoolean field, so it would have needed a wire change.)
  • Reading them is additive. A request that omits them behaves exactly as before, and an older cluster ignores them, so the Dashboards side can ship independently.

They do change behaviour when present, which is the point, so this is an API addition rather than a purely internal change — the api-specification companion PR is noted unchecked below.

Internally nothing is added to core's storage contract: no new interface, and StorageEngine.getTable keeps its signature. Other engines are untouched — a name they were never handed bounds in decodes to itself.

Files touched

File Change
core/.../executor/TimeBounds.java new — the request-level window, kept as the strings the request sent, plus the table-name codec
ppl/.../domain/PPLQueryRequest.java reads start_time / end_time / time_field off the body
ppl/.../PPLService.java hands them to the AST builder
ppl/.../parser/AstBuilder.java encodes them into the outermost source's name; isMainSource decides which that is
opensearch/.../storage/OpenSearchStorageEngine.java decodes the name and builds the table already narrowed
opensearch/.../request/IndexPruner.java takes the field the range is on, rather than assuming @timestamp
docs/user/admin/settings.rst, docs/user/interfaces/endpoint.rst the parameters, the literals accepted, and what they do and do not guarantee

Split out of this PR

Testing through Dashboards surfaced a partial-result defect: chart/timechart aggregate twice over the same scan on different group keys, so partial mode could exclude a different index set per aggregation — the top-N ranking then picks columns from rows that are not in the chart. It reproduces on main with pruning off, so it is not from this PR, and it is now #5777.

Related Issues

Part of #5698. Builds on #5727; expects #5759.

Front-end counterpart: opensearch-project/OpenSearch-Dashboards#12722.

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • New functionality has javadoc added.
  • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

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

Review notes

A self-review and a joint review against the Dashboards side turned up several defects, fixed in the later commits and worth recording:

  1. An index that does not map the time field. _field_caps reports it as not-matching, indistinguishably from one whose values fall outside the range. A first attempt retained such indices via an extra include_unmapped probe, but that regressed Avoid PIT context exhaustion by pruning indices that cannot match #5727's own index_pruning.yml case (on the pushdown path the range is the query's filter, so dropping the index is lossless there) and it left the partial-result feature something to exclude, producing a spurious "mapping conflict" banner on a field that was merely absent. Both paths now prune it, consistently.
  2. analyze dropped the bounds on both of its phases, so "analyze": true reported a plan over an index expression the execution would not have used.
  3. URL parameters could not work. BaseRestHandler rejects parameters absent from responseParams(), so ?start_time=… was a 400, and a GET carries no body for the loop to write into. Removed rather than half-supported.
  4. The security IT could not pass. createRoleWithIndexAccess granted neither indices:admin/resolve/index nor indices:data/read/field_caps*, so both probes were denied and pruning declined silently. Granting them is load-bearing: taking them back out makes the positive case fail again, which is also the first direct evidence for the permission limitation the manual documents.
  5. Both ITs pinned the pruning setting to false on teardown, which since Enable plugins.query.pruning.enabled by default #5759 disables the feature for every later class sharing the cluster. They clear the override instead.
  6. The bounds were threaded down the plan in the first shape of this PR — a field on AbstractPlan and its three subclasses, three QueryService overloads, an OpenSearchSchema constructor and a SupportsIndexPruning marker. Encoding them into the table name instead (@penghuo's suggestion) deleted all of it, 281 lines and ten files, and reached the V2 path that the Calcite-only schema hook had silently skipped.
  7. Bounds were applied to every source at first, including a lookup's dimension table and a join's other side. @penghuo and @mengweieric both caught it, from different directions: a lookup table is a static dataset with no window, and a client's where clause only covers the first command, so narrowing a secondary source drops rows nothing filtered. Now only the outermost source= is narrowed, decided structurally in isMainSource rather than by visit order. The two ITs that asserted the old behaviour now assert the invariant instead.
  8. The probe's format list was needed for a bound spelled as a UTC wall clock — the spelling a client that also writes it into the query text produces. Without it the probe throws, the exception is swallowed, and pruning silently declines; two ITs failed with absence as their only symptom.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 468418e)

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 decode method silently returns the original table name with null bounds when parsing fails (line 76), but the constructor throws IllegalArgumentException for blank fields. If an encoded name contains blank parts (e.g., table< ,start,end>), decode catches the exception and returns new Decoded(name, null), effectively ignoring malformed encoded bounds. This could mask configuration errors where a client sends invalid bounds that should be rejected. Consider logging a warning when catching IllegalArgumentException during decode to surface these silent failures.

try {
  return new Decoded(name, new TimeBounds(parts[0], parts[1], parts[2]));
} catch (IllegalArgumentException e) {
  return new Decoded(name, null);
}
Possible Issue

The prune method returns the original name when bounds is null OR when pruning is disabled (line 76-79). However, if getNodeClient() returns empty (line 96), it also falls back to the original name. This means a query with valid bounds on a client without node access silently skips pruning with no indication to the caller. While documented as a fallback behavior, this could lead to unexpected memory exhaustion (the issue pruning was meant to solve) when node client is unavailable. Consider logging at WARN level when node client is absent but bounds are present, so operators can detect this configuration issue.

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);
}
Possible Issue

The getTimeBounds method logs a warning and returns null when only one of start_time or end_time is present (line 202-206), but it also returns null when both are present but the TimeBounds constructor throws (line 213-215). The second case logs "Ignoring unusable time bounds" without specifying which field is invalid. If a user sends start_time with a typo and end_time correctly, they get a generic warning with no hint about which parameter failed validation. Consider including the exception message in the log to help diagnose which bound is malformed.

try {
  return new TimeBounds(
      jsonContent.optString(TIME_FIELD_FIELD, IMPLICIT_FIELD_TIMESTAMP),
      jsonContent.optString(START_TIME_FIELD, null),
      jsonContent.optString(END_TIME_FIELD, null));
} catch (RuntimeException e) {
  LOG.warn("Ignoring unusable time bounds: {}", e.getMessage());
  return null;
}

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 468418e

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for candidates array

The code retrieves a FieldCapabilitiesResponse and immediately calls getIndices() to
get the array, then checks its length. If getIndices() returns null (which is
possible in some edge cases), this will throw a NullPointerException. Add a null
check before accessing the array length to prevent potential crashes.

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)) {
+if (candidates != null && 0 < candidates.length && indexExpr.isPrunedBy(candidates.length)) {
   return new IndexName(String.join(",", candidates));
 }
Suggestion importance[1-10]: 7

__

Why: Valid defensive programming suggestion. While FieldCapabilitiesResponse.getIndices() typically doesn't return null in normal operation, adding a null check prevents potential NullPointerException in edge cases and improves robustness.

Medium
General
Validate trimmed value for consistency

The requireText method trims the value after validation, but the validation checks
if the original value is blank. If a value consists only of whitespace, isBlank()
returns true and throws an exception before trimming occurs. However, if the value
has leading/trailing whitespace with non-blank content, it passes validation but
gets trimmed. Consider validating the trimmed value to ensure consistency.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [89-94]

 private static String requireText(String value, String name) {
-  if (value == null || value.isBlank()) {
+  if (value == null) {
     throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
   }
-  return value.trim();
+  String trimmed = value.trim();
+  if (trimmed.isEmpty()) {
+    throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
+  }
+  return trimmed;
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that isBlank() checks the original value before trimming. Validating the trimmed value improves consistency, though the current implementation is functionally correct since isBlank() returns true for whitespace-only strings.

Low
Return original name on decode failure

The decode method catches IllegalArgumentException when constructing TimeBounds but
returns the decoded name without the encoded suffix. If the encoded portion is
malformed, this silently strips it and returns a potentially incorrect table name.
Consider returning the original tableName unchanged when decoding fails to preserve
the original input.

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 {
     return new Decoded(name, new TimeBounds(parts[0], parts[1], parts[2]));
   } catch (IllegalArgumentException e) {
-    return new Decoded(name, null);
+    return new Decoded(tableName, null);
   }
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion misunderstands the intent. When decoding fails due to malformed bounds, returning name (the table name without the encoded suffix) is correct behavior, as the method aims to extract the base table name. Returning tableName unchanged would keep the malformed encoding, which is not desirable.

Low

Previous suggestions

Suggestions up to commit 97ad23a
CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for candidates array

The code retrieves the full FieldCapabilitiesResponse but only uses getIndices(). If
getIndices() returns null (which can happen in certain failure scenarios), calling
candidates.length will throw a NullPointerException. Add a null check before
accessing the array length to prevent potential crashes during index pruning
failures.

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)) {
+if (candidates != null && 0 < candidates.length && indexExpr.isPrunedBy(candidates.length)) {
   return new IndexName(String.join(",", candidates));
 }
Suggestion importance[1-10]: 7

__

Why: Adding a null check for candidates prevents potential NullPointerException in failure scenarios. While the code is wrapped in a try-catch that handles exceptions, explicit null checking improves robustness and makes the code more defensive against API contract changes.

Medium
General
Validate trimmed value for consistency

The requireText method trims the value after validation, but the validation uses
isBlank() which already considers trimmed content. If a value contains only
whitespace, isBlank() returns true and throws an exception before trim() is called.
However, if the value has leading/trailing whitespace with non-blank content, it
passes validation but gets trimmed. Consider validating the trimmed value to ensure
consistency between what's validated and what's returned.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [89-94]

 private static String requireText(String value, String name) {
-  if (value == null || value.isBlank()) {
+  if (value == null) {
     throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
   }
-  return value.trim();
+  String trimmed = value.trim();
+  if (trimmed.isEmpty()) {
+    throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
+  }
+  return trimmed;
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion improves code clarity by validating the trimmed value, but the current implementation using isBlank() is functionally correct since it checks for whitespace-only strings. The improvement is minor and mainly affects code readability.

Low
Optimize parent chain traversal logic

The method traverses the entire parent chain to check for SubSearchContext, but it
already verified specific parent types in the initial condition. If those parent
checks pass but a SubSearchContext exists higher up, the logic may be inconsistent.
Consider whether the initial parent type checks are sufficient, or document why the
full traversal is necessary despite the specific parent requirements.

ppl/src/main/java/org/opensearch/sql/ppl/parser/AstBuilder.java [207-218]

 private boolean isMainSource(TableSourceClauseContext ctx) {
+  // Verify immediate parent structure
   if (!(ctx.getParent() instanceof OpenSearchPPLParser.TableOrSubqueryClauseContext)
       || !(ctx.getParent().getParent() instanceof OpenSearchPPLParser.FromClauseContext)) {
     return false;
   }
-  for (RuleContext parent = ctx.getParent(); parent != null; parent = parent.getParent()) {
+  // Ensure not within a subsearch by checking entire ancestor chain
+  for (RuleContext parent = ctx.getParent().getParent(); parent != null; parent = parent.getParent()) {
     if (parent instanceof OpenSearchPPLParser.SubSearchContext) {
       return false;
     }
   }
   return true;
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion adds a comment and starts the traversal from ctx.getParent().getParent() instead of ctx.getParent(), which is a minor optimization. However, the original logic is correct and the improvement is marginal since the first two iterations would fail the instanceof check anyway.

Low
Suggestions up to commit 705d0e8
CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for candidates array

Handle the case where getIndices() returns null. The
FieldCapabilitiesResponse.getIndices() method can return null when no indices match,
which would cause a NullPointerException when calling .length. Add a null check
before accessing the array.

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

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

__

Why: While adding a null check is generally good practice, the FieldCapabilitiesResponse.getIndices() method returns an empty array rather than null when no indices match. The suggestion addresses a theoretical issue that doesn't occur in practice with this API, making it a minor defensive improvement.

Low
General
Add null safety to encoding check

Add a null check before calling indexOf() on the value parameter. Although
requireText() validates non-null in the constructor, this private method could be
called with null in future refactorings, leading to a NullPointerException.
Defensive programming suggests adding the check.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [85-87]

 private static boolean isEncodable(String value) {
-  return value.indexOf(OPEN) < 0 && value.indexOf(CLOSE) < 0 && value.indexOf(SEPARATOR) < 0;
+  return value != null 
+      && value.indexOf(OPEN) < 0 
+      && value.indexOf(CLOSE) < 0 
+      && value.indexOf(SEPARATOR) < 0;
 }
Suggestion importance[1-10]: 2

__

Why: The suggestion adds defensive null checking to isEncodable(), but this is unnecessary since the method is private and only called from isEncodable() (line 82) after requireText() has already validated non-null values in the constructor. The suggestion addresses a non-existent issue in the current code.

Low
Suggestions up to commit e805474
CategorySuggestion                                                                                                                                    Impact
General
Catch specific exception type

The catch block catches all RuntimeException types, which is overly broad. Since
TimeBounds constructor throws IllegalArgumentException for invalid inputs, catch
that specific exception instead to avoid masking unexpected runtime errors.

ppl/src/main/java/org/opensearch/sql/ppl/domain/PPLQueryRequest.java [221-229]

 try {
   return new TimeBounds(
       jsonContent.optString(TIME_FIELD_FIELD, IMPLICIT_FIELD_TIMESTAMP),
       jsonContent.optString(START_TIME_FIELD, null),
       jsonContent.optString(END_TIME_FIELD, null));
-} catch (RuntimeException e) {
+} catch (IllegalArgumentException e) {
   LOG.warn("Ignoring unusable time bounds: {}", e.getMessage());
   return null;
 }
Suggestion importance[1-10]: 6

__

Why: Catching IllegalArgumentException specifically instead of all RuntimeException types is a good practice that prevents masking unexpected errors while still handling the known validation failures from TimeBounds constructor.

Low
Add warning when encoding fails

The encodeInto method silently returns the original table name when bounds cannot be
encoded. This could lead to unexpected behavior where pruning is silently skipped.
Consider logging a warning when encoding fails to help diagnose issues where pruning
doesn't occur as expected.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [43-48]

 public String encodeInto(String tableName) {
   if (!isEncodable()) {
+    log.warn("Cannot encode time bounds into table name '{}': delimiters present in bounds", tableName);
     return tableName;
   }
   return tableName + OPEN + timeField + SEPARATOR + start + SEPARATOR + end + CLOSE;
 }
Suggestion importance[1-10]: 5

__

Why: Adding a warning when encoding fails would improve debuggability, but the suggestion assumes a log field exists in TimeBounds class which is not present in the code. The class would need to be annotated with @Log4j2 or have a logger field added first.

Low
Check for response errors

The code retrieves the full FieldCapabilitiesResponse but only uses the indices
array. If the response contains additional metadata or errors that should be
checked, they are currently ignored. Verify that ignoring potential errors in the
response is safe, especially since the documentation mentions that per-index
failures are not surfaced.

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

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

__

Why: While extracting the response to a variable improves readability slightly, the suggestion to "verify that ignoring potential errors is safe" is more of a question than an actionable improvement. The existing code already handles failures via the outer try-catch block.

Low
Suggestions up to commit 975c7ef
CategorySuggestion                                                                                                                                    Impact
General
Log when node client unavailable

The prune method silently returns the original name when getNodeClient() returns
empty, which could mask configuration or connectivity issues. Consider logging a
warning when the node client is unavailable to aid debugging and monitoring of
pruning failures.

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

 private String prune(String name, @Nullable TimeBounds bounds) {
   if (bounds == null || !isPruningEnabled(settings)) {
     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);
+      .orElseGet(() -> {
+        log.warn("Node client unavailable; skipping index pruning for {}", name);
+        return name;
+      });
 }
Suggestion importance[1-10]: 7

__

Why: Adding a warning log when the node client is unavailable improves observability and helps with debugging pruning failures. This is a valuable enhancement for monitoring and troubleshooting.

Medium
Validate after trimming for consistency

The requireText method trims the value after validation, but the validation uses
isBlank() which already considers whitespace-only strings as blank. However, if a
string contains only whitespace, isBlank() returns true and an exception is thrown
before trim() is called. Consider validating after trimming to ensure consistent
behavior and clearer error messages.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [89-94]

 private static String requireText(String value, String name) {
-  if (value == null || value.isBlank()) {
+  if (value == null) {
     throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
   }
-  return value.trim();
+  String trimmed = value.trim();
+  if (trimmed.isEmpty()) {
+    throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
+  }
+  return trimmed;
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion improves code clarity by trimming before validation, making the logic more straightforward. However, the current implementation is functionally correct since isBlank() already handles whitespace-only strings, so the impact is moderate.

Low
Extract response before using indices

The code retrieves the full FieldCapabilitiesResponse but only uses getIndices(). If
the response is large or contains additional data, this could be inefficient.
Consider whether additional response data might be needed for validation or error
handling, or document why only indices are extracted.

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

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

__

Why: The suggestion extracts the response into a variable for potential future use, but the current code is already clear and efficient. The improvement is minimal unless additional response data is needed later.

Low
Suggestions up to commit 3f22a42
CategorySuggestion                                                                                                                                    Impact
General
Validate trimmed value for consistency

The requireText method trims the value after validation, but the validation uses
isBlank() which already considers whitespace-only strings as blank. This creates a
potential inconsistency where a string with only whitespace would fail validation
before being trimmed. Consider validating the trimmed value instead to ensure
consistent behavior.

core/src/main/java/org/opensearch/sql/executor/TimeBounds.java [89-94]

 private static String requireText(String value, String name) {
-  if (value == null || value.isBlank()) {
+  if (value == null || value.trim().isEmpty()) {
     throw new IllegalArgumentException(String.format(Locale.ROOT, "%s must not be blank", name));
   }
   return value.trim();
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion is technically correct but has minimal impact. Using isBlank() already handles whitespace-only strings correctly, and the current implementation is functionally equivalent to the proposed change. The improvement is marginal in terms of code clarity.

Low

The schema-conflict half of Approach 1 that opensearch-project#5727 left open, implemented as Approach 3
of the design on opensearch-project#5698: a request-level time range, applied while the table is still
being resolved.

A wildcard index expression is expanded -- and the mapping of every index it matches
merged -- before any predicate in the query text has been parsed, so nothing
downstream of that resolution can narrow it. opensearch-project#5727 reads its range from the filter
already sitting in the pushdown context, which is the broadest coverage available
without an API change but runs too late for the merge. Declaring the range on the
request puts it in hand before planning starts:

  start_time/end_time/time_field -> PPLQueryRequest.getTimeBounds -> AbstractPlan
  -> QueryService.buildFrameworkConfig (seeded once) -> OpenSearchSchema.registerTable
  -> OpenSearchStorageEngine.getTable(.., TimeBounds) -> IndexPruner -> OpenSearchIndex

Following the design's shape:

- Bounds are global, applied to every table the query resolves rather than attributed
  to one relation -- the scope Splunk's time range picker and ES|QL's request-level
  filter have. That is what lets them be a plain request parameter with no AST work,
  no visitor change and no ordering problem.
- Narrowing happens as the table is built, via a new SupportsIndexPruning the storage
  engine implements, not by mutating a table afterwards: a table's row type is derived
  from the merge, so once one exists the cost is already paid. The interface keeps the
  probe in the module owning a client to probe with, and core free of OpenSearch types.
- Bounds are carried as the strings the request sent and handed to _field_caps as-is,
  so OpenSearch's own date parser reads them and date math works. Re-interpreting them
  here risks a narrower window than the caller meant, which would drop an index that
  can match -- the divergence hazard the design flags for Approach 1.

Two additions the design leaves implicit. time_field makes the field explicit rather
than assuming @timestamp, because a Dashboards index pattern is routinely configured
on another field and would otherwise never prune. And the probe's format list accepts
a UTC wall clock alongside the OpenSearch defaults, since a client that also writes
the bound into the query text produces the spelling PPL accepts there; without it such
a bound fails to parse and pruning silently declines.

A source whose time_field is not a date excludes itself, read off the same probe
response, so a range that cannot prove an index disjoint prunes nothing.

Unusable bounds are dropped rather than rejected: they only decide which indices are
read, so failing a query over a parameter it does not need is the worse outcome.
Gated by plugins.query.pruning.enabled, which opensearch-project#5759 turns on by default.

Verified on a security-enabled cluster over eight monthly indices whose newest one
renamed a field's shape from object to keyword. Without bounds the merge sees the
object and charting by it fails; with them only the newest is resolved and the same
query returns its rows. Row counts are identical either way, a range covering every
index prunes none, and a range no index can match declines rather than pruning all.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the feat/time-range-index-pruning branch from c16b768 to c90cee5 Compare September 14, 2026 17:24
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit c90cee5

Correctness

An index that does not map the time field was pruned away with its rows. A range on an
unmapped field is *disjoint* for that index, not unknown, so _field_caps omits it
exactly as it omits an index whose values fall outside the window -- the two are
indistinguishable in the response, and the previous type check saw only the date entry
the mapping indices reported and let pruning proceed. Verified against a cluster: a
wildcard over one index mapping `ts` and one not returns only the former from the
probe. The gate now runs on its own unfiltered probe with include_unmapped, which is
the only way to see the indices a filtered probe has already hidden, and declines when
the field is unmapped anywhere, not a date anywhere, or mapped by nothing. Costs one
metadata probe, paid before the filtered one so a declining query stops early. New IT
keeps a row that lives only in an index without the field.

The gate also ran before the candidate count, so a window matching no index reported
"[ts] is not a date field" -- field-caps returns an empty field map along with an empty
index list -- and the "0 of N indices matched" line could never fire. Reordered.

analyze dropped the bounds on both phases, so `"analyze": true` merged every matched
index's mapping and reported a plan over an expression the execution would not have
used. Threaded, as explain already was.

Broken surface removed

The URL-parameter loop could not work: BaseRestHandler rejects parameters absent from
responseParams(), so start_time in a query string was a 400, and a real GET carries no
jsonContent for the loop to write into. Dropped rather than half-supported.

Tests

createRoleWithIndexAccess granted neither indices:admin/resolve/index nor
indices:data/read/field_caps*, so under security both probes were denied, pruning
declined silently, and TimeBoundsPruningSecurityIT's positive case could not pass.
Granted, matching what ppl_full_access carries since 3.9.

Both ITs pinned the pruning setting to false on teardown; since opensearch-project#5759 made it default
true, that left every later class in the cluster running with pruning off. They clear
the override instead.

Registered CalciteTimeBoundsPruningIT in CalciteNoPushdownIT, which the repo requires
and which matters here: request-level pruning is meant to be independent of pushdown.

Accuracy

Documented that these bounds are not free of effect. Pruning drops whole indices, so a
query whose text already constrains the same field to the same window returns the same
rows -- the intended use -- while one that does not returns fewer. The previous claim
that a request is "answered identically" was false, and this PR's own subsearch IT
asserts a row count changing.

Corrected the claim that a bound is read by the index's own date parser: the probe's
format list replaces the field's, so a field with some other custom format is not
pruned on. Said so, and noted that declining costs the optimization and never a row.

Stopped promising the unified query path reads these; it builds its own schema and
ignores them.

The "Request-level time bounds" heading was a section sibling, sweeping the setting's
own disable/result-set examples under it. Demoted to prose.

Renamed the leftover "hint" and "time_range" vocabulary in tests to the shipped
start_time/end_time/TimeBounds, reused OpenSearchConstants.IMPLICIT_FIELD_TIMESTAMP
instead of a second copy, and made a one-sided window warn rather than vanish.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 1380ef7

…hose indices

Reviewing this against the Dashboards side turned up two things the separate reviews
could not see.

The guard added for the unmapped-field case was applied to both pruning paths, which
regressed opensearch-project#5727's own yaml case "Prunes an index that does not map the timestamp". The
two paths are not alike. When the range is read out of the query's own pushed-down
filter, an index that does not map the field cannot satisfy that filter either, so its
documents are already excluded from the answer and dropping the index is lossless --
which is exactly what that test asserts. When the range arrives as a request parameter
the query text need not mention the field at all, so those documents are still wanted.
The guard now applies only to the bounds path; the filter path is untouched, and the
yaml suite passes again.

And rather than declining outright when the field is unmapped somewhere, the bounds
path now keeps those indices and prunes among the rest. _field_caps already names them
in the unmapped bucket of an include_unmapped probe, so this costs nothing and turns a
case that gave up into one that prunes correctly -- worth having because a Dashboards
index pattern spanning a stray index without the time field would otherwise never
prune at all.

Declining is kept only where nothing better is possible: no index maps the field, it is
mapped as a non-date somewhere, or the probe does not name the unmapped indices.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit d7b6b4c

Got integTestWithSecurity running locally for the first time on this branch, and the
suite failed two of its four cases -- not on the handoff it was written for, but because
of how it observed pruning.

It asserted that charting by a field mapped as an object in one index and a keyword in
another fails without bounds. Which side of that conflict wins the merge depends on hash
iteration order, so it varies between JVMs: the earlier manual run on a standalone
cluster returned the expected 400, this one returned 200 and the two negative cases
failed. The assertion was never sound.

Observes the resolved schema instead, as CalcitePPLTimeBounds... already does: a field
that exists only in the out-of-range index either resolves or does not, which is decided
by which indices the merge saw and nothing else. Adds a row-count parity case while here,
since that is the property that matters most and the old shape could not express it.

Confirmed the permission grant added earlier is load-bearing by taking it back out: the
positive case then fails with "nothing was thrown", pruning having declined on a denied
probe exactly as predicted. Restored, and 5/5 pass.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs ahkcs added the enhancement New feature or request label Sep 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit c792001

@codecov

codecov Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.78571% with 26 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.86%. Comparing base (6116c33) to head (468418e).
⚠️ Report is 1660 commits behind head on main.

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.00% 1 Missing and 1 partial ⚠️

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

❗ There is a different number of reports uploaded between BASE (6116c33) and HEAD (468418e). Click for more details.

HEAD has 5 uploads less than BASE
Flag BASE (6116c33) HEAD (468418e)
sql-engine 6 1
Additional details and impacted files
@@              Coverage Diff              @@
##               main    #5766       +/-   ##
=============================================
- Coverage     98.40%   62.86%   -35.54%     
- Complexity     2746     8814     +6068     
=============================================
  Files           266      938      +672     
  Lines          6758    40205    +33447     
  Branches        426     4528     +4102     
=============================================
+ Hits           6650    25275    +18625     
- Misses          107    14125    +14018     
- Partials          1      805      +804     
Flag Coverage Δ
sql-engine 62.86% <76.78%> (-35.54%) ⬇️

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.

Three time ranges can reach one query and they are not alternatives: a
where clause and earliest=/latest= both filter rows and combine, while
start_time/end_time only select indices. Spell out the consequence -- a
query whose own range is wider than the bounds loses rows, because the
indices outside the bounds are never read.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 5f74855

A client cannot assume plugins.query.pruning.enabled is there to read: a
cluster older than 3.9 does not have the setting at all, and a newer one
may have it off. A pruning boolean in the request body now decides for
that request, deferring to the cluster setting when omitted.

It rides jsonContent, which already crosses the transport, so there is no
StreamOutput change and no version gate -- unlike partial_result, which
carries its own wire field. Both pruning paths honour it: the bounds path
in OpenSearchStorageEngine and the pushed-down-filter path in
OpenSearchRequestBuilder.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 3f22a42

TimeBounds and the AstBuilder field still said the bounds apply to every
source; they narrow the outermost one. Also split the run-on paragraph in
endpoint.rst, make the priorities table's cross-reference concrete, and
cut isMainSource's javadoc to the part a reader cannot infer.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 975c7ef

Also drop the Calcite-only line: since the bounds decode in
OpenSearchStorageEngine.getTable, which both engines resolve tables
through, pruning applies on the V2 path too (verified live).

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit e805474

"Send them only alongside an equivalent filter" reads as though the
bounds need one to take effect. They do not: they prune regardless, and
the filter is what keeps the answer the same.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 705d0e8

/** Lookup command */
@Override
public UnresolvedPlan visitLookupCommand(OpenSearchPPLParser.LookupCommandContext ctx) {
// Not narrowed: a lookup index is a dimension table, not one of the searched sources.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove AI comments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

Comment thread docs/user/admin/settings.rst Outdated
"time_field" : "event_time",
"start_time" : "2026-09-07 00:00:00.000",
"end_time" : "2026-09-14 00:00:00.000",
"pruning" : true

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why need pruning override on query level? plugins.query.pruning.enabled is feature flag.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My previous assumption is that customer can't change cluster setting, but it turns out that they can use _plugins/_query/settings, so a query-level override was solving a problem that doesn't exist. Reverted in full: the request field, the plan/CalcitePlanContext carrier, the shared gate, the two ITs and the doc lines. plugins.query.pruning.enabled decides

The setting is a feature flag and a customer can already change it through
_plugins/_query/settings, so a query-level override adds an API for a
problem that does not exist. Back to: plugins.query.pruning.enabled
decides, full stop.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 97ad23a

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 468418e

@ahkcs
ahkcs requested a review from penghuo September 16, 2026 20:54
@ahkcs
ahkcs merged commit f40bfdd into opensearch-project:main Sep 16, 2026
41 of 43 checks passed
mengweieric added a commit that referenced this pull request Sep 18, 2026
…route and the security plugin (#5785)

CalciteTimeBoundsPruningIT and TimeBoundsPruningSecurityIT (added in #5766) carried no gates, so integTestRemote failed them on clusters the tests were never meant for: the analytics-engine route does not observe the request-level pruning, and the security IT drives the security REST API, which does not exist without the plugin.

Add the TIME_BOUNDS_PRUNING capability and annotate both classes with @RequiresCapability so they skip on the analytics-engine route, and assume the security plugin in TimeBoundsPruningSecurityIT.init() exactly like the sibling security ITs. Verified against four remote clusters: OpenSearch + security passes both classes (15/15), OpenSearch without security passes the Calcite class and skips the security one, and both analytics-engine clusters skip both classes.

Signed-off-by: menwe <[email protected]>
ahkcs added a commit that referenced this pull request Oct 12, 2026
…schema is resolved (#5766, #5852) (#5863)

* Prune indices by request-level time bounds before the schema is resolved (#5766)

(cherry picked from commit f40bfdd)
Signed-off-by: Kai Huang <[email protected]>

* Fix comma-separated sources with request-level time bounds (#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]>

---------

Signed-off-by: Kai Huang <[email protected]>
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.

2 participants