This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 0af29058748 Fold casts of array literals in the multi-stage planner 
without code generation (#20070)
0af29058748 is described below

commit 0af290587483ed15b355927073ba07a78271da3a
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Sat Nov 21 17:45:30 2026 -0800

    Fold casts of array literals in the multi-stage planner without code 
generation (#20070)
    
    * Fold casts of array literals in the query planner
    
    * Round REAL casts to single precision and test array-literal cast folding 
against Calcite
    
    * Fold only exact numeric sources to approximate casts and keep nullable 
targets
    
    Reading a DOUBLE literal as a BigDecimal rounds it to 16 digits, and NaN or 
infinity cannot be read that way, so
    approximate sources go to the fallback. A nullable target keeps its type 
through makeLiteral with a cast, as on the
    string path. The class Javadoc now covers numeric casts and literal arrays.
    
    * Build approximate cast literals from the double and fold overflow
    
    Pass the converted double straight to makeLiteral so a negative underflow 
keeps
    its sign, and drop the finite-value check: the literal can hold the 
infinity an
    exact-source overflow produces. Tests type their source literals explicitly,
    cover exact-source overflow and negative underflow, and reduce the 
768-element
    reference vector in one batch.
    
    * Preserve Calcite coercion when folding query vectors
    
    Calcite rebuilds array elements at their common type and narrows integer 
literals to their declared source width. For example, reducing an array with 
CHAR(1) and CHAR(3) elements pads the first value, and an INTEGER-typed literal 
holding 2147483648 converts to a negative DOUBLE. Restrict the direct paths to 
values already in range and vectors whose elements are already in their final 
representation.
    
    ---------
    
    Co-authored-by: Xiang Fu <[email protected]>
---
 .../apache/pinot/calcite/rex/PinotRexExecutor.java |  68 ++++++++++++-
 .../pinot/calcite/rex/PinotRexExecutorTest.java    | 112 +++++++++++++++++++++
 2 files changed, 175 insertions(+), 5 deletions(-)

diff --git 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rex/PinotRexExecutor.java
 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rex/PinotRexExecutor.java
index 5d4757f0ec3..3a92314b760 100644
--- 
a/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rex/PinotRexExecutor.java
+++ 
b/pinot-query-planner/src/main/java/org/apache/pinot/calcite/rex/PinotRexExecutor.java
@@ -21,6 +21,7 @@ package org.apache.pinot.calcite.rex;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
+import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -43,9 +44,11 @@ import org.apache.calcite.sql.type.SqlTypeUtil;
 
 
 /// Reduces string literal casts using bounded, reusable Calcite executables. 
Each source/target type pair is compiled
-/// with an input reference instead of a literal, so different values share 
Calcite's conversion code. Other expressions
-/// use the fallback executor. Cached functions are immutable; input values 
and results stay local to each call, making
-/// this executor thread-safe without sharing RexExecutable's mutable data 
context.
+/// with an input reference instead of a literal, so different values share 
Calcite's conversion code. Casts of exact
+/// numeric literals to DOUBLE, FLOAT or REAL are rounded directly. Arrays of 
approximate literals that already have
+/// their final element type and precision are kept as they are. Other 
expressions use the fallback executor. Cached
+/// functions are immutable; input values and results stay local to each call, 
making this executor thread-safe
+/// without sharing RexExecutable's mutable data context.
 public final class PinotRexExecutor implements RexExecutor {
   public static final PinotRexExecutor INSTANCE = new 
PinotRexExecutor(RexUtil.EXECUTOR);
 
@@ -68,7 +71,8 @@ public final class PinotRexExecutor implements RexExecutor {
     // Calcite treats reduction as all-or-nothing. Delegate the entire batch 
if any expression is unsupported, so a
     // failure in the fallback cannot leave the batch partially reduced.
     for (RexNode expression : constExps) {
-      if (!isSupportedStringCast(expression)) {
+      if (!isSupportedStringCast(expression) && !isReducedVector(expression)
+          && !isNumericToApproximateCast(expression)) {
         _fallback.reduce(rexBuilder, constExps, reducedValues);
         return;
       }
@@ -76,7 +80,20 @@ public final class PinotRexExecutor implements RexExecutor {
     List<RexNode> literals = new ArrayList<>(constExps.size());
     try {
       for (RexNode expression : constExps) {
-        RexLiteral operand = (RexLiteral) ((RexCall) 
expression).getOperands().get(0);
+        RexCall call = (RexCall) expression;
+        if (call.getOperator() == SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR) 
{
+          literals.add(call);
+          continue;
+        }
+        RexLiteral operand = (RexLiteral) call.getOperands().get(0);
+        if (!SqlTypeUtil.isCharacter(operand.getType())) {
+          BigDecimal value = operand.getValueAs(BigDecimal.class);
+          // Calcite uses single precision for REAL and double precision for 
FLOAT and DOUBLE.
+          double rounded =
+              call.getType().getSqlTypeName() == SqlTypeName.REAL ? 
value.floatValue() : value.doubleValue();
+          literals.add(rexBuilder.makeLiteral(rounded, call.getType(), true));
+          continue;
+        }
         Object value = null;
         if (!operand.isNull()) {
           Function1<DataContext, Object[]> cast = getCast(rexBuilder, 
operand.getType(), expression.getType());
@@ -105,6 +122,47 @@ public final class PinotRexExecutor implements RexExecutor 
{
     });
   }
 
+  private static boolean isNumericToApproximateCast(RexNode expression) {
+    if (!(expression instanceof RexCall call) || call.getOperator() != 
SqlStdOperatorTable.CAST
+        || call.getOperands().size() != 1 || 
!SqlTypeUtil.isApproximateNumeric(call.getType())
+        || !(call.getOperands().get(0) instanceof RexLiteral literal)
+        || !(literal.getValue() instanceof BigDecimal value)) {
+      return false;
+    }
+    RelDataType source = literal.getType();
+    if (SqlTypeUtil.isDecimal(source)) {
+      return true;
+    }
+    if (!SqlTypeName.INT_TYPES.contains(source.getSqlTypeName())) {
+      return false;
+    }
+    // An INTEGER-typed Rex literal can carry a wider value. Let Calcite 
narrow it to the source width first.
+    long max = SqlTypeUtil.maxValue(source);
+    return value.scale() == 0 && value.compareTo(BigDecimal.valueOf(-max - 1)) 
>= 0
+        && value.compareTo(BigDecimal.valueOf(max)) <= 0;
+  }
+
+  private static boolean isReducedVector(RexNode expression) {
+    if (!(expression instanceof RexCall call) || call.getOperator() != 
SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR
+        || call.getType().getSqlTypeName() != SqlTypeName.ARRAY || 
call.getType().isNullable()
+        || call.getOperands().isEmpty()) {
+      return false;
+    }
+    RelDataType component = call.getType().getComponentType();
+    if (component == null || component.isNullable() || 
!SqlTypeUtil.isApproximateNumeric(component)) {
+      return false;
+    }
+    // Calcite rebuilds each element at the array's component type and rounds 
REAL elements to single precision.
+    for (RexNode operand : call.getOperands()) {
+      if (!(operand instanceof RexLiteral literal) || 
!component.equals(literal.getType())
+          || !(literal.getValue() instanceof Double value) || 
Double.isNaN(value)
+          || (component.getSqlTypeName() == SqlTypeName.REAL && 
value.doubleValue() != value.floatValue())) {
+        return false;
+      }
+    }
+    return true;
+  }
+
   private static boolean isSupportedStringCast(RexNode expression) {
     if (!(expression instanceof RexCall)) {
       return false;
diff --git 
a/pinot-query-planner/src/test/java/org/apache/pinot/calcite/rex/PinotRexExecutorTest.java
 
b/pinot-query-planner/src/test/java/org/apache/pinot/calcite/rex/PinotRexExecutorTest.java
index 89351688c6b..c3ca92c9e19 100644
--- 
a/pinot-query-planner/src/test/java/org/apache/pinot/calcite/rex/PinotRexExecutorTest.java
+++ 
b/pinot-query-planner/src/test/java/org/apache/pinot/calcite/rex/PinotRexExecutorTest.java
@@ -278,13 +278,125 @@ public class PinotRexExecutorTest {
     }
   }
 
+  @DataProvider
+  public Object[][] numericLiterals() {
+    List<Object[]> cases = new ArrayList<>();
+    for (SqlTypeName target : List.of(SqlTypeName.FLOAT, SqlTypeName.REAL, 
SqlTypeName.DOUBLE)) {
+      // Exact DECIMAL sources, including values that overflow to infinity or 
underflow to a signed zero
+      for (String value : new String[]{"0", "1", "-7", "0.1", "-2.5", 
"0.123456789123", "3.4028235E38", "1E39",
+          "-1E39", "1E308", "1E400", "-1E400", "1E-50", "-1E-50", "1E-400", 
"-1E-400"}) {
+        cases.add(new Object[]{target, value, true});
+      }
+      // Approximate (DOUBLE) sources, as SQL writes a literal in exponent 
notation
+      for (String value : new String[]{"3.4028235E38", "1E39", "1E308"}) {
+        cases.add(new Object[]{target, value, false});
+      }
+    }
+    return cases.toArray(new Object[0][]);
+  }
+
+  @Test(dataProvider = "numericLiterals")
+  public void testNumericToApproximateCastsMatchCalcite(SqlTypeName 
targetType, String value, boolean exactSource) {
+    LiteralRexBuilder builder = new LiteralRexBuilder();
+    RelDataType target = builder.getTypeFactory().createSqlType(targetType);
+    RexNode literal = exactSource
+        ? exactLiteral(builder, new BigDecimal(value))
+        : builder.makeApproxLiteral(new BigDecimal(value));
+    RexNode expression = builder.makeAbstractCast(target, literal, false);
+    List<RexNode> input = List.of(expression);
+    CountingFallback fallback = new CountingFallback(CALCITE_EXECUTOR);
+    List<RexNode> expected = reduce(CALCITE_EXECUTOR, builder, input);
+    List<RexNode> actual = reduce(new PinotRexExecutor(fallback), builder, 
input);
+    assertEquals(actual, expected);
+    assertEquals(actual.get(0).getType(), expected.get(0).getType());
+    // Only approximate sources are left to the fallback
+    assertEquals(fallback._calls.get(), exactSource ? 0 : 1);
+  }
+
+  @Test
+  public void testNegativeUnderflowKeepsSign() {
+    LiteralRexBuilder builder = new LiteralRexBuilder();
+    // Each value is below the smallest positive value of its target type
+    for (Map.Entry<SqlTypeName, String> entry : Map.of(SqlTypeName.REAL, 
"-1E-50", SqlTypeName.DOUBLE, "-1E-400")
+        .entrySet()) {
+      SqlTypeName targetType = entry.getKey();
+      RexNode expression = 
builder.makeAbstractCast(builder.getTypeFactory().createSqlType(targetType),
+          exactLiteral(builder, new BigDecimal(entry.getValue())), false);
+      RexLiteral actual = (RexLiteral) reduce(new 
PinotRexExecutor(FAILING_FALLBACK), builder, List.of(expression))
+          .get(0);
+      
assertEquals(Double.doubleToRawLongBits(actual.getValueAs(Double.class)), 
Double.doubleToRawLongBits(-0.0),
+          "CAST(" + entry.getValue() + " AS " + targetType + ") must be 
negative zero");
+    }
+  }
+
+  /// An exact DECIMAL literal typed to hold `value` exactly, however large or 
small its exponent.
+  private static RexLiteral exactLiteral(RexBuilder builder, BigDecimal value) 
{
+    int scale = Math.max(value.scale(), 0);
+    int precision = Math.max(value.precision() - value.scale(), 1) + scale;
+    RelDataType type = 
builder.getTypeFactory().createSqlType(SqlTypeName.DECIMAL, precision, scale);
+    return builder.makeExactLiteral(value.setScale(scale), type);
+  }
+
+  @Test
+  public void testApproximateSourceCastsUseFallback() {
+    LiteralRexBuilder builder = new LiteralRexBuilder();
+    RelDataType doubleType = 
builder.getTypeFactory().createSqlType(SqlTypeName.DOUBLE);
+    // 17 significant digits: rounding to a 16-digit BigDecimal would fold 
this to 0.3
+    RexNode literal = builder.makeApproxLiteral(new 
BigDecimal("0.30000000000000004"));
+    RexNode expression = builder.makeAbstractCast(doubleType, literal, false);
+    List<RexNode> input = List.of(expression);
+    CountingFallback fallback = new CountingFallback(CALCITE_EXECUTOR);
+    List<RexNode> actual = reduce(new PinotRexExecutor(fallback), builder, 
input);
+    assertEquals(fallback._calls.get(), 1);
+    assertEquals(actual, reduce(CALCITE_EXECUTOR, builder, input));
+  }
+
+  @Test
+  public void testNumericToApproximateCastKeepsNullableTargetType() {
+    LiteralRexBuilder builder = new LiteralRexBuilder();
+    RelDataType nullableDouble = 
builder.getTypeFactory().createTypeWithNullability(
+        builder.getTypeFactory().createSqlType(SqlTypeName.DOUBLE), true);
+    RexNode expression = builder.makeAbstractCast(nullableDouble, 
builder.makeExactLiteral(new BigDecimal("0.5")),
+        false);
+    List<RexNode> input = List.of(expression);
+    List<RexNode> actual = reduce(new PinotRexExecutor(FAILING_FALLBACK), 
builder, input);
+    assertEquals(actual.get(0).getType(), expression.getType());
+    assertEquals(actual, reduce(CALCITE_EXECUTOR, builder, input));
+  }
+
+  @Test
+  public void testQueryVectorIsReducedWithoutFallback() {
+    LiteralRexBuilder builder = new LiteralRexBuilder();
+    RelDataType real = 
builder.getTypeFactory().createSqlType(SqlTypeName.REAL);
+    List<RexNode> casts = new ArrayList<>();
+    casts.add(builder.makeAbstractCast(real, 
builder.makeExactLiteral(BigDecimal.ZERO), false));
+    for (int i = 1; i < 768; i++) {
+      casts.add(builder.makeAbstractCast(real, 
builder.makeExactLiteral(BigDecimal.valueOf(i, 3)), false));
+    }
+    // One reference batch: a compilation per element would dominate the 
test's run time
+    List<RexNode> elements = reduce(CALCITE_EXECUTOR, builder, casts);
+    // A vector of literals arrives either as its element casts or as an array 
of already reduced literals
+    assertEquals(reduce(new PinotRexExecutor(FAILING_FALLBACK), builder, 
casts), elements);
+    RexNode array = 
builder.makeCall(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR, elements);
+    List<RexNode> actual = reduce(new PinotRexExecutor(FAILING_FALLBACK), 
builder, List.of(array));
+    assertSame(actual.get(0), array);
+    assertEquals(actual, reduce(CALCITE_EXECUTOR, builder, List.of(array)));
+  }
+
   @Test
   public void testUnsupportedExpressionsDelegateTheWholeBatchInOrder() {
     LiteralRexBuilder builder = new LiteralRexBuilder();
     RexNode fast = timestampCast(builder, SqlTypeName.CHAR, "2026-09-01 
12:34:56.123", 3);
     RelDataType timestamp = 
builder.getTypeFactory().createSqlType(SqlTypeName.TIMESTAMP, 3);
     RexLiteral string = builder.stringLiteral("2026-09-01 12:34:56.123", 
SqlTypeName.CHAR);
+    RelDataType integer = 
builder.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
+    RelDataType real = 
builder.getTypeFactory().createSqlType(SqlTypeName.REAL);
     List<RexNode> unsupported = List.of(
+        builder.makeCall(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR, 
builder.makeLiteral("a"),
+            builder.makeLiteral("abc")),
+        builder.makeCall(SqlStdOperatorTable.ARRAY_VALUE_CONSTRUCTOR, 
builder.makeApproxLiteral(0.1d, real)),
+        builder.makeAbstractCast(real, builder.makeExactLiteral(new 
BigDecimal("2147483648"), integer), false),
+        builder.makeAbstractCast(real, builder.makeNullLiteral(integer), 
false),
         builder.makeCall(SqlStdOperatorTable.PLUS, 
builder.makeExactLiteral(BigDecimal.ONE),
             builder.makeExactLiteral(BigDecimal.TEN)),
         builder.makeAbstractCast(timestamp, string, true),


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to