Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@
import org.apache.calcite.runtime.PairList;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.tools.RelBuilder;
import org.apache.commons.lang3.tuple.Pair;
import org.immutables.value.Value;
import org.opensearch.sql.calcite.utils.PlanUtils;
import org.opensearch.sql.expression.function.PPLBuiltinOperators;

/**
* Planner rule that converts specific aggCall to a more efficient expressions, which includes:
Expand Down Expand Up @@ -217,27 +219,36 @@ private int putToDistinctAggregateCalls(
}

private boolean isConvertableAggCall(AggregateCall aggCall, Project project) {
return aggCall.getAggregation().getKind() == SqlKind.SUM
&& Config.isCallWithLiteral(project.getProjects().get(aggCall.getArgList().getFirst()));
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;
}

private static Pair<RexInputRef, RexLiteral> getFieldAndLiteral(RexNode node) {
RexCall call = (RexCall) node;
RexNode arg1 = call.getOperands().getFirst();
RexNode arg2 = call.getOperands().getLast();
return arg1.getKind() == SqlKind.INPUT_REF
? Pair.of((RexInputRef) arg1, (RexLiteral) arg2)
: Pair.of((RexInputRef) arg2, (RexLiteral) arg1);
return arg1.getKind() == SqlKind.LITERAL
? Pair.of(Config.unwrapField(arg2), (RexLiteral) arg1)
: Pair.of(Config.unwrapField(arg1), (RexLiteral) arg2);
}

private static RexNode convertToNewOperand(
RexNode operand,
Function<RexNode, RexNode> fieldConverter,
Function<RexNode, RexNode> literalConverter) {
if (operand.getKind() == SqlKind.INPUT_REF) {
return fieldConverter.apply(operand);
} else {
if (operand.getKind() == SqlKind.LITERAL) {
return literalConverter.apply(operand);
} else {
return fieldConverter.apply(operand);
}
}

Expand Down Expand Up @@ -274,12 +285,36 @@ private static boolean isCallWithLiteral(RexNode node) {
if (CONVERTABLE_FUNCTIONS.contains(node.getKind()) && node instanceof RexCall call) {
RexNode arg1 = call.getOperands().getFirst();
RexNode arg2 = call.getOperands().getLast();
return (arg1.getKind() == SqlKind.INPUT_REF && arg2.getKind() == SqlKind.LITERAL)
|| (arg1.getKind() == SqlKind.LITERAL && arg2.getKind() == SqlKind.INPUT_REF);
return (unwrapField(arg1) != null && arg2.getKind() == SqlKind.LITERAL)
|| (arg1.getKind() == SqlKind.LITERAL && unwrapField(arg2) != null);
}
return false;
}

/** Returns the non-literal operand of a call accepted by {@link #isCallWithLiteral}. */
private static RexNode getField(RexCall call) {
RexNode arg1 = call.getOperands().getFirst();
return arg1.getKind() == SqlKind.LITERAL ? call.getOperands().getLast() : arg1;
}

/**
* Returns the input ref of a bare field or of a lossless integer widening cast of one (e.g.
* {@code CAST($0 AS BIGINT)} on a SMALLINT field, added by PPL arithmetic to prevent overflow),
* otherwise null.
*/
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;
}
return null;
}

