Skip to content

Restore SUM(narrow_int + literal) aggregation pushdown - #5827

Merged
ahkcs merged 3 commits into
opensearch-project:mainfrom
ahkcs:fix/5823-agg-convert-widening-cast
Oct 13, 2026
Merged

ahkcs merged 3 commits into
opensearch-project:mainfrom
ahkcs:fix/5823-agg-convert-widening-cast

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

stats sum(<narrow-int field> + <literal>) lost its aggregation pushdown in 3.8. #5603 widens narrow-integer arithmetic operands, so the aggregate argument became +(CAST($x):BIGINT, k). PPLAggregateConvertRule only matched a bare INPUT_REF, so the SUM(x + k) → SUM(x) + k * COUNT(x) rewrite stopped firing. Queries then ran as a full _source scan with coordinator-side EnumerableAggregate (ClickBench q30: 90 such sums, sub-second → timeout).

Fix (PPLAggregateConvertRule)

  • The field operand may now be a bare input ref or a lossless integer widening CAST of one (TINYINT ≤ SMALLINT ≤ INTEGER ≤ BIGINT). Narrowing and non-integer casts are still rejected.
  • The cast is dropped in the rewrite. This is type-safe because CHECKED_LONG_SUM always returns BIGINT, so a cast is only unwrapped when the agg is CHECKED_LONG_SUM. Dropping it also lets every rewritten _SUM dedup with the plain sum(x), so q30 collapses back to two metric aggregations.

q30 plan, before → after

main (3.8+) this PR (same as 3.7)
Pushdown PROJECT->[ResolutionWidth] only AGGREGATION + LIMIT
Request _source scan, no size "size":0, sum + value_count
Coordinator EnumerableAggregate with 90 CHECKED_LONG_SUMs EnumerableCalc only

Test gaps fixed

  • PPLAggregateConvertRuleTest only covered a BIGINT input ref, which is never widened. It now covers a SMALLINT field widened to BIGINT (including dedup with a plain sum(a)) and a narrowing cast that must not match.
  • CalciteExplainIT's only sum-enhancement test (testExplainOnAggregationWithSumEnhancement) uses balance (long), which Widen narrow integer operands in PPL +/-/* to prevent overflow #5603 doesn't widen, so it never saw the cast. Added testExplainOnAggregationWithSumEnhancementOnNarrowInt on age (integer), with pushdown and no-pushdown fixtures. It fails on main in both modes.
  • CalcitePPLClickBenchIT never compared q30's plan. ignored() skips q30 when GCedMemoryUsage.initialized() is false, and that static is never initialized in the test JVM, so q30 was always skipped, explain assertion included. That is how the regressed q30.yaml went unnoticed. The IT now checks the plan for every query and skips only execution for ignored ones. q30.yaml is regenerated.

Verified: :core:test, :ppl:test, :opensearch:test, CalcitePPLClickBenchIT and CalciteExplainIT all pass. The ClickBench IT change fails against the old q30.yaml.

Related Issues

Resolves #5823
Regressed by #5603

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

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit ed50d6b)

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

unwrapField returns null for narrowing casts, but isConvertableAggCall only checks if the result is an instanceof RexInputRef when the aggregation is not CHECKED_LONG_SUM. If unwrapField returns null for a narrowing cast on a non-CHECKED_LONG_SUM aggregation, getField will pass that null to getFieldAndLiteral, which then calls Config.unwrapField again and attempts to use the result without a null check. This can cause a NullPointerException when processing a narrowing cast with a non-CHECKED_LONG_SUM sum function.

