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
1 change: 1 addition & 0 deletions SKILLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ the pre-commit hook also checks. Groups below are in file order.
* [After a warm-up's `RELEASED` verdict, the "once compiled" rows measure the row engine](sql/varka/skills/benchmarking.md#after-a-warm-ups-released-verdict-the-once-compiled-rows-measure-the-row-engine)
* [Spark's codegen cache: what a compile count and a cache hit measure](sql/varka/skills/benchmarking.md#sparks-codegen-cache-what-a-compile-count-and-a-cache-hit-measure)
* [An Arm benchmark is a dispatch of `benchmark.yml` with `runner=ubuntu-24.04-arm`](sql/varka/skills/benchmarking.md#an-arm-benchmark-is-a-dispatch-of-benchmarkyml-with-runnerubuntu-2404-arm)
* [A probe pass whose fused control loses is not read](sql/varka/skills/benchmarking.md#a-probe-pass-whose-fused-control-loses-is-not-read)
* [A dispatch of Varka classes only skips the TPC-DS data job](sql/varka/skills/benchmarking.md#a-dispatch-of-varka-classes-only-skips-the-tpc-ds-data-job)

#### [Build and environment](sql/varka/skills/build-and-environment.md)
Expand Down
2 changes: 1 addition & 1 deletion docs/sql-varka.md
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ bitmask, never a machine word or a token of text.
| **shape cache** | A bounded LRU of emitted classes keyed by shape, shared *across tasks*. The cost it saves is not emission - that is about 80 microseconds - but JIT warm-up: a re-defined class is a new class to HotSpot and re-pays the whole tier ladder, 13 to 50 ms per task. Reusing the loaded class is the only thing that avoids it. |
| **literal slot** | An index into the kernel's runtime argument array where a folded constant lives. Why the IR carries no literal *values*: keeping them out is what makes the shape the identity. |
| **selection bitmap** | A filter's output: one bit per row, set meaning the predicate is known true. An unknown row - a null under the comparison - reads as false by construction, which is SQL's `WHERE` semantics for free. |
| **partial eligibility** | A projection qualifies when *at least one* of its entries compiles. The rest are forwarded zero-copy or left to stock Spark, and the results merge. Eligibility is per entry, not all-or-nothing. |
| **partial eligibility** | A projection qualifies when *at least one* of its entries compiles. The rest are forwarded zero-copy or left to stock Spark, and the results merge. Eligibility is per entry, not all-or-nothing, with one exception: under a consumer that wants rows, a projection whose residual entries outnumber its fused ones is left whole to stock Spark, whose one whole-stage loop is then faster than the kernel and the per-row merge (VARKA-613). |
| **decline** | A compile-time refusal: the compiler cannot translate an expression, or the emitter will not build a shape. Declining is a normal outcome, not an error - the query runs on stock Spark instead. |
| **ghost fallback** | The run-time counterpart: if an emitted kernel fails on a batch, that batch is recomputed by the ordinary row engine and the query still returns the right answer. The Janino projection behind it is compiled lazily, only if some batch actually needs it. |
| **civil-from-days** | The calendar algorithm turning a day count since the epoch into year, month and day (Neri and Schneider's, transcribed in `sql/varka/papers`). Branch-free and 31 vector operations, which is why several outputs over one date share it. |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.execution;

import java.util.List;
import java.util.Optional;

import org.apache.spark.sql.catalyst.expressions.Alias;
import org.apache.spark.sql.catalyst.expressions.Expression;
import org.apache.spark.sql.catalyst.expressions.codegen.PartialVarkaProjection;
import org.apache.spark.sql.catalyst.expressions.codegen.VarkaOutputSpec;
import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaEmitOptions;

/**
* Whether a projection that fuses in part is left whole to Spark when its consumer wants rows
* (VARKA-613), and why: when its residual entries outnumber its fused ones and also outweigh
* them, an entry weighing the operators of its expression.
*
* <p>Under a row consumer such a projection runs its kernel over each batch, then builds every
* output row in a merge projection over the input row and the kernel's row, which evaluates the
* residual entries per row outside whole-stage code. Spark's own plan evaluates every entry in
* one whole-stage loop over the batch's vectors. So the kernel wins only where the work it takes
* off the row path outweighs the batch pass and the merge's indirection it adds, and with more
* residual entries than fused ones it does not: the day-time baseline's {@code extract} of four
* fields, of which only the day fuses, ran at 0.7x the row path at 256 bits and 0.5x at 128 on
* the runners, and the laptop probe ({@code VARKA-613.md} 9) found three fused arithmetic entries
* beside one residual entry over the same column a win, so whether the residual entries share
* the fused ones' columns does not decide it, the weight does. Both must hold, so the rule
* declines no shape the count alone kept, and one expensive fused entry beside two cheap residual
* ones, which the count would decline, keeps the kernel that carries most of the work.
*
* <p>The rule is asked only where the consumer is known to want rows, in
* {@link VarkaColumnarRule}'s post stage; a columnar consumer keeps every partial projection. A
* test's forced decline ({@link VarkaEmitOptions#forceResidualAt()}) is never declined here,
* since the force exists to run the merge path.
*/
public final class VarkaPartialDecline {

private VarkaPartialDecline() {
}

/**
* Why {@code partial} is left to Spark under a row consumer, or empty when it keeps its
* kernel: empty for a projection whose residual entries are no more in number or in weight than
* its fused ones, those of every kernel together, and under a forced decline.
* {@code projectList} is the projection's expressions, one per entry of
* {@code partial.specs()}. A forwarded column weighs nothing.
*/
public static Optional<String> reason(
PartialVarkaProjection partial, List<? extends Expression> projectList,
VarkaEmitOptions options) {
if (options.forceResidualAt() != 0) {
return Optional.empty();
}
int fused = 0;
int residual = 0;
int fusedWeight = 0;
int residualWeight = 0;
List<VarkaOutputSpec> specs = partial.specs();
for (int i = 0; i < specs.size(); i++) {
switch (specs.get(i)) {
case VarkaOutputSpec.FusedOutput f -> {
fused++;
fusedWeight += weight(projectList.get(i));
}
case VarkaOutputSpec.KernelOutput k -> {
fused++;
fusedWeight += weight(projectList.get(i));
}
case VarkaOutputSpec.ForwardedOutput f -> { }
case VarkaOutputSpec.ResidualOutput r -> {
residual++;
residualWeight += weight(projectList.get(i));
}
}
}
if (residual <= fused || residualWeight <= fusedWeight) {
return Optional.empty();
}
return Optional.of("fuses in part under a row consumer, and its residual entries outnumber "
+ "and outweigh its fused ones, " + residual + " entries of " + residualWeight
+ " operators to " + fused + " of " + fusedWeight + ", so the per-row merge would cost "
+ "more than the kernel saves (VARKA-613)");
}

/** The operators in {@code e}: its inner nodes, not counting an alias or a leaf. */
private static int weight(Expression e) {
int n = e instanceof Alias || e.children().isEmpty() ? 0 : 1;
var children = e.children();
for (int i = 0; i < children.size(); i++) {
n += weight(children.apply(i));
}
return n;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import scala.jdk.OptionConverters._

import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeSeq, BindReferences, Expression, NamedExpression}
import org.apache.spark.sql.catalyst.expressions.codegen.VarkaExpressionCompiler
import org.apache.spark.sql.catalyst.expressions.codegen.{PartialVarkaProjection, VarkaExpressionCompiler}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.adaptive.{QueryStageExec, TableCacheQueryStageExec}
import org.apache.spark.sql.execution.columnar.{ArrowCachedBatchSerializer, InMemoryTableScanExec}
Expand Down Expand Up @@ -57,7 +57,9 @@ import org.apache.spark.sql.vectorized.ArrowColumnVector
* - after transitions, a to-row transition that did get inserted above such a node is fused with
* it into a [[VarkaColumnarToRowExec]], which runs the same kernels and converts their output
* to rows in one node. That is the plan a row consumer got before this two-stage split existed,
* unchanged.
* unchanged, except that a projection whose residual entries outnumber its fused ones is left
* to Spark there ([[VarkaPartialDecline]]), since only there is the consumer known to want
* rows.
*
* The post stage also still matches a plain projection over a to-row transition, for a projection
* the pre stage did not see - another columnar rule may have introduced it, and post rules run in
Expand Down Expand Up @@ -106,18 +108,24 @@ object VarkaColumnarRule extends ColumnarRule with Logging {
if isForwardedNarrowing(projectList, filter.output) =>
VarkaFilterColumnarToRowExec(filter.condition, filter.child, Some(projectList),
filter.wholeCondition, filter.sessionEmit)
case ColumnarToRowExec(varka: VarkaProjectExec) =>
VarkaColumnarToRowExec(varka.projectList, varka.child, varka.sessionEmit)
// A projection that fuses in part is left whole to Spark under a row consumer when its
// residual entries outnumber its fused ones (`VarkaPartialDecline`): Spark's projection
// over its child's rows (`declinedChild`).
case ColumnarToRowExec(varka: VarkaProjectExec) => projectionToRows(varka)
case ColumnarToRowExec(varka: VarkaFilterExec) =>
VarkaFilterColumnarToRowExec(varka.condition, varka.child,
wholeCondition = varka.wholeCondition, sessionEmit = varka.sessionEmit)
// The same decline guards this arm, which a declined projection reaches as
// `ProjectExec(ColumnarToRowExec(child))` on any later pass: it stays the projection.
case project @ ProjectExec(projectList, child)
if isVarkaEligible(projectList, child.output) =>
val columnarChild = child match {
case ColumnarToRowExec(inner) => inner
case other => other
}
if (columnarChild.supportsColumnar) {
val session = VarkaSessionEmit.of(SQLConf.get)
if (columnarChild.supportsColumnar && partialDecline(
compilePartial(projectList, child.output, session), projectList, session).isEmpty) {
VarkaColumnarToRowExec(projectList, columnarChild)
} else {
project
Expand Down Expand Up @@ -224,10 +232,62 @@ object VarkaColumnarRule extends ColumnarRule with Logging {
// at least one entry compiles to the vector IR - nested chains, shared subtrees and
// predication included - with bare columns forwarded and the rest evaluated per row.
private def isVarkaEligible(
projectList: Seq[NamedExpression], childOutput: Seq[Attribute]): Boolean = {
val session = VarkaSessionEmit.of(SQLConf.get)
projectList: Seq[NamedExpression], childOutput: Seq[Attribute]): Boolean =
compilePartial(projectList, childOutput, VarkaSessionEmit.of(SQLConf.get)).isDefined

private def compilePartial(
projectList: Seq[NamedExpression],
childOutput: Seq[Attribute],
session: VarkaSessionEmit): Option[PartialVarkaProjection] =
VarkaExpressionCompiler.compilePartial(projectList, childOutput,
VarkaColumnarToRowExec.emitOptions(session), session.admission).isPresent
VarkaColumnarToRowExec.emitOptions(session), session.admission).toScala

/**
* A Varka projection under a row consumer: Spark's projection when the rule declines it, else
* its row node. A declined projection's own child may be a Varka projection, which the
* transition rule never wrapped, so [[declinedChild]] asks again there.
*/
private def projectionToRows(varka: VarkaProjectExec): SparkPlan =
partialDecline(varka.classification.toScala, varka.projectList, varka.sessionEmit) match {
case Some(_) => ProjectExec(varka.projectList, declinedChild(varka.child))
case None => VarkaColumnarToRowExec(varka.projectList, varka.child, varka.sessionEmit)
}

/**
* The rows a declined projection reads from `child`, its Varka node's columnar child, as the
* transition rule would have given them to a row projection: a source that also produces rows
* gives them itself, as it does for the session without Varka (an Arrow-cached scan, read as
* rows); a Varka filter becomes its to-row node, which reads the selection bitmap without
* compacting, as the arm for a filter under a transition builds it; any other columnar child
* gets a to-row transition. `transformUp` does not revisit what an arm returns, so the filter's
* node is built here rather than left to that arm.
*/
private def declinedChild(child: SparkPlan): SparkPlan = child match {
// A nested Varka projection is under a row consumer too, so it is asked the same question.
case inner: VarkaProjectExec => projectionToRows(inner)
case filter: VarkaFilterExec =>
VarkaFilterColumnarToRowExec(filter.condition, filter.child,
wholeCondition = filter.wholeCondition, sessionEmit = filter.sessionEmit)
case rows if rows.supportsRowBased => rows
case batches => ColumnarToRowExec(batches)
}

/**
* Why a projection, classified as `partial`, is left whole to Spark under a row consumer, or
* None when it keeps its kernel ([[VarkaPartialDecline]]). The reason is logged at DEBUG, as a
* filter left to Spark is: the plan holds no Varka node to show it in `EXPLAIN`.
*/
private def partialDecline(
partial: Option[PartialVarkaProjection],
projectList: Seq[NamedExpression],
session: VarkaSessionEmit): Option[String] = {
val reason = partial.flatMap { p =>
VarkaPartialDecline.reason(p, projectList.asJava,
VarkaColumnarToRowExec.emitOptions(session)).toScala
}
reason.foreach(why => logDebug(s"Varka leaves the projection " +
s"${projectList.map(_.sql).mkString(", ")} to Spark: it $why"))
reason
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ void decimalValuesDecline() {
assumeTrue(varka != null, "not x86: the refusal does not apply");
for (String n : List.of("", "n")) {
String query = "SELECT p" + n + " < p2" + n + " AS a, w" + n + " < w2" + n + " AS b, l" + n
+ " < l2" + n + " AS c FROM two_lane_default";
+ " < l2" + n + " AS c, l" + n + " <= l2" + n + " AS d FROM two_lane_default";
Dataset<Row> actual = varka.sql(query);
List<String> got = sorted(actual.collectAsList());
SparkPlan plan = actual.queryExecution().executedPlan();
Expand All @@ -194,7 +194,8 @@ void decimalValuesDecline() {
PartialVarkaProjection partial = (node instanceof VarkaProjectExec p
? p.classification() : ((VarkaColumnarToRowExec) node).classification())
.orElseThrow(() -> new AssertionError("no classification: " + clue));
// The two decimal entries are the row path's, with the reason; the long one is fused.
// The two decimal entries are the row path's, with the reason; the two long ones are
// fused, so the rule that leaves a residual-heavy projection to Spark keeps this one.
assertEquals(Set.of(0, 1), partial.declines().keySet(), clue);
for (VarkaDecline d : partial.declines().values()) {
assertEquals(VarkaKernelPlan.TWO_LANE_DECIMAL_VALUE_REASON, d.reason(), clue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,11 @@
* results file notes each section that fuses. A row that fuses more of a section sets its new
* class, so that its fusion cannot turn a baseline section into a fused one unnoticed. A section
* is {@code NONE} when no Varka node plans it and {@code WHOLE} when no row operator evaluates
* any of it. The projections row 103 fuses are {@code WHOLE} at both widths, the four extracts
* together {@code PARTIAL} (the DAY field fuses, the other three are row 103's later step), and
* the other projections but the blend control are {@code NONE}. So is the filter
* any of it. The projections row 103 fuses are {@code WHOLE} at both widths, and the other
* projections but the blend control are {@code NONE}. So are the four extracts together: only the
* DAY field would fuse (the other three are row 103's later step), and a projection that fuses
* in part under a row consumer with more residual entries than fused ones stays whole on the
* row path (VARKA-613), so both arms time the row path. So is the filter
* {@code extract(HOUR FROM dt) >= 12} at both densities: of it only the {@code IS NOT NULL}
* Spark infers of the column would fuse, and a filter fusing nothing else stays whole on the row
* path (VARKA-598), so both arms time the row path. Each
Expand Down Expand Up @@ -194,7 +196,7 @@ static List<Section> sections(boolean declinesLongConditions) {
out.add(new Section("extract DAY, HOUR, MINUTE and SECOND together" + density,
"SELECT extract(DAY FROM " + dt + ") AS a, extract(HOUR FROM " + dt + ") AS b, "
+ "extract(MINUTE FROM " + dt + ") AS c, extract(SECOND FROM " + dt + ") AS d"
+ from, Map.of(), Fusion.PARTIAL));
+ from, Map.of(), Fusion.NONE));
out.add(new Section("make_dt_interval(i, i2, i3)" + density,
"SELECT make_dt_interval(" + i + ", i2, i3) AS a" + from, Map.of(), Fusion.NONE));
out.add(new Section("make_dt_interval(i, i2, i3, s), DECIMAL(18, 6) seconds" + density,
Expand Down
Loading