List<SqlKind> CONVERTABLE_FUNCTIONS =
List.of(
SqlKind.PLUS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
package org.opensearch.sql.calcite;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opensearch.sql.calcite.utils.OpenSearchTypeFactory.TYPE_FACTORY;

Expand Down Expand Up @@ -40,6 +43,7 @@
import org.opensearch.sql.calcite.plan.rule.OpenSearchRules;
import org.opensearch.sql.calcite.plan.rule.PPLAggregateConvertRule;
import org.opensearch.sql.calcite.utils.CalciteToolsHelper.OpenSearchRelBuilder;
import org.opensearch.sql.expression.function.PPLBuiltinOperators;

@ExtendWith(MockitoExtension.class)
public class PPLAggregateConvertRuleTest {
Expand Down Expand Up @@ -113,4 +117,77 @@ public void testRuleMatch() {
.transformTo(any());
OpenSearchRules.AGGREGATE_CONVERT_RULE.apply(mockedCall, aggregate, project);
}

@Test
public void testRuleMatchWithWideningCast() {
// PPL widens narrow-int arithmetic operands: sum(a + 10) on a SMALLINT field becomes
// CHECKED_LONG_SUM(CAST($0 AS BIGINT) + 10). The cast must not block the rewrite.
RelDataType smallint = TYPE_FACTORY.createSqlType(SqlTypeName.SMALLINT);
when(input.getRowType())
.thenReturn(TYPE_FACTORY.createStructType(List.of(smallint, type), List.of("a", "b")));
relBuilder.push(input);
RexNode field = new RexInputRef(0, smallint);
RexNode arg =
rexBuilder.makeCall(
SqlStdOperatorTable.PLUS,
List.of(rexBuilder.makeCast(type, field), rexBuilder.makeLiteral(10, type)));
LogicalAggregate aggregate =
(LogicalAggregate)
relBuilder
.aggregate(
relBuilder.groupKey(1),
ImmutableList.of(
relBuilder.aggregateCall(PPLBuiltinOperators.CHECKED_LONG_SUM, field),
relBuilder.aggregateCall(PPLBuiltinOperators.CHECKED_LONG_SUM, arg)))
.build();
LogicalProject project = (LogicalProject) aggregate.getInput();
assertTrue(PPLAggregateConvertRule.Config.containsCallWithNumber(project));

doAnswer(
invocation -> {
RelNode rel = invocation.getArgument(0);
assertTrue(
RelOptUtil.areRowTypesEqual(rel.getRowType(), aggregate.getRowType(), false));
// The cast is dropped so both sums collapse into one pushable SUM on the raw field
assertEquals(
"LogicalProject(b=[$0], $f1=[$1], $f2=[+($1, *($2, 10))])\n"
+ " LogicalAggregate(group=[{1}], agg#0=[CHECKED_LONG_SUM($0)],"
+ " null_COUNT=[COUNT($0)])\n"
+ " LogicalProject(a=[$0], b=[$1])\n",
rel.explain().replaceAll("\\r\\n", "\n"));
return null;
})
.when(mockedCall)
.transformTo(any());
OpenSearchRules.AGGREGATE_CONVERT_RULE.apply(mockedCall, aggregate, project);
verify(mockedCall).transformTo(any());
}

@Test
public void testNarrowingCastNotMatched() {
relBuilder.push(input);
RexNode arg =
rexBuilder.makeCall(
SqlStdOperatorTable.PLUS,
List.of(
rexBuilder.makeCast(
TYPE_FACTORY.createSqlType(SqlTypeName.INTEGER), new RexInputRef(0, type)),
rexBuilder.makeLiteral(10, type)));
LogicalAggregate aggregate =
(LogicalAggregate)
relBuilder
.aggregate(
relBuilder.groupKey(1),
ImmutableList.of(
relBuilder.aggregateCall(PPLBuiltinOperators.CHECKED_LONG_SUM, arg)))
.build();
assertEquals(
"LogicalAggregate(group=[{0}], agg#0=[CHECKED_LONG_SUM($1)])\n"
+ " LogicalProject(b=[$1], $f2=[+(CAST($0):INTEGER NOT NULL, 10:BIGINT)])\n",
aggregate.explain().replaceAll("\\r\\n", "\n"));
LogicalProject project = (LogicalProject) aggregate.getInput();
assertFalse(PPLAggregateConvertRule.Config.containsCallWithNumber(project));
OpenSearchRules.AGGREGATE_CONVERT_RULE.apply(mockedCall, aggregate, project);
verify(mockedCall, never()).transformTo(any());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,17 @@ protected Set<Integer> ignored() throws IOException {
@Test
public void test() throws IOException {
for (int i = 1; i <= 43; i++) {
if (ignored().contains(i)) {
continue;
}
logger.info("Running Query{}", i);
String ppl = sanitize(loadFromFile("clickbench/queries/q" + i + ".ppl"));
// V2 gets unstable scripts, ignore them when comparing plan
if (isCalciteEnabled()) {
String expected = loadExpectedPlan("clickbench/q" + i + ".yaml");
assertYamlEqualsIgnoreId(expected, explainQueryYaml(ppl));
}
// Ignored queries still get their plan checked above; only execution is skipped
if (ignored().contains(i)) {
continue;
}
timing(summary, "q" + i, ppl);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,19 @@ public void testExplainOnAggregationWithSumEnhancement() throws IOException {
TEST_INDEX_BANK)));
}

// Narrow-int operands are widened by a CAST, which must not block the SUM rewrite (#5823)
@Test
public void testExplainOnAggregationWithSumEnhancementOnNarrowInt() throws IOException {
String expected = loadExpectedPlan("explain_agg_with_sum_enhancement_narrow_int.yaml");
assertYamlEqualsIgnoreId(
expected,
explainQueryYaml(
String.format(
"source=%s | stats sum(age), sum(age + 100), sum(age - 100), sum(age * 100) by"
+ " gender",
TEST_INDEX_BANK)));
}

@Test
public void testStatsDistinctCountApproxFunctionExplainWithPushDown() throws IOException {
enabledOnlyWhenPushdownIsEnabled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1518,6 +1518,36 @@ public void testAggWithFunction() throws IOException {
verifyDataRows(response, rows(121764, 1, "F"), rows(65909, 1, "M"));
}

// Narrow-int operands are widened by a CAST before the SUM rewrite (#5823)
@Test
public void testSumWithLiteralOnNarrowInt() throws IOException {
JSONObject response =
executeQuery(
String.format(
"source=%s | stats sum(age) as s, sum(age + 100) as p, sum(age - 100) as m,"
+ " sum(age * 100) as x by gender",
TEST_INDEX_BANK));
verifySchema(
response,
schema("s", null, "bigint"),
schema("p", null, "bigint"),
schema("m", null, "bigint"),
schema("x", null, "bigint"),
schema("gender", null, "string"));
verifyDataRows(response, rows(101, 401, -199, 10100, "F"), rows(137, 537, -263, 13700, "M"));
}

// Null ages are excluded from COUNT, so sum(age + 100) adds 100 per non-null row only
@Test
public void testSumWithLiteralOnNarrowIntWithNulls() throws IOException {
JSONObject response =
executeQuery(
String.format(
"source=%s | stats sum(age + 100) as p by gender",
TEST_INDEX_BANK_WITH_NULL_VALUES));
verifyDataRows(response, rows(262, "F"), rows(537, "M"));
}

@Test
public void testAggByByteNumberWithScript() throws IOException {
JSONObject response =
Expand Down
Loading
Loading