private boolean isConvertableAggCall(AggregateCall aggCall, Project project) {
  if (aggCall.getAggregation().getKind() != SqlKind.SUM) {
    return false;
  }
  RexNode arg = project.getProjects().get(aggCall.getArgList().getFirst());
  if (!Config.isCallWithLiteral(arg)) {
    return false;
  }
  // Dropping a widening cast is only type-safe when the sum's return type doesn't depend on
  // its input type, which holds for CHECKED_LONG_SUM (always BIGINT).
  return Config.getField((RexCall) arg) instanceof RexInputRef
      || aggCall.getAggregation() == PPLBuiltinOperators.CHECKED_LONG_SUM;

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to ed50d6b

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Validate cast before allowing transformation

The condition allows dropping widening casts only when the aggregation is
CHECKED_LONG_SUM, but doesn't verify that the cast itself is actually a widening
cast. If getField returns a non-RexInputRef (e.g., a nested cast), the second
condition could incorrectly allow the transformation. Consider adding an explicit
check that the field is either a bare RexInputRef or a valid widening cast.

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [231-232]

-return Config.getField((RexCall) arg) instanceof RexInputRef
-    || aggCall.getAggregation() == PPLBuiltinOperators.CHECKED_LONG_SUM;
+RexNode field = Config.getField((RexCall) arg);
+return field instanceof RexInputRef
+    || (aggCall.getAggregation() == PPLBuiltinOperators.CHECKED_LONG_SUM
+        && Config.unwrapField(field) != null);
Suggestion importance[1-10]: 7

__

Why: The suggestion identifies a potential logic gap where getField might return a non-RexInputRef that isn't properly validated. Adding an explicit check using unwrapField would make the condition more robust and prevent incorrect transformations, improving correctness.

Medium
Document INT_TYPES ordering assumption

The cast validation logic assumes SqlTypeName.INT_TYPES is ordered from narrowest to
widest integer types. If this ordering changes or is not guaranteed, the comparison
to >= from could incorrectly classify casts as widening or narrowing. Add a comment
documenting this ordering assumption or use explicit type comparisons to make the
logic more robust.

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [305-316]

 private static RexInputRef unwrapField(RexNode node) {
   if (node instanceof RexInputRef ref) {
     return ref;
   }
   if (node.getKind() == SqlKind.CAST
       && ((RexCall) node).getOperands().getFirst() instanceof RexInputRef ref) {
+    // INT_TYPES is ordered from narrowest to widest: TINYINT, SMALLINT, INTEGER, BIGINT
     int from = SqlTypeName.INT_TYPES.indexOf(ref.getType().getSqlTypeName());
     int to = SqlTypeName.INT_TYPES.indexOf(node.getType().getSqlTypeName());
     return from >= 0 && to >= from ? ref : null;
   }
   return null;
 }
Suggestion importance[1-10]: 5

__

Why: Adding a comment to document the ordering assumption of SqlTypeName.INT_TYPES improves code maintainability and helps future developers understand the logic. However, this is a documentation improvement rather than a functional fix, so it has moderate impact.

Low

Previous suggestions

Suggestions up to commit 8f6335d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate integer type ordering assumption

The method assumes SqlTypeName.INT_TYPES is ordered from narrowest to widest integer
types, but this ordering is not guaranteed by the API. If the list order changes,
the comparison to >= from could incorrectly validate narrowing casts as widening.
Explicitly verify the cast is widening by checking specific type pairs or use a more
robust ordering mechanism.

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [305-316]

 private static RexInputRef unwrapField(RexNode node) {
   if (node instanceof RexInputRef ref) {
     return ref;
   }
   if (node.getKind() == SqlKind.CAST
       && ((RexCall) node).getOperands().getFirst() instanceof RexInputRef ref) {
-    int from = SqlTypeName.INT_TYPES.indexOf(ref.getType().getSqlTypeName());
-    int to = SqlTypeName.INT_TYPES.indexOf(node.getType().getSqlTypeName());
-    return from >= 0 && to >= from ? ref : null;
+    SqlTypeName fromType = ref.getType().getSqlTypeName();
+    SqlTypeName toType = node.getType().getSqlTypeName();
+    if (isWideningIntegerCast(fromType, toType)) {
+      return ref;
+    }
   }
   return null;
 }
 
+private static boolean isWideningIntegerCast(SqlTypeName from, SqlTypeName to) {
+  int fromIdx = SqlTypeName.INT_TYPES.indexOf(from);
+  int toIdx = SqlTypeName.INT_TYPES.indexOf(to);
+  return fromIdx >= 0 && toIdx >= 0 && toIdx >= fromIdx;
+}
+
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies a potential assumption about SqlTypeName.INT_TYPES ordering. However, the improved code doesn't materially change the logic—it just extracts the comparison into a separate method. The core assumption (to >= from indicates widening) remains unchanged. This is a minor refactoring that slightly improves code organization but doesn't address a critical issue or significantly enhance robustness.

Low
Suggestions up to commit f61cabd
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate operands list before access

The cast validation logic doesn't verify that the cast operand list is non-empty
before accessing the first element. If a malformed RexCall with an empty operand
list is passed, this will throw an exception. Add a check to ensure the operands
list has at least one element before calling getFirst().

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [305-316]

 private static RexInputRef unwrapField(RexNode node) {
   if (node instanceof RexInputRef ref) {
     return ref;
   }
-  if (node.getKind() == SqlKind.CAST
-      && ((RexCall) node).getOperands().getFirst() instanceof RexInputRef ref) {
+  if (node.getKind() == SqlKind.CAST && node instanceof RexCall call
+      && !call.getOperands().isEmpty()
+      && call.getOperands().getFirst() instanceof RexInputRef ref) {
     int from = SqlTypeName.INT_TYPES.indexOf(ref.getType().getSqlTypeName());
     int to = SqlTypeName.INT_TYPES.indexOf(node.getType().getSqlTypeName());
     return from >= 0 && to >= from ? ref : null;
   }
   return null;
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion adds defensive programming by checking if the operands list is non-empty before accessing it. However, in the context of Calcite's RexCall for CAST operations, the operands list should always have exactly one element by design. This check adds safety but addresses a theoretical edge case rather than a likely bug.

Low
Suggestions up to commit d9f751b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify node type before casting

The cast to RexCall is performed without verifying that node is actually an instance
of RexCall. If node.getKind() returns SqlKind.CAST but node is not a RexCall, this
will throw a ClassCastException. Add an instanceof check before casting.

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [305-316]

 private static RexInputRef unwrapField(RexNode node) {
   if (node instanceof RexInputRef ref) {
     return ref;
   }
-  if (node.getKind() == SqlKind.CAST
-      && ((RexCall) node).getOperands().getFirst() instanceof RexInputRef ref) {
+  if (node.getKind() == SqlKind.CAST && node instanceof RexCall call
+      && call.getOperands().getFirst() instanceof RexInputRef ref) {
     int from = SqlTypeName.INT_TYPES.indexOf(ref.getType().getSqlTypeName());
     int to = SqlTypeName.INT_TYPES.indexOf(node.getType().getSqlTypeName());
     return from >= 0 && to >= from ? ref : null;
   }
   return null;
 }
Suggestion importance[1-10]: 8

__

Why: This is a valid safety improvement. While SqlKind.CAST typically implies RexCall, adding an explicit instanceof check before casting prevents potential ClassCastException and makes the code more robust and defensive against unexpected node types.

Medium
Add null check for unwrapped field

The method unwrapField can return null, but the result is directly used in Pair.of
without null checking. This could lead to a NullPointerException if the field cannot
be unwrapped. Add validation to ensure the unwrapped field is not null before
creating the pair.

core/src/main/java/org/opensearch/sql/calcite/plan/rule/PPLAggregateConvertRule.java [239-241]

-return arg1.getKind() == SqlKind.LITERAL
-    ? Pair.of(Config.unwrapField(arg2), (RexLiteral) arg1)
-    : Pair.of(Config.unwrapField(arg1), (RexLiteral) arg2);
+RexInputRef field = arg1.getKind() == SqlKind.LITERAL
+    ? Config.unwrapField(arg2)
+    : Config.unwrapField(arg1);
+if (field == null) {
+  throw new IllegalArgumentException("Unable to unwrap field from operand");
+}
+RexLiteral literal = arg1.getKind() == SqlKind.LITERAL
+    ? (RexLiteral) arg1
+    : (RexLiteral) arg2;
+return Pair.of(field, literal);
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that Config.unwrapField can return null, which could cause issues when creating the Pair. However, the method getFieldAndLiteral is only called when Config.isCallWithLiteral returns true, which already validates that unwrapField returns non-null. The suggestion adds defensive programming but may not be strictly necessary given the existing validation.

Medium

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit f61cabd

@ahkcs ahkcs added the performance Make it fast! label Sep 30, 2026
@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.80%. Comparing base (866dafc) to head (ed50d6b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...sql/calcite/plan/rule/PPLAggregateConvertRule.java 50.00% 3 Missing and 9 partials ⚠️

❌ Your project check has failed because the head coverage (63.80%) 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    #5827      +/-   ##
============================================
+ Coverage     63.66%   63.80%   +0.13%     
- Complexity     9022     9070      +48     
============================================
  Files           959      962       +3     
  Lines         40836    40989     +153     
  Branches       4635     4660      +25     
============================================
+ Hits          26000    26152     +152     
+ Misses        13964    13960       -4     
- Partials        872      877       +5     
Flag Coverage Δ
sql-engine 63.80% <50.00%> (+0.13%) ⬆️

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 added 2 commits October 12, 2026 09:51
PPL widens narrow-integer arithmetic operands (opensearch-project#5603), so sum(x + 1) on a
SMALLINT field reaches PPLAggregateConvertRule as
CHECKED_LONG_SUM(CAST($x):BIGINT + 1). The rule only matched a bare input
ref, so the SUM(x) + k * COUNT(x) rewrite stopped firing and the aggregate
fell back to a full scan with coordinator-side aggregation (ClickBench q30).

Accept a lossless integer widening cast of an input ref as the field operand
and drop the cast in the rewrite. This is type-safe for CHECKED_LONG_SUM,
which always returns BIGINT, and lets the rewritten sums dedup with a plain
sum(x). Casts are only unwrapped for CHECKED_LONG_SUM.

Also assert the explain plan for ClickBench queries that are skipped for
execution: q30 was always skipped because GCedMemoryUsage is never
initialized in the test JVM, so q30.yaml was never compared.

Resolves opensearch-project#5823

Signed-off-by: Kai Huang <[email protected]>
The existing sum-enhancement explain test uses a long field, which is not
widened, so it never exercised the CAST path from opensearch-project#5603. Cover an integer
field in both pushdown and no-pushdown modes.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the fix/5823-agg-convert-widening-cast branch from f61cabd to 8f6335d Compare October 12, 2026 16:52
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 8f6335d

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit ed50d6b

@ahkcs ahkcs added the bugFix label Oct 12, 2026
@ahkcs
ahkcs merged commit 0026279 into opensearch-project:main Oct 13, 2026
47 of 51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Aggregation pushdown lost for sum(int_field + literal): ClickBench q30 regressed from ~700ms to 2min timeout in 3.8

2 participants