Skip to content

Narrow every aggregate over a scan to one shared subset for partial results - #5777

Closed
ahkcs wants to merge 2 commits into
opensearch-project:mainfrom
ahkcs:feat/chart-skip-partial-result
Closed

ahkcs wants to merge 2 commits into
opensearch-project:mainfrom
ahkcs:feat/chart-skip-partial-result

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Revised again from the gate version of this PR. Instead of skipping partial-result mode when a plan groups a scan more than once, we now narrow those aggregations to one shared index subset, so chart/timechart keep the speedup and stay correct. (History: v1 gated chart/timechart by name; v2 gated any plan grouping a scan twice; this is v3.)

Partial-result mode (#5657) narrows an aggregation to the index subset where its group fields are aggregatable. It decided per aggregation, so a plan grouping one scan more than once could pick two different subsets — one response built from different sets of documents, with two warnings whose text differed so drainWarnings().distinct() couldn't collapse them.

env is bare text in index C, svc is bare text in index B, both aggregatable in A:

chart count() over ts by env          (partial_result on, BEFORE)
        |
        +-- data rows      group by [ts, env] --> narrowed to {A, B}   <- counts from here
        +-- top-N ranking  group by [env]     --> narrowed to {A, C}   <- labels from here
                                                    ^
                             one response, two different document sets

appendcol was the worst: it zips the two aggregations into one row, so [5, "bx", "ay"] paired a count from {A,B} with a label ranked over {A,C} — a row describing documents that don't exist.

Fix

Narrow every aggregate over a scan to one shared subset: the indices aggregatable for the union of all their group fields.

chart count() over ts by env          (partial_result on, AFTER)
        |
   union of group fields = {env, ts}
        |
   plan({env, ts}) --> keep the indices where BOTH are aggregatable --> {A, C}
        |
   every aggregate over this scan narrows to {A, C}
        |
   one population, one warning

Because the subset is the union, chart (env + ts) drops only the index where env is bad; appendcol by env / by svc drops any index where either is bad. Every aggregation over the scan sees the same indices, so the response can't mix populations.

At a glance, one query end to end:

PPL query
   |
   v  (1) COMPILE  -- whole plan in hand, once
   ScanAggregates.analyze:  per scan, the union of fields its aggregates need
                            e.g. partial_demo_*  ->  {env, svc}
   |
   v  (2) PUSHDOWN -- per scan, picks indices
   keep only indices clean for the WHOLE union  ->  {A}
   point every aggregate over this scan at {A}
   |
   v  (3) RUN
   search hits only {A}  ->  one population, one warning

Two steps because (1) must see the whole plan (only place all aggregates are visible) but lives in core, which cannot read index mappings; (2) lives in opensearch, which can. The thread-local carries the field list between them.

Split across the module boundary:

core       ScanAggregates.analyze(plan)
             walk the plan; per scan, resolve each grouped aggregate's group keys
             to field names via RelMetadataQuery.getColumnOrigins (survives
             projects, filters, casts); union them
opensearch tryPartialResultAggregate
             look up the scan's union, call PartialResultAggregatePushdown.plan(union)
             once, narrow every aggregate to its keptIndices
bridge     CalcitePlanContext carries the per-scan field sets on ThreadLocalSnapshot

How every case resolves:

case behavior
single aggregation (plain stats, chart limit=0) analyze returns EMPTY; per-aggregate pushdown, unchanged from #5657
multi-agg, all keys traceable, a clean union subset exists (chart, timechart, append/appendcol, multisearch, join / subquery over aggregating subsearches) narrow every aggregate to that one subset → one population, one warning
multi-agg, union has no clean index anywhere plan() → null → complete result over all indices, no warning — never empty
multi-agg, union fields aggregatable everywhere (no real conflict) plan() → null (nothing excluded) → normal pushdown, no warning
multi-agg, a group key with no traceable origin scan barred → complete result (fail-closed)
clean indices disagree on aggregatable type (keyword vs integer, two numerics) plan() → null → complete result, deferred to #5610
any exception in the analysis bar-all → whole query complete (fail-closed)
warnings-unsupported format (CSV / RAW / VIZ) analysis skipped and pushdown returns null → no silent index dropping
partial_result disabled pushdown returns null → normal / complete
two different index patterns each aggregated keyed by distinct qualified names → each narrows independently → N legitimate warnings (distinct sources, not one mixed scan)

The walk runs once per compile, in OpenSearchRelRunners.run just before prepareStatement, and is skipped entirely for response formats with no warnings channel. Since #5646 a text/keyword conflict pushes down as a _source script rather than failing, so every "complete" fallback above is correct — just slower.

Two fixes fall out:

  • The warning sorts its group fields, so equivalent plan alternatives that differ only in key order ([env, ts] vs [ts, env]) render alike and de-duplicate.
  • buildResultSet drains warnings before the timewrap pivot, whose finally clears the lifecycle signals. A narrowed timechart | timewrap would otherwise lose its PARTIAL_RESULT warning — silent partial data, exactly what the channel exists to prevent. (Latent before this PR; reachable now that timechart narrows.)

Behaviour

Fixture: env bare text in one index, svc bare text in another, both aggregatable in a third. partial_result on. All rows verified coherent on a live cluster.

query gate (v2) this PR (v3)
chart count() over ts by env complete, 0 banners (slow) partial over {A,C}, 1 banner (fast)
timechart span=1h count() by env complete, 0 banners partial, 1 banner
... | append [ ... by svc ] complete, 0 banners both halves from one subset, 1 banner
... | appendcol [ ... by svc ] complete, 0 banners coherent row, 1 banner (was [5,bx,ay] lie)
multisearch [by env] [by svc] complete, 0 banners 1 banner
join / in-subquery / chart-in-subsearch complete, 0 banners 1 banner
union has no clean index complete complete (no empty)
stats count() by env 1 banner 1 banner (unchanged)
chained stats | stats, addcoltotals, streamstats 1 banner 1 banner (unchanged)

The substantive change vs. main: those queries no longer mix populations or emit duplicate banners; and vs. the gate: chart/timechart get the partial-result speedup back.

Testing

  • CalcitePartialResultOnMappingConflictIT — 31/31 on a live cluster. The multi-aggregation cases assert exactly one warning and that no value living only in an excluded index appears (proof of one coherent population); a concurrency test fires 12 interleaved chart/svc-stats queries and asserts each sees its own subset.
  • ScanAggregatesTest, CalcitePPLScanAggregateShapeTest — the structural walk (DAG identity-dedup, ungrouped/no-scan aggregates don't count, fail-closed).
  • PartialResultAggregatePushdownTest — warning text is independent of group-key order.
  • PartialResultGateTest — the per-query info is derived per compile and doesn't leak across pooled-thread queries.
  • Full core / opensearch / ppl unit suites, CalciteChartCommandIT, CalciteTimechartCommandIT — green.

Related Issues

Follows up #5657.

Check List

  • 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.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@github-actions

github-actions Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 1a37aa3)

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 nodesOf method uses an IdentityHashMap to track visited nodes but does not handle cycles that might exist in the plan graph. If a cycle exists (e.g., through a subquery or join that references itself), the method could loop indefinitely or produce incorrect results. While the code does check visited.add(node) before continuing, a malformed plan with a cycle could still cause issues if the cycle is not properly detected.

private static List<RelNode> nodesOf(RelNode root) {
  Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
  List<RelNode> collected = new ArrayList<>();
  Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
  while (!pending.isEmpty()) {
    RelNode node = pending.pop();
    if (!visited.add(node)) {
      continue;
    }
    collected.add(node);
    pending.addAll(node.getInputs());
    collectSubQueryPlans(node, pending); // a subquery becomes a join, so its scan takes pushdown
  }
  return collected;
}
Possible Issue

The groupFieldOrigins method returns null when any group key has no traceable column origin, but it does not distinguish between a legitimate null (no origin) and an error condition. If mq.getColumnOrigins(input, group) returns null due to an internal error rather than a missing origin, the method treats it as unresolvable and bars partial results for that scan. This could cause correct queries to fall back to complete mode unnecessarily when metadata queries fail transiently.

private static Map<String, Set<String>> groupFieldOrigins(
    Aggregate aggregate, RelMetadataQuery mq) {
  Map<String, Set<String>> byTable = new HashMap<>();
  RelNode input = aggregate.getInput();
  for (int group : aggregate.getGroupSet()) {
    Set<RelColumnOrigin> origins = mq.getColumnOrigins(input, group);
    if (origins == null || origins.isEmpty()) {
      return null;
    }
    for (RelColumnOrigin origin : origins) {
      RelOptTable table = origin.getOriginTable();
      if (table == null) {
        return null;
      }
      String field = table.getRowType().getFieldNames().get(origin.getOriginColumnOrdinal());
      byTable.computeIfAbsent(qualifiedName(table), k -> new LinkedHashSet<>()).add(field);
    }
  }
  return byTable;
}
Possible Issue

The warnings are drained before the timewrap block's finally clears the lifecycle signals. If an exception occurs during the timewrap pivot processing (lines 479-487), the warnings are already drained but the response may not be returned, causing those warnings to be lost. The finally block at line 490 will clear the signals, but the drained warnings won't be attached to any response if the exception propagates.

List<Warning> warnings = CalcitePlanContext.drainWarnings();
// Timewrap post-processing: pivot unpivoted rows into period columns. The pivot is shared with
// the analytics route (AnalyticsExecutionEngine) so both engines produce identical output.
if (TimewrapPivot.isTimewrap()) {
  try {
    TimewrapPivot.Result pivoted =
        TimewrapPivot.pivot(
            columns,
            values,
            CalcitePlanContext.timewrapUnitName.get(),
            CalcitePlanContext.timewrapSeries.get());
    columns = pivoted.columns();
    values = pivoted.values();
  } finally {
    CalcitePlanContext.clearTimewrapSignals();
  }
}

Schema schema = new Schema(columns);
QueryResponse response = new QueryResponse(schema, values, null);
response.setWarnings(warnings);
return response;

ahkcs added a commit to ahkcs/sql that referenced this pull request Sep 15, 2026
Split out to opensearch-project#5777; it is independent of request-level time bounds.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs ahkcs added bugFix enhancement New feature or request labels Sep 15, 2026
@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 38.23529% with 84 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.17%. Comparing base (c75d3bb) to head (1a37aa3).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
...g/opensearch/sql/calcite/utils/ScanAggregates.java 38.77% 59 Missing and 1 partial ⚠️
.../opensearch/sql/calcite/CalciteRelNodeVisitor.java 0.00% 9 Missing ⚠️
...ensearch/storage/scan/CalciteLogicalIndexScan.java 0.00% 7 Missing ⚠️
...org/opensearch/sql/calcite/CalcitePlanContext.java 54.54% 5 Missing ⚠️
...opensearch/executor/OpenSearchExecutionEngine.java 0.00% 2 Missing ⚠️
...ensearch/sql/calcite/utils/CalciteToolsHelper.java 80.00% 1 Missing ⚠️

❌ Your project check has failed because the head coverage (63.17%) 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              @@
##               main    #5777      +/-   ##
============================================
+ Coverage     62.84%   63.17%   +0.32%     
- Complexity     8777     8839      +62     
============================================
  Files           937      939       +2     
  Lines         40118    40349     +231     
  Branches       4516     4556      +40     
============================================
+ Hits          25212    25489     +277     
+ Misses        14106    14035      -71     
- Partials        800      825      +25     
Flag Coverage Δ
sql-engine 63.17% <38.23%> (+0.32%) ⬆️

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 force-pushed the feat/chart-skip-partial-result branch from 4cf8d1e to 99e88a5 Compare September 16, 2026 19:00
@ahkcs ahkcs changed the title Skip partial-result mode for chart and timechart Skip partial-result mode when a plan aggregates a scan more than once Sep 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 99e88a5

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 99e88a5 to 12bd4cc Compare September 16, 2026 19:28
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 12bd4cc

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 1a37aa3

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Add depth limit for plan traversal

The nodesOf method performs a depth-first traversal without any depth limit or cycle
detection beyond identity checking. For deeply nested or pathological plans, this
could lead to excessive memory consumption or stack issues. Consider adding a depth
limit or size limit to prevent resource exhaustion on malformed or adversarial query
plans.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [186-200]

+private static final int MAX_PLAN_DEPTH = 10_000;
+
 private static List<RelNode> nodesOf(RelNode root) {
   Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
   List<RelNode> collected = new ArrayList<>();
   Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
-  while (!pending.isEmpty()) {
+  while (!pending.isEmpty() && collected.size() < MAX_PLAN_DEPTH) {
     RelNode node = pending.pop();
     if (!visited.add(node)) {
       continue;
     }
     collected.add(node);
     pending.addAll(node.getInputs());
     collectSubQueryPlans(node, pending);
   }
+  if (collected.size() >= MAX_PLAN_DEPTH) {
+    throw new IllegalStateException("Plan depth exceeds maximum limit");
+  }
   return collected;
 }
Suggestion importance[1-10]: 5

__

Why: Adding a depth limit is a reasonable defensive measure against pathological plans, though the test at line 65-74 already demonstrates the method handles 20,000 nodes without issues. The suggestion provides protection against resource exhaustion but may be overly conservative given existing validation.

Low
Avoid overly broad exception handling

The analyze method catches all exceptions and returns BAR_ALL, which disables
partial results for the entire query. This broad exception handling may mask
critical errors that should be propagated. Consider catching only specific expected
exceptions (e.g., metadata query failures) and letting unexpected errors propagate
to surface actual bugs during development and testing.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [70-119]

 public static MultiAggregateInfo analyze(RelNode plan) {
   if (!moreThanOneGroupedOverAScan(plan)) {
     return MultiAggregateInfo.EMPTY;
   }
   try {
     RelMetadataQuery mq = plan.getCluster().getMetadataQuery();
     ...
-  } catch (Exception e) {
-    LOG.debug("Cannot analyze scan aggregates, barring partial results for the query", e);
+  } catch (RuntimeException e) {
+    LOG.warn("Failed to analyze scan aggregates, barring partial results for the query", e);
     return MultiAggregateInfo.BAR_ALL;
   }
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion to narrow exception handling from Exception to RuntimeException is reasonable for better error visibility, but the impact is limited since the method already logs the error and fails closed safely. The change from LOG.debug to LOG.warn is a minor improvement in observability.

Low
Possible issue
Add null check for thread-local value

The code retrieves multiAggregate from thread-local context and uses it to determine
partition fields. If multiAggregate is null (which shouldn't happen but isn't
explicitly guarded), calling barred() or unionFieldsFor() would throw a
NullPointerException. Add a null check to ensure robustness, especially since this
code runs during pushdown on a different thread pool.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteLogicalIndexScan.java [531-537]

 var multiAggregate = CalcitePlanContext.getMultiAggregateInfo();
+if (multiAggregate == null) {
+  return null;
+}
 String qualifiedName = String.join(".", table.getQualifiedName());
 if (multiAggregate.barred(qualifiedName)) {
   return null;
 }
 List<String> sharedFields = multiAggregate.unionFieldsFor(qualifiedName);
 List<String> fieldsToPartitionBy = sharedFields != null ? sharedFields : partitionFields;
Suggestion importance[1-10]: 3

__

Why: While defensive null checking is generally good practice, the thread-local multiAggregateInfo is initialized with ThreadLocal.withInitial(() -> ScanAggregates.MultiAggregateInfo.EMPTY) at line 96-97, guaranteeing it never returns null. The suggestion addresses a non-existent issue, though the defensive check has minimal cost.

Low

Previous suggestions

Suggestions up to commit a5b5a15
CategorySuggestion                                                                                                                                    Impact
General
Improve exception handling visibility

The catch block swallows all exceptions and returns BAR_ALL, which silently disables
partial results for the entire query. This could mask critical errors during plan
analysis. Consider logging at a higher level (WARN or ERROR) and potentially
re-throwing exceptions that indicate serious system issues rather than expected
analysis failures.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [70-118]

 public static MultiAggregateInfo analyze(RelNode plan) {
   if (!moreThanOneGroupedOverAScan(plan)) {
     return MultiAggregateInfo.EMPTY;
   }
   try {
     RelMetadataQuery mq = plan.getCluster().getMetadataQuery();
     ...
   } catch (Exception e) {
-    LOG.debug("Cannot analyze scan aggregates, barring partial results for the query", e);
+    LOG.warn("Cannot analyze scan aggregates, barring partial results for the query", e);
     return MultiAggregateInfo.BAR_ALL;
   }
 }
Suggestion importance[1-10]: 5

__

Why: Changing the log level from DEBUG to WARN would improve visibility of analysis failures, but the current DEBUG level is appropriate for a fallback mechanism that gracefully degrades to complete results. The suggestion is valid but has moderate impact.

Low
Prevent potential stack overflow

The iterative traversal using a Deque could cause stack overflow for extremely deep
plans despite being iterative, because collectSubQueryPlans recursively calls
RexShuttle.visitSubQuery. For plans with deeply nested subqueries, this could still
exhaust the stack. Consider adding a depth limit or converting the subquery
collection to an iterative approach as well.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [186-200]

+private static final int MAX_PLAN_DEPTH = 10000;
+
 private static List<RelNode> nodesOf(RelNode root) {
   Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
   List<RelNode> collected = new ArrayList<>();
   Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
-  while (!pending.isEmpty()) {
+  int depth = 0;
+  while (!pending.isEmpty() && depth++ < MAX_PLAN_DEPTH) {
     RelNode node = pending.pop();
     if (!visited.add(node)) {
       continue;
     }
     collected.add(node);
     pending.addAll(node.getInputs());
     collectSubQueryPlans(node, pending);
   }
   return collected;
 }
Suggestion importance[1-10]: 3

__

Why: The concern about stack overflow is overstated. The iterative traversal already prevents stack overflow for the main plan traversal. The collectSubQueryPlans uses RexShuttle which is shallow, and the test at line 66-74 demonstrates handling of 20,000-deep plans without issues. Adding a depth limit could be useful but is not critical.

Low
Suggestions up to commit 672abde
CategorySuggestion                                                                                                                                    Impact
General
Increase exception logging severity

The analyze method catches all exceptions and returns BAR_ALL, which disables
partial results for the entire query. This fail-closed approach may hide legitimate
errors during development. Consider logging at WARN level instead of DEBUG, or
re-throwing specific critical exceptions after logging, to ensure important failures
are visible.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [124-127]

 public static MultiAggregateInfo analyze(RelNode plan) {
   // Most queries group a scan at most once; skip the column-origin resolution for them.
   if (!moreThanOneGroupedOverAScan(plan)) {
     return MultiAggregateInfo.EMPTY;
   }
   try {
     RelMetadataQuery mq = plan.getCluster().getMetadataQuery();
     ...
   } catch (Exception e) {
-    LOG.debug("Cannot analyze scan aggregates, barring partial results for the query", e);
+    LOG.warn("Cannot analyze scan aggregates, barring partial results for the query", e);
     return MultiAggregateInfo.BAR_ALL;
   }
 }
Suggestion importance[1-10]: 5

__

Why: Changing from DEBUG to WARN level would make failures more visible during development, but the fail-closed behavior is intentional and the current logging level may be appropriate for production. The suggestion has moderate value for debugging.

Low
Add depth limit protection

The nodesOf method uses iterative traversal with a deque to avoid stack overflow on
deep plans. However, collectSubQueryPlans recursively calls node.accept(new
RexShuttle()), which may still cause stack overflow if a node contains deeply nested
subqueries. Consider adding depth tracking or iterative handling for subquery
traversal as well.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [200-214]

 private static List<RelNode> nodesOf(RelNode root) {
   Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
   List<RelNode> collected = new ArrayList<>();
   Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
-  while (!pending.isEmpty()) {
+  int maxDepth = 10000; // reasonable limit
+  int depth = 0;
+  while (!pending.isEmpty() && depth++ < maxDepth) {
     RelNode node = pending.pop();
     if (!visited.add(node)) {
       continue;
     }
     collected.add(node);
     pending.addAll(node.getInputs());
-    // A subquery becomes a join later, so its scan takes pushdown too.
     collectSubQueryPlans(node, pending);
+  }
+  if (depth >= maxDepth) {
+    throw new IllegalStateException("Plan depth exceeds maximum allowed");
   }
   return collected;
 }
Suggestion importance[1-10]: 3

__

Why: The iterative traversal already prevents stack overflow for the main plan structure. While collectSubQueryPlans uses recursion, subqueries are typically shallow. The suggested depth limit adds complexity without addressing a demonstrated problem, and the test at line 66-74 shows the code handles 20k-deep plans correctly.

Low
Add null check for safety

The code retrieves multiAggregate and then checks if it's barred, but doesn't verify
that multiAggregate itself is non-null before calling methods on it. While
getMultiAggregateInfo() appears to return a default value, explicitly checking for
null would make the code more defensive and prevent potential NPE if the
implementation changes.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/CalciteLogicalIndexScan.java [531-537]

 var multiAggregate = CalcitePlanContext.getMultiAggregateInfo();
+if (multiAggregate == null) {
+  return null;
+}
 String qualifiedName = String.join(".", table.getQualifiedName());
 if (multiAggregate.barred(qualifiedName)) {
   return null;
 }
 List<String> sharedFields = multiAggregate.unionFieldsFor(qualifiedName);
 List<String> fieldsToPartitionBy = sharedFields != null ? sharedFields : partitionFields;
Suggestion importance[1-10]: 2

__

Why: The getMultiAggregateInfo() method returns a non-null default value (MultiAggregateInfo.EMPTY as shown in line 100), so the null check is unnecessary. Adding it would reduce code clarity without providing actual safety benefits.

Low
Suggestions up to commit 03cf048
CategorySuggestion                                                                                                                                    Impact
General
Add traversal depth limit

The nodesOf method performs unbounded graph traversal without depth or node count
limits. For deeply nested or cyclic query plans, this could lead to excessive memory
consumption or stack overflow. Add a safety limit on the number of nodes collected
to prevent resource exhaustion on malformed or adversarial query plans.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [219-234]

+private static final int MAX_NODES = 10_000;
+
 private static List<RelNode> nodesOf(RelNode root) {
   Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
   List<RelNode> collected = new ArrayList<>();
   Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
   while (!pending.isEmpty()) {
     RelNode node = pending.pop();
     if (!visited.add(node)) {
       continue;
     }
+    if (collected.size() >= MAX_NODES) {
+      throw new IllegalStateException("Query plan exceeds maximum node limit");
+    }
     collected.add(node);
     pending.addAll(node.getInputs());
-    // A subquery becomes a join later, so its scan takes pushdown too.
     collectSubQueryPlans(node, pending);
   }
   return collected;
 }
Suggestion importance[1-10]: 5

__

Why: Adding a node limit provides protection against resource exhaustion from malformed plans. However, the test at line 66-74 already validates handling of 20,000-node deep plans without overflow, and the method uses iterative traversal (not recursive) which prevents stack overflow. The suggestion adds defensive programming but addresses a relatively low-probability scenario.

Low
Narrow exception handling scope

The analyze method catches all exceptions and returns BAR_ALL, which disables
partial results for the entire query. This overly broad exception handling could
mask critical bugs during development and make debugging difficult. Consider
catching only specific expected exceptions (e.g., metadata query failures) and
letting unexpected exceptions propagate to surface actual bugs.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [90-141]

 public static MultiAggregateInfo analyze(RelNode plan) {
   // Most queries group a scan at most once; skip the column-origin resolution for them.
   if (!moreThanOneGroupedOverAScan(plan)) {
     return MultiAggregateInfo.EMPTY;
   }
   try {
     RelMetadataQuery mq = plan.getCluster().getMetadataQuery();
     ...
-  } catch (Exception e) {
+  } catch (RuntimeException e) {
     LOG.debug("Cannot analyze scan aggregates, barring partial results for the query", e);
     return MultiAggregateInfo.BAR_ALL;
   }
 }
Suggestion importance[1-10]: 3

__

Why: While narrowing from Exception to RuntimeException is technically more specific, the method is designed to fail-safe by returning BAR_ALL on any analysis failure. The broad catch is intentional to ensure partial results are disabled rather than causing query failures. The suggestion provides minimal practical benefit.

Low
Suggestions up to commit 0953d84
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use remove() for ThreadLocal cleanup

In clearTimewrapSignals(), use multipleScanAggregates.remove() instead of set(false)
to properly clean up the ThreadLocal and prevent memory leaks in thread pools where
threads are reused.

core/src/main/java/org/opensearch/sql/calcite/CalcitePlanContext.java [293]

-multipleScanAggregates.set(false);
+multipleScanAggregates.remove();
Suggestion importance[1-10]: 5

__

Why: Valid suggestion for consistency. While set(false) works with withInitial(), using remove() is more idiomatic and consistent with how partialResultOverride is cleaned up at line 292.

Low
Prevent ThreadLocal memory leak

The multipleScanAggregates ThreadLocal should be cleared in clearTimewrapSignals()
using remove() instead of set(false) to prevent memory leaks in thread pools.
ThreadLocals that are only set to false can accumulate in pooled threads.

core/src/main/java/org/opensearch/sql/calcite/CalcitePlanContext.java [100-101]

-private static final ThreadLocal<Boolean> multipleScanAggregates =
-    ThreadLocal.withInitial(() -> false);
+private static final ThreadLocal<Boolean> multipleScanAggregates = new ThreadLocal<>();
Suggestion importance[1-10]: 3

__

Why: The suggestion to avoid withInitial(() -> false) is partially valid, but the actual memory leak concern is addressed by the remove() call in clearTimewrapSignals() at line 293. The withInitial() pattern itself doesn't cause leaks when properly cleaned up.

Low
Suggestions up to commit 04f8c59
CategorySuggestion                                                                                                                                    Impact
General
Narrow exception catch scope

The method catches all exceptions and returns true (barring partial results) as a
fail-safe. However, catching Exception is too broad and may hide unexpected errors.
Consider catching only specific exceptions that are expected during plan traversal,
such as RuntimeException or custom exceptions, to avoid masking critical bugs.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [45-61]

 public static boolean moreThanOneGroupedOverAScan(RelNode plan) {
   try {
     int grouped = 0;
     for (RelNode node : nodesOf(plan)) {
       if (node instanceof Aggregate aggregate
           && !aggregate.getGroupSet().isEmpty()
           && canReachAScan(aggregate)
           && ++grouped > 1) {
         return true;
       }
     }
     return false;
-  } catch (Exception e) {
+  } catch (RuntimeException e) {
     LOG.debug("Cannot count scan aggregates, barring partial results", e);
     return true;
   }
 }
Suggestion importance[1-10]: 4

__

Why: While catching Exception is broad, the fail-safe behavior (returning true to bar partial results) is intentional for safety. Narrowing to RuntimeException provides marginal improvement but doesn't significantly impact correctness since the method already logs and handles failures appropriately.

Low
Clarify deque traversal order

The method uses pending.pop() which retrieves from the head of the deque, but
pending.addAll() adds to the tail. This creates depth-first traversal behavior. For
deeply nested plans (20k+ levels as tested), this could cause stack-like growth in
the deque. Consider using pollFirst() and addFirst() for explicit depth-first, or
pollLast() with addAll() for breadth-first to better control memory usage.

core/src/main/java/org/opensearch/sql/calcite/utils/ScanAggregates.java [78-93]

 private static List<RelNode> nodesOf(RelNode root) {
   Set<RelNode> visited = Collections.newSetFromMap(new IdentityHashMap<>());
   List<RelNode> collected = new ArrayList<>();
   Deque<RelNode> pending = new ArrayDeque<>(List.of(root));
   while (!pending.isEmpty()) {
-    RelNode node = pending.pop();
+    RelNode node = pending.pollFirst();
     if (!visited.add(node)) {
       continue;
     }
     collected.add(node);
     pending.addAll(node.getInputs());
     collectSubQueryPlans(node, pending);
   }
   return collected;
 }
Suggestion importance[1-10]: 2

__

Why: The suggestion misunderstands the code: pop() and pollFirst() are equivalent for ArrayDeque. The current implementation already handles deep plans correctly (as proven by the 20k-level test), so this change offers no functional benefit and only adds verbosity.

Low

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 12bd4cc to 0b57419 Compare September 16, 2026 21:05
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 0b57419

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 0b57419 to 04f8c59 Compare September 17, 2026 17:29
@ahkcs ahkcs changed the title Skip partial-result mode when a plan aggregates a scan more than once Skip partial-result mode when a plan groups a scan more than once Sep 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 04f8c59

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 04f8c59 to 0953d84 Compare September 17, 2026 18:33
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 0953d84

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 0953d84 to 03cf048 Compare September 18, 2026 22:41
@ahkcs ahkcs changed the title Skip partial-result mode when a plan groups a scan more than once Narrow every aggregate over a scan to one shared subset for partial results Sep 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 03cf048

@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 03cf048 to 672abde Compare September 21, 2026 04:39
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 672abde

…esults

Partial-result mode (opensearch-project#5657) narrows an aggregation to the index subset
where its group fields are aggregatable. It decided per aggregation, so a
plan grouping one scan more than once could pick two different subsets:
the one response was then built from different sets of documents, and the
two warnings differed in text so they could not be collapsed.

chart and timechart are this shape by construction -- the charted rows
plus a pass ranking the top-N columns -- as are append, appendcol,
multisearch, join and subqueries over aggregating subsearches. appendcol
was the worst: it zips the two aggregations into one row, so a count from
one subset sat beside a label ranked over another, and the row looked
fine.

Rather than skip partial mode for those queries, narrow every aggregate
over a scan to a single shared subset: the indices aggregatable for the
union of all their group fields. ScanAggregates resolves that union once
per scan at compile time, via column origins so it survives projects and
casts, and pushdown narrows every aggregate to it. Because the subset is
shared, the response is drawn from one population and carries one warning.
chart and timechart now get the partial-result speedup too, instead of
always paying the full scan.

When no index is aggregatable for the whole union, plan() returns null and
the complete result is returned -- never an empty one. A group key with no
traceable origin, or any failure in the analysis, bars partial mode for
the scan, so the fallback is always the complete result.

The union is resolved in core (Calcite only) and the mapping-aware subset
in the opensearch module, bridged by CalcitePlanContext, which carries the
per-scan field sets on its ThreadLocalSnapshot so they survive the
transport->worker handoff.

Two fixes fall out. The warning sorts its group fields, so equivalent plan
alternatives that differ only in key order render alike and de-duplicate.
And buildResultSet drains warnings before the timewrap pivot, whose
finally clears the lifecycle signals -- otherwise a narrowed timechart
followed by timewrap would lose its PARTIAL_RESULT warning.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the feat/chart-skip-partial-result branch from 672abde to a5b5a15 Compare September 21, 2026 18:59
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit a5b5a15

The dashboards search path attaches a request-body highlight to every
query. On an aggregating query that highlight adds a synthetic _highlight
column (type ANY) to the scan, which defeats
RelMetadataQuery.getColumnOrigins for the group keys. ScanAggregates.analyze
can then no longer trace any group key, fails closed, and bars every
multi-aggregate plan (chart, timechart, appendcol) from partial-result
narrowing -- so the query silently returns the complete result over all
indices with no PARTIAL_RESULT warning (no banner), while single-aggregate
queries keep warning. Aggregate pushdown itself is unaffected; the engine
already drops the highlight on the size:0 request.

A highlight is meaningless once rows collapse into aggregate buckets, so
drop it when the plan aggregates. Origin tracing then succeeds, the shared
index subset is computed, and the warning is emitted as before -- for every
client, not just the dashboards. This also stops sending a redundant
highlight the engine was discarding anyway.

Adds chart- and timechart-with-highlight regression tests to
CalcitePartialResultOnMappingConflictIT.

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

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 1a37aa3

@ahkcs

ahkcs commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

closing this PR as the partial_result feature will be kept as experimental

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

Labels

bugFix enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant