diff --git a/SKILLS.md b/SKILLS.md
index c660eec5b9e9..3a57a0722cce 100644
--- a/SKILLS.md
+++ b/SKILLS.md
@@ -248,5 +248,7 @@ the pre-commit hook also checks. Groups below are in file order.
* [The fork's CI queue is a job inside the Build, and the check sync rides the push](sql/varka/skills/working-in-this-repo.md#the-forks-ci-queue-is-a-job-inside-the-build-and-the-check-sync-rides-the-push)
* [GitHub Actions facts the CI queue cost a run each to learn](sql/varka/skills/working-in-this-repo.md#github-actions-facts-the-ci-queue-cost-a-run-each-to-learn)
* [`varka_regen_generated.sh --all` does not regenerate the golden corpus](sql/varka/skills/working-in-this-repo.md#varka_regen_generatedsh---all-does-not-regenerate-the-golden-corpus)
+* [The pre-commit hook refuses a census claim that `coverage.json` cannot show yet](sql/varka/skills/working-in-this-repo.md#the-pre-commit-hook-refuses-a-census-claim-that-coveragejson-cannot-show-yet)
+* [The quote check reads a plan section numbered 10.1x as a measurement](sql/varka/skills/working-in-this-repo.md#the-quote-check-reads-a-plan-section-numbered-101x-as-a-measurement)
diff --git a/docs/sql-varka.md b/docs/sql-varka.md
index 16aec604dec5..4103f2d13170 100644
--- a/docs/sql-varka.md
+++ b/docs/sql-varka.md
@@ -291,7 +291,7 @@ An entry is a function or operator of the census; a type counts *fused* for it o
| `LongType` (`bigint`) | LONG | 85 | 60 | 2 | plumbing 5, semantics 18 | 0 | 90 |
| `FloatType` (`float`) | FLOAT | 66 | 36 | 2 | plumbing 5, semantics 23 | 0 | 62 |
| `DoubleType` (`double`) | DOUBLE | 102 | 54 | 2 | plumbing 4, semantics 24, ulp 18 | 0 | 82 |
-| `DecimalType` (`dec`) | LONG, words per value: 1 to precision 18, 2 to precision 38 | 66 | 2 | 9 | plumbing 12, semantics 43 | 3 | 85: 60 to precision 18, 25 at precision 19 to 38 |
+| `DecimalType` (`dec`) | LONG, words per value: 1 to precision 18, 2 to precision 38 | 66 | 2 | 26 | plumbing 3, semantics 35 | 3 | 93: 68 to precision 18, 25 at precision 19 to 38 |
| `DateType` (`date`) | INT | 63 | 49 | 1 | plumbing 1, semantics 12 | 0 | 107 |
| `TimestampNTZType` (`ntz`) | LONG | 54 | 49 | 0 | plumbing 1, semantics 4 | 0 | 75 |
| `TimeType` (`time`) | LONG | 49 | 34 | 3 | plumbing 1, semantics 11 | 0 | 47 |
@@ -304,9 +304,9 @@ One row per section of Spark's function registry, and per family of the operator
| Family | Entries | Every type | Some type | In part | Types owed | Rows |
| :--- | ---: | ---: | ---: | ---: | :--- | :--- |
-| conditional | 11 | 1 | 11 | 1 | float, dec | 329, 331, 338, 341, 348, 359 |
+| conditional | 11 | 1 | 11 | 10 | float, dec | 329, 331, 338, 341, 348, 359 |
| predicate | 16 | 6 | 15 | 8 | bool, dec | 27, 329, 331, 336, 338, 341, 347, 348, 359, 497 |
-| math | 59 | 17 | 33 | 0 | bool, byte, short, int, bigint, float, double, dec, time, ym, dt | 30, 95, 103, 104, 329, 330, 333, 341, 342, 344, 346, 348, 349, 351, 356, 357, 358, 359, 360, 361, 362, 363, 367, 577, 621 |
+| math | 59 | 17 | 33 | 8 | bool, byte, short, int, bigint, float, double, dec, time, ym, dt | 30, 95, 103, 104, 329, 330, 333, 341, 342, 344, 346, 348, 349, 351, 356, 357, 358, 359, 360, 361, 362, 363, 367, 577, 621 |
| bitwise | 13 | 13 | 13 | 0 | | |
| datetime | 41 | 27 | 36 | 0 | byte, short, int, bigint, float, double, dec, ntz, time, ym, dt | 103, 329, 339, 340, 343, 351 |
| hash | 2 | 0 | 0 | 0 | bool, byte, short, int, bigint, float, double, dec, date, ntz, time, ym, dt | 337, 359, 368 |
@@ -1530,6 +1530,19 @@ The *Switches* column names the family switches that keep the row off Varka, eac
| `-(d9 + d9b) = d9s4` | `predicate` | | the negation of a sum, compared at DECIMAL(12, 4) | not emitted: a filter's condition in a kernel driven at a 64-bit lane (BIGINT, DOUBLE, TIMESTAMP_NTZ, TIME, day-time interval, DECIMAL), on an x86 host whose 64-bit species have two lanes or fewer: C2 lowers no mask there, and the selection would run the Vector API's Java fallback |
| `try_multiply(d8, d9) IS NULL` | `predicate` | | null only where an operand is: no product within 18 digits overflows, so TRY's null past the precision never fires | not emitted: a filter's condition in a kernel driven at a 64-bit lane (BIGINT, DOUBLE, TIMESTAMP_NTZ, TIME, day-time interval, DECIMAL), on an x86 host whose 64-bit species have two lanes or fewer: C2 lowers no mask there, and the selection would run the Vector API's Java fallback |
+#### DECIMAL values
+
+| Expression | Switches | Domain | Notes | 128-bit lanes |
+|---|---|---|---|---|
+| `CASE WHEN d9 < d9b THEN d9 ELSE d9b END` | `predicate`, `condition` | | a DECIMAL(9, 2) choice, the comparison and the blend on the long lane | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `if(d9 < d9b, d18, d18b)` | `predicate`, `condition` | | a DECIMAL(18, 2) choice under a DECIMAL(9, 2) condition | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `coalesce(d9, d9s4)` | `condition` | | DECIMAL(11, 4): d9 times 10^2, then the first valid operand | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `greatest(d18, d18b)` | `intArithmetic` | | the null-skipping pick, of one scale | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `least(d9, d9s4)` | `intArithmetic` | | the null-skipping pick at DECIMAL(11, 4), d9 carrying its rescale | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `-d18` | none | | a negation, which cannot overflow: an unscaled value within 18 digits is never the long lane's minimum | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `abs(d18)` | none | | a compare with zero, a negation and a blend; the lanewise ABS is the decimalAbsLanewise option | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+| `try_subtract(d9, d9s4)` | none | | DECIMAL(12, 4), row 349's difference stored by the same path: no difference within 18 digits overflows, so TRY's null never fires | per-lane: compare to mask, mask cast, other, blend, mask logic, mask broadcast, mask test |
+
#### Time arithmetic
| Expression | Switches | Domain | Notes | 128-bit lanes |
@@ -1578,7 +1591,7 @@ operands (a row counts once for each type it reads):
| `bool` | 39 | 0 | 0 | 0 | 13 | 0 | 26 |
| `byte` | 57 | 0 | 0 | 0 | 0 | 8 | 49 |
| `date` | 128 | 17 | 0 | 0 | 1 | 0 | 110 |
-| `dec` | 85 | 1 | 42 | 12 | 0 | 0 | 30 |
+| `dec` | 93 | 1 | 50 | 12 | 0 | 0 | 30 |
| `double` | 97 | 0 | 0 | 1 | 0 | 0 | 96 |
| `dt` | 36 | 2 | 0 | 4 | 0 | 0 | 30 |
| `float` | 63 | 0 | 0 | 0 | 0 | 0 | 63 |
diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaDecimalCompiler.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaDecimalCompiler.java
index d44b2d6bd89b..2e657149a744 100644
--- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaDecimalCompiler.java
+++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaDecimalCompiler.java
@@ -121,8 +121,8 @@
* lowers the scale or the integral digits, or one from an integral type (row 350); a negative
* scale (the milestone plan's 2.8); and every operator no arm here claims yet.
*
- *
A decimal-valued output root is compiled by {@link #output}, which the projection's root
- * binding calls, and admitted by {@link #outputRoot}.
+ *
A decimal-valued output root is any {@link #value}, compiled by {@link #output}, which the
+ * projection's root binding calls, and admitted by {@link #outputRoot}.
*/
final class VarkaDecimalCompiler {
@@ -208,6 +208,12 @@ static Optional value(Expression e, VarkaSlotTable inputs, VarkaSlotTabl
return switch (e) {
case BoundReference br -> column(br, type, inputs, sink);
case Cast c -> cast(c, type, inputs, literals, sink);
+ // The two decimal-valued TIME functions (VARKA-157 2.3), under the TIME family's switch,
+ // which this path never reaches through compileNode: each is within its precision for
+ // every time of day.
+ case StaticInvoke si when VarkaTimeCompiler.isDecimalProducer(si) ->
+ VarkaNodeCompiler.inFamily(VarkaFamily.TIME,
+ () -> VarkaTimeCompiler.decimalProducer(si, inputs, literals, sink), si, sink);
// Neither can fail or leave the precision, |-u| = |u| (VARKA-348 0.5), so both wrap: the
// one overflowing long, Long.MIN_VALUE, is outside every decimal's bound.
case UnaryMinus m -> value(m.child(), inputs, literals, sink)
@@ -886,13 +892,11 @@ private static Optional> compiledOperands(Expression whole,
}
/**
- * A decimal-valued output root, or empty with the reason noted (`VARKA-157.md` 2.1): the
- * output's type is asked first, so a precision above 18 or a negative scale declines naming its
- * row at plan time, whatever the expression; then the value is compiled and wrapped by
- * {@link #outputRoot}. The producers today are the two decimal-valued {@code TIME} functions
- * ({@code VarkaTimeCompiler.decimalProducer}); every other decimal value as an output declines
- * naming row 348, whose values ({@link #value}) reach this method's {@link #widened} when its
- * part 348b admits them.
+ * A decimal-valued output root, or empty with the reason noted (`VARKA-157.md` 2.1,
+ * `VARKA-348.md` 2.4): the output's type is asked first, so a precision above 18 or a negative
+ * scale declines naming its row at plan time, whatever the expression; then the value is
+ * compiled by {@link #value}, as under a comparison, and wrapped by {@link #widened}. Every
+ * form {@link #value} builds is within its type's precision, so the store needs no check.
*/
static Optional output(Expression e, VarkaSlotTable inputs,
VarkaSlotTable literals, DeclineSink sink) {
@@ -901,29 +905,27 @@ static Optional output(Expression e, VarkaSlotTable inputs,
if (refused.isPresent()) {
return sink.decline(refused.get(), e);
}
- if (e instanceof StaticInvoke si && VarkaTimeCompiler.isDecimalProducer(si)) {
- // The producers are the TIME family's nodes, and this path never passes through
- // compileNode, so it asks the family's switch and notes the family itself.
- return VarkaNodeCompiler.inFamily(VarkaFamily.TIME, () ->
- VarkaTimeCompiler.decimalProducer(si, inputs, literals, sink)
- .flatMap(v -> widened(e, v, sink)), e, sink);
+ // Bracketed as a comparison's operands are, so the choice conditions it keeps are dropped
+ // before the entry's tables can be rolled back to its marks.
+ sink.enterDecimal();
+ try {
+ return value(e, inputs, literals, sink).flatMap(v -> widened(e, v, sink));
+ } finally {
+ sink.exitDecimal();
}
- return sink.decline("a " + type.simpleString() + " value as a projection's output: the "
- + "decimal store writes it, and the values it admits are the TIME functions "
- + "time_to_seconds and extract(SECOND ...); the others are row 348's", e);
}
/**
* The output root of a compiled decimal {@code value} of {@code whole}: at the output type's
- * scale, which every producer builds, and then {@link #outputRoot}. A value at another scale is
- * a producer's error, not a decline.
+ * scale, which every producer builds, and then {@link #outputRoot}. A value at another scale, or
+ * of a wider precision, declines with its types named: the store does not rescale.
*/
private static Optional widened(Expression whole, Scaled value,
DeclineSink sink) {
DecimalType type = (DecimalType) whole.dataType();
if (value.type().scale() != type.scale() || value.type().precision() > type.precision()) {
- throw VarkaErrors.illegalState("a decimal output of " + type.simpleString()
- + " over a value of " + value.type().simpleString() + ": " + whole);
+ return sink.decline("a decimal output of " + type.simpleString() + " over a value of "
+ + value.type().simpleString() + ", which the store does not rescale", whole);
}
return outputRoot(whole, value.unscaled(), sink);
}
diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaTimeCompiler.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaTimeCompiler.java
index f58852d7e465..bb12f09c991b 100644
--- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaTimeCompiler.java
+++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaTimeCompiler.java
@@ -231,13 +231,12 @@ static VarkaFamilyArm arm(
// constructors refuse a tree that mixes it with the int lane anyway.
// A decimal column is never a long column, whatever lane the registry gives it
// (VARKA-347): its sixteen-byte slots are read by its own leaf, with the check Spark's
- // reader makes. Under a comparison or a null test, a decimal value - the column, a
- // rescale, a negation, abs, a choice or a pick over it (VARKA-348), a sum, a difference or
- // a product (VARKA-349) - is built by VarkaDecimalCompiler, so a decimal column reaching
- // here declines, ahead of the long column's arm below, which would read the slots as
- // eight-byte longs: with the registry's reason where it has one (a precision or scale off
- // the lane), and otherwise as a value outside a
- // condition - an output, row 348's (348b), or the operand of a cast to an integral
+ // reader makes. Under a comparison or a null test and as a decimal output, a decimal
+ // value - the column, a rescale, a negation, abs, a choice or a pick over it (VARKA-348),
+ // a sum, a difference or a product (VARKA-349) - is built by VarkaDecimalCompiler, so a
+ // decimal column reaching here declines, ahead of the long column's arm below, which would
+ // read the slots as eight-byte longs: with the registry's reason where it has one (a
+ // precision or scale off the lane), and otherwise as the operand of a cast to an integral
// or a floating type, rows 350 and 366. Above 18 digits the value is two words
// (VARKA-359), whose operators beyond the comparisons and null tests are later rows'.
case BoundReference br when br.dataType() instanceof DecimalType d ->
@@ -247,8 +246,8 @@ static VarkaFamilyArm arm(
? "its comparisons and null tests fuse; its negation, abs and choices are row "
+ "359's, its +, - and * rows 360 to 363, a decimal output its two-word "
+ "store, row 359's"
- : "its comparisons, null tests and the values they read fuse, +, - and * "
- + "among them; a decimal output is row 348's")
+ : "its comparisons, null tests, the values they read and a decimal output "
+ + "of them fuse, +, - and * among them")
+ ", its casts to other types rows 350 and 366"), br);
case BoundReference br
when VarkaTypes.lane(br.dataType()).orElse(null) == LaneType.LONG ->
@@ -602,14 +601,14 @@ private static String timeNotLoweredYet(String label) {
}
/**
- * The reason the two decimal-valued {@code TIME} expressions decline below a root: at an output
- * root they fuse through the decimal store ({@link #decimalProducer}), and as the operand of
- * another expression their value is a decimal operand, which row 348 consumes
- * (`VARKA-157.md` 2.1).
+ * The reason the two decimal-valued {@code TIME} expressions decline where a non-decimal
+ * operator reads them: as an output root and as a decimal operand they are
+ * {@code VarkaDecimalCompiler.value}'s ({@link #decimalProducer}), and the casts of a decimal
+ * to another type are rows 350 and 366.
*/
private static String decimalOperandNotYet(String label) {
- return label + " returns a decimal, which fuses as a projection's output; as the operand of "
- + "another expression its value is row 348's";
+ return label + " returns a decimal, which fuses as a projection's output and as a decimal "
+ + "operand; its casts to other types are rows 350 and 366";
}
/** The two {@code TIME} functions whose value is a decimal (`VARKA-157.md` 2.3). */
@@ -623,10 +622,10 @@ static boolean isDecimalProducer(StaticInvoke si) {
}
/**
- * The unscaled value of a decimal-valued {@code TIME} function at an output root, or empty with
- * the reason noted (`VARKA-157.md` 2.3). Both are non-negative and within their precision for
- * every time of day, so neither needs a guard, and every divisor is proven in
- * {@code long_divide.smt2}.
+ * The unscaled value of a decimal-valued {@code TIME} function, at an output root or as a
+ * decimal operand, or empty with the reason noted (`VARKA-157.md` 2.3). Both are non-negative
+ * and within their precision for every time of day, so neither needs a guard, and every divisor
+ * is proven in {@code long_divide.smt2}.
*
*
* - {@code time_to_seconds(t)}, a {@code DECIMAL(14, 6)}: {@code (n + 500) / 1000}, Spark's
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalConformanceSuite.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalConformanceSuite.java
index 2b8ec4566986..6b08e6957f71 100644
--- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalConformanceSuite.java
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalConformanceSuite.java
@@ -18,6 +18,7 @@
package org.apache.spark.sql.catalyst.expressions.codegen.varka;
import java.math.BigInteger;
+import java.util.Set;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.DecimalType;
@@ -72,4 +73,17 @@ protected ConformanceType type() {
protected BigInteger[] decimalSlots() {
return VALUES;
}
+
+ /**
+ * The operators the census marks fused in part for {@code dec} because the long fuses them and
+ * the pair does not: the values, each a projection's output at this suite's
+ * {@code DECIMAL(30, 4)}, which is row 359's two-word store - the choices, {@code greatest},
+ * {@code least}, the negation and {@code abs} (row 348), and the sums and differences (row 349;
+ * the pair's are row 360's).
+ */
+ @Override
+ protected Set declinesInPart() {
+ return Set.of("if", "when", "coalesce", "nullif", "greatest", "negative", "abs", "+", "-",
+ "try_add", "least", "try_subtract");
+ }
}
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalLongConformanceSuite.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalLongConformanceSuite.java
index 5f0366296ef3..060522f1906a 100644
--- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalLongConformanceSuite.java
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalLongConformanceSuite.java
@@ -18,6 +18,7 @@
package org.apache.spark.sql.catalyst.expressions.codegen.varka;
import java.math.BigInteger;
+import java.util.Set;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.DecimalType;
@@ -33,8 +34,11 @@
*
*
The values are the precision's bounds and their neighbours and zero and one each way. The
* census marks the comparisons and {@code IN} fused in part for {@code dec}: this representation
- * fuses them at every scale (rows 348 and 497), the pair at one, so both are checked here; every
- * other form the census owes must decline.
+ * fuses them at every scale (rows 348 and 497), the pair at one, so both are checked here. So it
+ * marks the values this representation stores and the pair does not: the choices,
+ * {@code greatest}, {@code least}, the negation and {@code abs} (row 348), and the sums and
+ * differences (row 349), each checked here as a projection's output. Every other form the census
+ * owes must decline.
*
*
In its own JVM, as the long-lane suites are ({@link VarkaSpeciesGuard}).
*/
@@ -61,4 +65,14 @@ protected ConformanceType type() {
protected BigInteger[] decimalSlots() {
return VALUES;
}
+
+ /**
+ * The sum and difference of two values within 10 digits fit the result type's 11, and the
+ * negation and {@code abs} stay within the operand's 10, so Spark never raises on them, whatever
+ * the mode; only the product, past 18 digits, leaves the long.
+ */
+ @Override
+ protected boolean overflowReachable(String register) {
+ return !Set.of("+", "-", "negative", "abs", "try_add", "try_subtract").contains(register);
+ }
}
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalOutputSuite.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalOutputSuite.java
new file mode 100644
index 000000000000..82c943287caa
--- /dev/null
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalOutputSuite.java
@@ -0,0 +1,404 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.expressions.codegen.varka;
+
+import static org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaDecimalStoreTables.label;
+import static org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaDecimalValueSuite.seq;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.vector.DecimalVector;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import org.apache.spark.sql.catalyst.expressions.Attribute;
+import org.apache.spark.sql.catalyst.expressions.Expression;
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow;
+import org.apache.spark.sql.catalyst.expressions.NamedExpression;
+import org.apache.spark.sql.catalyst.expressions.codegen.CompiledVarkaProjection;
+import org.apache.spark.sql.catalyst.expressions.codegen.VarkaExpressionCompiler;
+import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaEmitOptions.DecimalStore;
+import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.WidenDecimal;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.util.ArrowUtils;
+import org.apache.spark.sql.vectorized.ArrowColumnVector;
+
+/**
+ * A decimal value within 18 digits as a projection's output (VARKA-348 2.4, part 348b): every
+ * form {@code VarkaDecimalCompiler.value} builds is written by the decimal store, so the output
+ * root is {@code WidenDecimal} over the value a comparison would read. The value under the store
+ * is run as a long output, at one, two, four and eight long lanes, over the precision's ends,
+ * values one unit inside them, zero, one each way and every null pattern of two operands, and
+ * held row by row to Spark's own {@code eval} of the same expression at the output's scale; and
+ * the whole root, the store over the decimal columns' leaves, is run into a {@code DecimalVector}
+ * of the output's type under both store arms, read back by Spark's {@code ArrowColumnVector}. The
+ * store's bytes over long columns are {@link VarkaDecimalStoreSuite}'s. In a JVM of its own, for
+ * the several species (VARKA-246).
+ */
+@VarkaSuite(ownJvm = true)
+public final class VarkaDecimalOutputSuite {
+
+ private static final int[] WIDTHS = {1, 2, 4, 8};
+ private static final DecimalType D9 = new DecimalType(9, 2);
+ private static final DecimalType D9S4 = new DecimalType(9, 4);
+ private static final DecimalType D18 = new DecimalType(18, 2);
+
+ /** A row of the two columns: each one's unscaled value, or null. */
+ private record Row(Long a, Long b) { }
+
+ /** A form: its SQL over {@code a} and {@code b}, and the two columns' types. */
+ private record Shape(String sql, DecimalType ta, DecimalType tb) { }
+
+ /** The plan's projections (VARKA-348 3 item 4) and the choices and picks beside them. */
+ private static final List SHAPES = List.of(
+ new Shape("CASE WHEN a < b THEN a ELSE b END", D9, D9),
+ new Shape("CASE WHEN a < b THEN a END", D9, D9),
+ new Shape("if(a > b, a, b)", D18, D18),
+ new Shape("coalesce(a, b)", D9, D9S4),
+ new Shape("coalesce(a, 1.5)", D18, D18),
+ new Shape("greatest(a, b)", D18, D18),
+ new Shape("least(a, b)", D9, D9S4),
+ new Shape("nullif(a, b)", D9, D9),
+ new Shape("-a", D18, D18),
+ new Shape("abs(a)", D18, D18),
+ new Shape("abs(b)", D9, D9S4),
+ new Shape("-greatest(a, b)", D9, D9S4),
+ new Shape("CAST(a AS DECIMAL(18, 4))", D9, D9));
+
+ /** The sums and differences within 18 digits, row 349's arithmetic stored by the same path. */
+ private static final List ARITHMETIC = List.of(
+ new Shape("a + b", D9, D9S4),
+ new Shape("a - b", D9, D9),
+ new Shape("try_subtract(a, b)", D9, D9S4));
+
+ private static long bound(DecimalType t) {
+ return Decimal.POW_10()[t.precision()] - 1L;
+ }
+
+ /** The precision's ends, one unit inside them, zero and one each way. */
+ private static List edges(DecimalType t) {
+ long top = bound(t);
+ return List.copyOf(new LinkedHashSet<>(List.of(0L, 1L, -1L, top, -top, top - 1, -top + 1)));
+ }
+
+ /** Every ordered pair of the two types' edges, then every null pattern beside a few. */
+ private static List rows(DecimalType ta, DecimalType tb) {
+ var rows = new ArrayList();
+ for (long a : edges(ta)) {
+ for (long b : edges(tb)) {
+ rows.add(new Row(a, b));
+ }
+ }
+ for (long v : List.of(0L, 1L, -1L)) {
+ rows.add(new Row(null, v));
+ rows.add(new Row(v, null));
+ }
+ rows.add(new Row(null, null));
+ return rows;
+ }
+
+ @Test
+ @DisplayName("each decimal value is a projection's output through the decimal store, at the "
+ + "expression's type, and answers as Spark at every width")
+ void valuesAnswerAsSpark() {
+ for (Shape s : SHAPES) {
+ check(s, VarkaMatrixRuns.BASE);
+ }
+ }
+
+ @Test
+ @DisplayName("abs as an output answers as Spark under both lowerings, the blend and the "
+ + "lanewise ABS of decimalAbsLanewise")
+ void absUnderBothLowerings() {
+ VarkaEmitOptions lanewise = VarkaMatrixRuns.BASE.toBuilder().decimalAbsLanewise(true).build();
+ for (Shape s : List.of(new Shape("abs(a)", D18, D18), new Shape("abs(b)", D9, D9S4),
+ new Shape("abs(-a)", D9, D9))) {
+ check(s, VarkaMatrixRuns.BASE);
+ check(s, lanewise);
+ }
+ }
+
+ @Test
+ @DisplayName("a sum or difference within 18 digits is an output by the same path, its rescale "
+ + "inside")
+ void arithmeticAnswersAsSpark() {
+ for (Shape s : ARITHMETIC) {
+ check(s, VarkaMatrixRuns.BASE);
+ }
+ }
+
+ @Test
+ @DisplayName("the store over a decimal column's value writes the slots Spark's reader reads back "
+ + "as Spark's answer, under both store arms and at every width")
+ void storedOverDecimalLeaves() {
+ for (Shape s : List.of(SHAPES.get(0), SHAPES.get(3), SHAPES.get(7), SHAPES.get(9),
+ ARITHMETIC.get(0))) {
+ List columns = columns(s);
+ Expression e = VarkaSqlResolve.parse(s.sql(), seq(columns));
+ var type = (DecimalType) e.dataType();
+ Expression bound = VarkaSqlResolve.bind(VarkaSqlResolve.replaced(e), seq(columns));
+ List rows = rows(s.ta(), s.tb());
+ for (DecimalStore arm : DecimalStore.values()) {
+ for (int lanes : WIDTHS) {
+ VarkaEmitOptions options = VarkaMatrixRuns.BASE.withDecimalStore(arm)
+ .withLanesOverride(lanes);
+ CompiledVarkaProjection compiled = VarkaExpressionCompiler.compile(out(e),
+ seq(columns), options).orElseThrow(() -> new AssertionError(s + " does not fuse"));
+ Decimal[] got = stored(compiled, rows, s, type, options);
+ for (int i = 0; i < rows.size(); i++) {
+ Row r = rows.get(i);
+ Object spark = bound.eval(new GenericInternalRow(new Object[] {
+ decimal(r.a(), s.ta()), decimal(r.b(), s.tb())}));
+ int row = i;
+ assertEquals(spark, got[i], () -> s + " stored by " + arm + " at " + label(lanes)
+ + ", row " + r + " at " + row);
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("a constant decimal output and a typed null fuse beside a column's value, each "
+ + "under the store")
+ void constantsBesideAColumn() {
+ List columns = columns(new Shape("", D9, D9));
+ var entries = new ArrayList();
+ for (String sql : List.of("-a", "CAST(1.25 AS DECIMAL(9, 2))", "CAST(NULL AS DECIMAL(9, 2))")) {
+ entries.add(VarkaSqlResolve.named(VarkaSqlResolve.parse(sql, seq(columns)), "c"));
+ }
+ CompiledVarkaProjection compiled = VarkaExpressionCompiler.compile(
+ scala.jdk.javaapi.CollectionConverters.asScala(entries).toSeq(), seq(columns),
+ VarkaMatrixRuns.BASE).orElseThrow(() -> new AssertionError("the three do not fuse"));
+ assertEquals(3, compiled.outputs().size(), () -> compiled.toString());
+ for (VarkaVectorIR root : compiled.outputs()) {
+ assertInstanceOf(WidenDecimal.class, root, () -> compiled.toString());
+ }
+ assertEquals(List.of(D9, D9, D9), compiled.outputTypes());
+ }
+
+ @Test
+ @DisplayName("an output whose type passes 18 digits declines naming row 359, before its value "
+ + "is compiled")
+ void wideOutputDeclines() {
+ var wide = new DecimalType(18, 0);
+ for (Shape s : List.of(new Shape("coalesce(a, b)", wide, D18),
+ new Shape("a + b", D18, D18), new Shape("if(a < b, a, b)", wide, D9S4))) {
+ List columns = columns(s);
+ Expression e = VarkaSqlResolve.parse(s.sql(), seq(columns));
+ assertTrue(((DecimalType) e.dataType()).precision() > 18, () -> s + ": " + e.dataType());
+ String reason = decline(e, columns);
+ assertTrue(reason.contains("359"), () -> s + ": " + reason);
+ }
+ }
+
+ private static List columns(Shape s) {
+ return List.of(VarkaSqlResolve.column("a", s.ta()), VarkaSqlResolve.column("b", s.tb()));
+ }
+
+ private static scala.collection.immutable.Seq out(Expression e) {
+ return scala.jdk.javaapi.CollectionConverters.asScala(
+ List.of(VarkaSqlResolve.named(e, "c"))).toSeq();
+ }
+
+ private static String decline(Expression e, List columns) {
+ var declines = VarkaExpressionCompiler.declines(out(e), seq(columns), VarkaMatrixRuns.BASE);
+ return declines.isEmpty() ? "fused" : declines.get(declines.firstKey()).reason();
+ }
+
+ /**
+ * Compiles {@code s} as a projection's one output under {@code options}, checks its root is
+ * the store over a long value at the expression's type, runs that value at every width over
+ * {@link #rows}, and holds each row to Spark's evaluation, {@code nullif} replaced as it has no
+ * evaluation of its own.
+ */
+ private static void check(Shape s, VarkaEmitOptions options) {
+ List columns = columns(s);
+ Expression e = VarkaSqlResolve.parse(s.sql(), seq(columns));
+ var type = (DecimalType) e.dataType();
+ CompiledVarkaProjection compiled = VarkaExpressionCompiler.compile(out(e), seq(columns),
+ options).orElseThrow(() -> new AssertionError(s + " does not fuse: "
+ + decline(e, columns)));
+ assertEquals(List.of(type), compiled.outputTypes(), () -> s.toString());
+ assertTrue(compiled.literals().isEmpty(), () -> s + " holds int literals: " + compiled);
+ WidenDecimal root = assertInstanceOf(WidenDecimal.class, compiled.outputs().get(0),
+ () -> s.toString());
+ Expression bound = VarkaSqlResolve.bind(VarkaSqlResolve.replaced(e), seq(columns));
+ List rows = rows(s.ta(), s.tb());
+ for (int lanes : WIDTHS) {
+ Long[] got = run(compiled, root.child(), rows, s, options.withLanesOverride(lanes));
+ for (int i = 0; i < rows.size(); i++) {
+ Row r = rows.get(i);
+ Object spark = bound.eval(new GenericInternalRow(new Object[] {decimal(r.a(), s.ta()),
+ decimal(r.b(), s.tb())}));
+ Long want = spark == null ? null : ((Decimal) spark).toJavaBigDecimal()
+ .setScale(type.scale()).unscaledValue().longValueExact();
+ int row = i;
+ assertEquals(want, got[i], () -> s + " under " + options.canonical() + " at "
+ + label(lanes) + ", row " + r + " at " + row);
+ }
+ }
+ }
+
+ private static Decimal decimal(Long unscaled, DecimalType t) {
+ return unscaled == null ? null
+ : Decimal.apply(BigDecimal.valueOf(unscaled, t.scale()), t.precision(), t.scale());
+ }
+
+ /**
+ * Runs {@code value}, the long under the store, as the kernel's one long output over the
+ * columns {@code a} and {@code b} holding {@code rows}, and returns each row's long, or null
+ * where it is not valid.
+ */
+ private static Long[] run(CompiledVarkaProjection compiled, VarkaVectorIR value,
+ List rows, Shape s, VarkaEmitOptions options) {
+ long[] lits = new long[compiled.longLiterals().size()];
+ for (int i = 0; i < lits.length; i++) {
+ lits[i] = compiled.longLiterals().get(i);
+ }
+ List ordinals = compiled.inputOrdinals();
+ var emitted = VarkaEmitterFixtures.emit(List.of(value), ordinals.size(), lits.length,
+ options);
+ VarkaFusedKernel kernel = VarkaEmitterFixtures.load(emitted).kernel();
+ int length = rows.size();
+ int inputs = ordinals.size();
+ try (BufferAllocator allocator =
+ ArrowUtils.rootAllocator().newChildAllocator("varka-decimal-output", 0, Long.MAX_VALUE);
+ DecimalVector va = vector("a", rows, true, s.ta(), allocator);
+ DecimalVector vb = vector("b", rows, false, s.tb(), allocator);
+ var arena = Arena.ofConfined()) {
+ DecimalVector[] byOrdinal = {va, vb};
+ long[] srcData = new long[inputs];
+ long[] srcValidity = new long[inputs];
+ int[] nullCounts = new int[inputs];
+ long[] inStride = new long[inputs];
+ for (int i = 0; i < inputs; i++) {
+ DecimalVector v = byOrdinal[ordinals.get(i)];
+ srcData[i] = v.getDataBuffer().memoryAddress();
+ nullCounts[i] = v.getNullCount();
+ srcValidity[i] = nullCounts[i] == length ? 0L : v.getValidityBuffer().memoryAddress();
+ inStride[i] = 16L;
+ }
+ long wordBytes = ((length + 63) / 64) * 8L;
+ MemorySegment out = arena.allocate(length * 8L, 64);
+ MemorySegment outValid = arena.allocate(wordBytes, 64);
+ long[] outData = {out.address()};
+ long[] outValidity = {outValid.address()};
+ long[] outStride = {8L};
+ int status = VarkaKernelChecks.sanitized(kernel, length, inStride, outStride, srcData,
+ srcValidity, outData, outValidity,
+ scratch -> kernel.run(srcData, srcValidity, nullCounts, outData, outValidity,
+ new int[0], lits, length, scratch));
+ assertEquals(0, status, "an in-precision batch runs");
+ var got = new Long[length];
+ for (int i = 0; i < length; i++) {
+ boolean valid = (outValid.get(ValueLayout.JAVA_LONG, (i >>> 6) * 8L) >>> (i & 63) & 1L)
+ != 0;
+ got[i] = valid ? out.get(ValueLayout.JAVA_LONG, i * 8L) : null;
+ }
+ return got;
+ }
+ }
+
+ /**
+ * Runs {@code compiled}'s one root, the store, over the columns {@code a} and {@code b} into a
+ * {@code DecimalVector} of {@code type}, and returns each row as Spark's reader reads it.
+ */
+ private static Decimal[] stored(CompiledVarkaProjection compiled, List rows, Shape s,
+ DecimalType type, VarkaEmitOptions options) {
+ long[] lits = new long[compiled.longLiterals().size()];
+ for (int i = 0; i < lits.length; i++) {
+ lits[i] = compiled.longLiterals().get(i);
+ }
+ List ordinals = compiled.inputOrdinals();
+ var emitted = VarkaEmitterFixtures.emit(compiled.outputs(), ordinals.size(), lits.length,
+ options);
+ VarkaFusedKernel kernel = VarkaEmitterFixtures.load(emitted).kernel();
+ int length = rows.size();
+ int inputs = ordinals.size();
+ try (BufferAllocator allocator =
+ ArrowUtils.rootAllocator().newChildAllocator("varka-decimal-stored", 0, Long.MAX_VALUE);
+ DecimalVector va = vector("a", rows, true, s.ta(), allocator);
+ DecimalVector vb = vector("b", rows, false, s.tb(), allocator);
+ DecimalVector out = new DecimalVector("c", allocator, type.precision(), type.scale())) {
+ out.allocateNew(length);
+ // A pattern whose high word is no sign extension, so a slot left unwritten is seen.
+ for (int i = 0; i < length; i++) {
+ out.getDataBuffer().setLong(i * 16L, 0x5A5A5A5A5A5A5A5AL);
+ out.getDataBuffer().setLong(i * 16L + 8, 0x0123456789ABCDEFL);
+ }
+ DecimalVector[] byOrdinal = {va, vb};
+ long[] srcData = new long[inputs];
+ long[] srcValidity = new long[inputs];
+ int[] nullCounts = new int[inputs];
+ long[] inStride = new long[inputs];
+ for (int i = 0; i < inputs; i++) {
+ DecimalVector v = byOrdinal[ordinals.get(i)];
+ srcData[i] = v.getDataBuffer().memoryAddress();
+ nullCounts[i] = v.getNullCount();
+ srcValidity[i] = nullCounts[i] == length ? 0L : v.getValidityBuffer().memoryAddress();
+ inStride[i] = 16L;
+ }
+ long[] outData = {out.getDataBuffer().memoryAddress()};
+ long[] outValidity = {out.getValidityBuffer().memoryAddress()};
+ long[] outStride = {16L};
+ int status = VarkaKernelChecks.sanitized(kernel, length, inStride, outStride, srcData,
+ srcValidity, outData, outValidity,
+ scratch -> kernel.run(srcData, srcValidity, nullCounts, outData, outValidity,
+ new int[0], lits, length, scratch));
+ assertEquals(0, status, "an in-precision batch runs");
+ out.setValueCount(length);
+ var spark = new ArrowColumnVector(out);
+ var got = new Decimal[length];
+ for (int i = 0; i < length; i++) {
+ got[i] = spark.isNullAt(i) ? null
+ : spark.getDecimal(i, type.precision(), type.scale());
+ }
+ return got;
+ }
+ }
+
+ private static DecimalVector vector(String name, List rows, boolean left,
+ DecimalType type, BufferAllocator allocator) {
+ var v = new DecimalVector(name, allocator, type.precision(), type.scale());
+ v.allocateNew(rows.size());
+ for (int i = 0; i < rows.size(); i++) {
+ Long u = left ? rows.get(i).a() : rows.get(i).b();
+ if (u == null) {
+ v.setNull(i);
+ } else {
+ v.getDataBuffer().setLong(i * 16L, u);
+ v.getDataBuffer().setLong(i * 16L + 8, u >> 63);
+ v.setIndexDefined(i);
+ }
+ }
+ v.setValueCount(rows.size());
+ return v;
+ }
+}
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalRefinementFile.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalRefinementFile.java
index 3393e12a26f9..684b4a02fe4b 100644
--- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalRefinementFile.java
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaDecimalRefinementFile.java
@@ -37,6 +37,7 @@
import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaSmtNodes.Outcome;
import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaSmtTerm.Quot;
import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaSmtTerm.Var;
+import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.WidenDecimal;
import org.apache.spark.sql.internal.SQLConf;
import org.apache.spark.sql.internal.SQLConf$;
import org.apache.spark.sql.types.DataTypes;
@@ -64,9 +65,9 @@ private VarkaDecimalRefinementFile() {
static final String IN_SET = "d18 IN (11 to 16 decimal literals)";
/**
- * The rows of {@code VarkaCoverageSuite}'s families "DECIMAL columns" (VARKA-347, VARKA-348)
- * and "DECIMAL arithmetic" (VARKA-349), in its order; that suite fails a row of either family
- * this file does not echo, so the list cannot fall behind the table.
+ * The rows of {@code VarkaCoverageSuite}'s families "DECIMAL columns" (VARKA-347, VARKA-348),
+ * "DECIMAL arithmetic" (VARKA-349) and "DECIMAL values" (VARKA-348b), in its order; that suite
+ * fails a row of any of them this file does not echo, so the list cannot fall behind the table.
*/
static final List SHAPES = List.of("d9 < d9b", "d9 <= d9b", "d9 > d9b", "d9 >= d9b",
"d9 = d9b", "d9 <> d9b", "d9 <=> d9b", "d9 = 0.42", "d9 < d18", "d18 < d18b", "d18 = d18b",
@@ -77,7 +78,9 @@ private VarkaDecimalRefinementFile() {
"CASE WHEN d9 < d9b THEN d9 ELSE d9s4 END > 0.0", "d9 IN (0.42, 0.00, -1.25)",
"d9 IN (0.425, 1.5)", IN_SET, "d9 + d9b < d18", "d9 - d8 >= d9b", "d8 * d9 <= d9b",
"try_add(d9, d9b) > d18", "d9 * 0.5 > d9b", "d9 + 1.5 < d9b", "d9 - d9s4 > 0.00",
- "d9 + d16s9 > d9s4", "-(d9 + d9b) = d9s4", "try_multiply(d8, d9) IS NULL");
+ "d9 + d16s9 > d9s4", "-(d9 + d9b) = d9s4", "try_multiply(d8, d9) IS NULL",
+ "CASE WHEN d9 < d9b THEN d9 ELSE d9b END", "if(d9 < d9b, d18, d18b)", "coalesce(d9, d9s4)",
+ "greatest(d18, d18b)", "least(d9, d9s4)", "-d18", "abs(d18)", "try_subtract(d9, d9s4)");
private static Attribute column(String name, int precision, int scale) {
return VarkaSqlResolve.column(name, DataTypes.createDecimalType(precision, scale));
@@ -111,14 +114,15 @@ static String render() {
var out = new StringBuilder(VarkaProofFiles.LICENSE);
out.append("""
; The 64-bit decimal kernels refined against Spark (VARKA-506 2.6). Per coverage row of the
- ; families "DECIMAL columns" and "DECIMAL arithmetic", compiled as VarkaCoverageSuite
- ; compiles it under an ANSI and a LEGACY session: the kernel printed by VarkaSmtNodes from
- ; the IR the compiler built, its decline the emitter's guards on the lanes Analysis
- ; qualifies them by, every long in the word form with its obligations; and the
- ; specification read from Spark's analyzed expression into decimal_spec.smt2's spec.dec.*,
- ; a column's valid slot past its precision raising as Spark's reader does, a result past
- ; its type's precision raising under ANSI and null otherwise. The five checks are
- ; refinement.smt2's; a row whose two sessions print alike is checked once.
+ ; families "DECIMAL columns", "DECIMAL arithmetic" and "DECIMAL values", compiled as
+ ; VarkaCoverageSuite compiles it under an ANSI and a LEGACY session (a predicate as a
+ ; filter's condition, a value as a projection's output): the kernel printed by
+ ; VarkaSmtNodes from the IR the compiler built, its decline the emitter's guards on the
+ ; lanes Analysis qualifies them by, every long in the word form with its obligations;
+ ; and the specification read from Spark's analyzed expression into decimal_spec.smt2's
+ ; spec.dec.*, a column's valid slot past its precision raising as Spark's reader does, a
+ ; result past its type's precision raising under ANSI and null otherwise. The five checks
+ ; are refinement.smt2's; a row whose two sessions print alike is checked once.
;
; Refused, each keeping the verification VarkaCoverageSuite names for it:
""");
@@ -164,12 +168,13 @@ private static List checks(String sql, boolean ansi) {
Outcome o = printer.kernel(root, VarkaLoopEmitter.guardsForTest(k.outputs(),
k.inputOrdinals().size(), k.numLiterals(), VarkaEmitOptions.DEFAULTS));
var words = new VarkaSmtTerm.WordForm();
- Outcome p = VarkaSmtSamples.printed(o, root, words);
+ // A decimal store's data is the stored value, read signed as the specification's is; a
+ // long root's printed data is the unsigned reading, which a predicate's boolean never meets.
+ Outcome p = root instanceof WidenDecimal
+ ? new Outcome(words.term(o.decline()), words.term(o.valid()), words.term(o.data()))
+ : VarkaSmtSamples.printed(o, root, words);
var spec = new Spec(k.inputOrdinals());
Spec.Value s = spec.of(e);
- if (s.precision() >= 0) {
- throw new Refused("not a predicate");
- }
String raises = Spec.or(s.raise(), Spec.any(spec.reads));
var setup = setup(printer.facts, spec.ordinals, List.of(p.decline(), p.valid(), p.data()),
words.obligations);
@@ -209,15 +214,30 @@ private static Expression expression(String sql) {
return new InSet(COLUMNS.get(2), CollectionConverters.asScala(set).toSet());
}
- /** The row's one fused kernel, as {@code VarkaCoverageSuite} compiles a predicate row. */
+ /**
+ * The row's one fused kernel, as {@code VarkaCoverageSuite} compiles it: a predicate row as a
+ * filter's condition, a decimal-valued row as a projection's one output, whose root is the
+ * decimal store over the value ({@code WidenDecimal}, which the printer reads through).
+ */
private static CompiledVarkaProjection kernelOf(String sql, Expression e) {
- CompiledVarkaPredicate p = VarkaExpressionCompiler.compilePredicate(e,
- CollectionConverters.asScala(COLUMNS).toSeq(), VarkaEmitOptions.DEFAULTS,
- VarkaAdmission.NO_HOST_REFUSAL).orElseThrow(() -> new Refused("it does not compile"));
- CompiledVarkaProjection k = p.fused();
- if (!p.specs().stream().allMatch(VarkaConjunctSpec::fused) || p.clauses().size() != 1
- || k.outputs().size() != 1) {
- throw new Refused("not one fused root");
+ var columns = CollectionConverters.asScala(COLUMNS).toSeq();
+ CompiledVarkaProjection k;
+ if (e.dataType() instanceof DecimalType) {
+ k = VarkaExpressionCompiler.compile(CollectionConverters.asScala(
+ List.of(VarkaSqlResolve.named(e, "c"))).toSeq(), columns, VarkaEmitOptions.DEFAULTS)
+ .orElseThrow(() -> new Refused("it does not compile"));
+ if (k.outputs().size() != 1) {
+ throw new Refused("not one fused root");
+ }
+ } else {
+ CompiledVarkaPredicate p = VarkaExpressionCompiler.compilePredicate(e, columns,
+ VarkaEmitOptions.DEFAULTS, VarkaAdmission.NO_HOST_REFUSAL)
+ .orElseThrow(() -> new Refused("it does not compile"));
+ k = p.fused();
+ if (!p.specs().stream().allMatch(VarkaConjunctSpec::fused) || p.clauses().size() != 1
+ || k.outputs().size() != 1) {
+ throw new Refused("not one fused root");
+ }
}
if (!k.inputBounds().isEmpty() || !k.derivedInputs().isEmpty()) {
throw new Refused("an input bound or a derived input, which the printer does not read");
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelChecks.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelChecks.java
index 561da37f3f38..a4cba657ec89 100644
--- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelChecks.java
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelChecks.java
@@ -671,12 +671,11 @@ public static int runLoadedNarrow(String context, VarkaFusedKernel kernel,
public static int runLoadedDecimal(String context, VarkaFusedKernel kernel,
List roots, int numInputs, long[] lits, int[] intLits, LongBatch batch,
BigInteger[] values, boolean declineAllowed, SparkAnswers spark, CallHook hook) {
- // The slot lane writes long outputs alone: a decimal store, a narrowing root and a kernel
- // of both lanes need the long lane's handling of them, which it does not carry yet.
- if (holdsBothLanes(roots) || roots.stream().anyMatch(r -> r instanceof WidenDecimal
- || r instanceof NarrowLane)) {
- throw new IllegalArgumentException(context + ": the decimal slot lane checks long and "
- + "condition outputs only, not " + roots);
+ // The slot lane writes long and decimal-store outputs and conditions: a narrowing root and a
+ // kernel of both lanes need the long lane's handling of them, which it does not carry yet.
+ if (holdsBothLanes(roots) || roots.stream().anyMatch(r -> r instanceof NarrowLane)) {
+ throw new IllegalArgumentException(context + ": the decimal slot lane checks long, "
+ + "decimal-store and condition outputs only, not " + roots);
}
return runLoaded(context, kernel, roots, numInputs,
new DecimalSlotLane(batch, lits, intLits, values, numInputs, new IdentityHashMap<>()),
@@ -1210,10 +1209,24 @@ private VarkaVectorIR asColumns(VarkaVectorIR node) {
return VarkaReference.longCond((Cond) asColumns(cond), words(row), twice(isNull), lits);
}
+ @Override public long outputStride(VarkaVectorIR root, VarkaVectorIR.LaneType rootLane) {
+ return root instanceof WidenDecimal ? DECIMAL_SLOT : stride();
+ }
+
+ @Override public void putOutput(VarkaVectorIR root, VarkaVectorIR.LaneType rootLane,
+ MemorySegment d, int i, long v) {
+ if (root instanceof WidenDecimal) {
+ putSlot(d, i, v);
+ } else {
+ put(d, i, v);
+ }
+ }
+
@Override public long got(MemorySegment out, int i, VarkaVectorIR root,
VarkaVectorIR.LaneType rootLane) {
- // runLoadedDecimal refuses a narrowing root, so every output is a long a row.
- return out.get(ValueLayout.JAVA_LONG, i * 8L);
+ // runLoadedDecimal refuses a narrowing root, so an output is a decimal slot or a long.
+ return root instanceof WidenDecimal ? slot(out, i)
+ : out.get(ValueLayout.JAVA_LONG, i * 8L);
}
}
diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaTypeConformance.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaTypeConformance.java
index 511bfd3310cb..0b6ac83774e2 100644
--- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaTypeConformance.java
+++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaTypeConformance.java
@@ -392,17 +392,17 @@ void overflow() {
var forms = new ArrayList