Skip to content

[SPARK-2364][STREAMING] ShuffledDStream run tasks only when dstream has partition items - #1291

Closed
guowei2 wants to merge 540 commits into
apache:masterfrom
guowei2:master
Closed

guowei2 wants to merge 540 commits into
apache:masterfrom
guowei2:master

Conversation

@guowei2

@guowei2 guowei2 commented Jul 3, 2014

Copy link
Copy Markdown
Contributor

ShuffledDStream run tasks no matter whether dstream has partition items

this patch fixed it

@AmplabJenkins

Copy link
Copy Markdown

Can one of the admins verify this patch?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @guowei2 , two quick questions:

  1. Is there any situation where partitions will be 0?
  2. I don't think numPartitions can be set to 0, since HashPartitioner will be failed if Mod 0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1、for example:
u use NetworkInputDStream to receive data to generate BlockRDD. when it receive no blocks in validtime, then partitions will be 0

NetworkInputDStream's code here

override def compute(validTime: Time): Option[RDD[T]] = {
// If this is called for any time before the start time of the context,
// then this returns an empty RDD. This may happen when recovering from a
// master failure
if (validTime >= graph.startTime) {
val blockIds = ssc.scheduler.networkInputTracker.getBlockIds(id, validTime)
Some(new BlockRDD (ssc.sc, blockIds))
} else {
Some(new BlockRDD (ssc.sc, ArrayBlockId))
}
}

2、 when parent RDD partition num is 0 ,but ShuffledDStream also change into muti-partitions ,
then emtpy job will be running.

  what i do is when this happen ShuffledDStream also out 0 partition

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @jerryshao , if numPartitioner is set to 0, then partitioning will fail as partitions are calculated by doing (hashcode % numPartitions) and anything % 0 gives "java.lang.ArithmeticException: / by zero" error.

@tdas

tdas commented Jul 4, 2014

Copy link
Copy Markdown
Contributor

Please add a JIRA for this and add the JIRA number in the title (look at other pull request to figure out the style).

@tdas

tdas commented Jul 4, 2014

Copy link
Copy Markdown
Contributor

I have a high level question. Is it a big system overhead if the spark runs tasks when there is no data?

@guowei2 guowei2 changed the title FIX: ShuffledDStream run tasks only when dstream has partition items [SPARK-2364][STREAMING] ShuffledDStream run tasks only when dstream has partition items Jul 4, 2014
@guowei2

guowei2 commented Jul 4, 2014

Copy link
Copy Markdown
Contributor Author

when numPartitioner is set to 0, HashPartitioner would not be failed ,because getPartition method would not be called.

here is the DAGScheduler's code

if (partitions.size == 0) {
  return new JobWaiter[U](this, jobId, 0, resultHandler)
}

if partitionSize is 0, job does not really submit. this is why i set it to 0

@guowei2

guowei2 commented Jul 4, 2014

Copy link
Copy Markdown
Contributor Author

it is not a big system overhead. but user puzzled by this on monitor page : 4040
if there's no shuffle behavior,spark does not run tasks when there is no data.
why it has shuffle behavior be.

@jerryshao

Copy link
Copy Markdown
Contributor

It makes sense for the problem you addressed, but modified in ShuffleDStream seems like just a workaround method, not a good solution, since you may also face this problem when using other operators like cogroup, join.

@guowei2

guowei2 commented Jul 4, 2014

Copy link
Copy Markdown
Contributor Author

yeah, i agree with u.
how about i do the same in StateDStream ?

@tdas

tdas commented Jul 8, 2014

Copy link
Copy Markdown
Contributor

Actually, I think its worse if this is done for StateDStream, as in StateDStream the computation should be run even if there is no input data, as it is expected that the state update function is called on all the (key, state) pairs even if there is no new data.

Regarding the fundamental reason behind doing this change, it seems that it is a nice-to-have from the UI point of view, and not really a system optimization. Regarding that, I dont have a strong reasoning against this but I have found that it is more confusing to have no jobs show up in the UI, as it is not even clear whether anything is running at all.

@guowei2

guowei2 commented Jul 10, 2014

Copy link
Copy Markdown
Contributor Author

thanks for your comments.
i try to resolve this issue in another way, According to @jerryshao .
in this way,no job will be generated when no data in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A white space here between ==

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also after if and )

@jerryshao

Copy link
Copy Markdown
Contributor

Like @tdas said, it's a nice-to-have feature, modification may narrow the flexibility of current implementation, so TD, what's your opinion?

@guowei2

guowei2 commented Jul 11, 2014

Copy link
Copy Markdown
Contributor Author

i think narrowing the flexibility of current implementation need to judge.
i don't think it's only a nice-to-have feature,
i think the modification in TransformedDStream and UnionDStream also should be a improvement
and it does fix the situation.
if some place i modified does not suitable ,i'll be keeping improving it

@guowei2

guowei2 commented Jul 22, 2014

Copy link
Copy Markdown
Contributor Author

is there anything wrong with this patch?

kennyballou and others added 13 commits July 31, 2014 14:58
Fix several awkward wordings and grammatical issues in the following
documents:

*   docs/monitoring.md

*   docs/streaming-programming-guide.md

Author: kballou <kballou@devnulllabs.io>

Closes #1662 from kennyballou/grammar_fixes and squashes the following commits:

e1b8ad6 [kballou] Docs: monitoring, streaming programming guide
…tBy...

It should be more convenient if user can specify ascending and numPartitions when calling sortByKey.

Author: Rui Li <rui.li@intel.com>

Closes #1645 from lirui-intel/spark-2740 and squashes the following commits:

fb5d52e [Rui Li] SPARK-2740: allow user to specify ascending and numPartitions for sortByKey
Prior to this change, every PySpark task completion opened a new socket to the accumulator server, passed its updates through, and then quit. I'm not entirely sure why PySpark always sends accumulator updates, but regardless this causes a very rapid buildup of ephemeral TCP connections that remain in the TCP_WAIT state for around a minute before being cleaned up.

Rather than trying to allow these sockets to be cleaned up faster, this patch simply reuses the connection between tasks completions (since they're fed updates in a single-threaded manner by the DAGScheduler anyway).

The only tricky part here was making sure that the AccumulatorServer was able to shutdown in a timely manner (i.e., stop polling for new data), and this was accomplished via minor feats of magic.

I have confirmed that this patch eliminates the buildup of ephemeral sockets due to the accumulator updates. However, I did note that there were still significant sockets being created against the PySpark daemon port, but my machine was not able to create enough sockets fast enough to fail. This may not be the last time we've seen this issue, though.

Author: Aaron Davidson <aaron@databricks.com>

Closes #1503 from aarondav/accum and squashes the following commits:

b3e12f7 [Aaron Davidson] SPARK-2282: Reuse Socket for sending accumulator updates to Pyspark
…BroadcastNestedLoopJoin.

This PR resolves the following two tickets:

- [SPARK-2531](https://issues.apache.org/jira/browse/SPARK-2531): BNLJ currently assumes the build side is the right relation. This patch refactors some of its logic to take into account a BuildSide properly.
- [SPARK-2436](https://issues.apache.org/jira/browse/SPARK-2436): building on top of the above, we simply use the physical size statistics (if available) of both relations, and make the smaller relation the build side in the planner.

Author: Zongheng Yang <zongheng.y@gmail.com>

Closes #1448 from concretevitamin/bnlj-buildSide and squashes the following commits:

1780351 [Zongheng Yang] Use size estimation to decide optimal build side of BNLJ.
68e6c5b [Zongheng Yang] Consolidate two adjacent pattern matchings.
96d312a [Zongheng Yang] Use a while loop instead of collection methods chaining.
4bc525e [Zongheng Yang] Make BroadcastNestedLoopJoin take a BuildSide.
RandomRDDGenerators but without support for randomRDD and randomVectorRDD, which take in arbitrary DistributionGenerator.

`randomRDD.py` is named to avoid collision with the built-in Python `random` package.

Author: Doris Xin <doris.s.xin@gmail.com>

Closes #1628 from dorx/pythonRDD and squashes the following commits:

55c6de8 [Doris Xin] review comments. all python units passed.
f831d9b [Doris Xin] moved default args logic into PythonMLLibAPI
2d73917 [Doris Xin] fix for linalg.py
8663e6a [Doris Xin] reverting back to a single python file for random
f47c481 [Doris Xin] docs update
687aac0 [Doris Xin] add RandomRDDGenerators.py to run-tests
4338f40 [Doris Xin] renamed randomRDD to rand and import as random
29d205e [Doris Xin] created mllib.random package
bd2df13 [Doris Xin] typos
07ddff2 [Doris Xin] units passed.
23b2ecd [Doris Xin] WIP
(1) Inconsistent aggregate (agg) indexing for unordered features.
(2) Fixed gain calculations for edge cases.
(3) One-off error in choosing thresholds for continuous features for small datasets.
(4) (not a bug) Changed meaning of tree depth by 1 to fit scikit-learn and rpart. (Depth 1 used to mean 1 leaf node; depth 0 now means 1 leaf node.)

Other updates, to help with tests:
* Updated DecisionTreeRunner to print more info.
* Added utility functions to DecisionTreeModel: toString, depth, numNodes
* Improved internal DecisionTree documentation

Bug fix details:

(1) Indexing was inconsistent for aggregate calculations for unordered features (in multiclass classification with categorical features, where the features had few enough values such that they could be considered unordered, i.e., isSpaceSufficientForAllCategoricalSplits=true).

* updateBinForUnorderedFeature indexed agg as (node, feature, featureValue, binIndex), where
** featureValue was from arr (so it was a feature value)
** binIndex was in [0,…, 2^(maxFeatureValue-1)-1)
* The rest of the code indexed agg as (node, feature, binIndex, label).
* Corrected this bug by changing updateBinForUnorderedFeature to use the second indexing pattern.

Unit tests in DecisionTreeSuite
* Updated a few tests to train a model and test its training accuracy, which catches the indexing bug from updateBinForUnorderedFeature() discussed above.
* Added new test (“stump with categorical variables for multiclass classification, with just enough bins”) to test bin extremes.

(2) Bug fix: calculateGainForSplit (for classification):
* It used to return dummy prediction values when either the right or left children had 0 weight.  These were incorrect for multiclass classification.  It has been corrected.

Updated impurities to allow for count = 0.  This was related to the above bug fix for calculateGainForSplit (for classification).

Small updates to documentation and coding style.

(3) Bug fix: Off-by-1 when finding thresholds for splits for continuous features.

* Exhibited bug in new test in DecisionTreeSuite: “stump with 1 continuous variable for binary classification, to check off-by-1 error”
* Description: When finding thresholds for possible splits for continuous features in DecisionTree.findSplitsBins, the thresholds were set according to individual training examples’ feature values.
* Fix: The threshold is set to be the average of 2 consecutive (sorted) examples’ feature values.  E.g.: If the old code set the threshold using example i, the new code sets the threshold using exam
* Note: In 4 DecisionTreeSuite tests with all labels identical, removed check of threshold since it is somewhat arbitrary.

CC: mengxr manishamde  Please let me know if I missed something!

Author: Joseph K. Bradley <joseph.kurata.bradley@gmail.com>

Closes #1673 from jkbradley/decisiontree-bugfix and squashes the following commits:

2b20c61 [Joseph K. Bradley] Small doc and style updates
dab0b67 [Joseph K. Bradley] Added documentation for DecisionTree internals
8bb8aa0 [Joseph K. Bradley] Merge remote-tracking branch 'upstream/master' into decisiontree-bugfix
978cfcf [Joseph K. Bradley] Merge remote-tracking branch 'upstream/master' into decisiontree-bugfix
6eed482 [Joseph K. Bradley] In DecisionTree: Changed from using procedural syntax for functions returning Unit to explicitly writing Unit return type.
376dca2 [Joseph K. Bradley] Updated meaning of maxDepth by 1 to fit scikit-learn and rpart. * In code, replaced usages of maxDepth <-- maxDepth + 1 * In params, replace settings of maxDepth <-- maxDepth - 1
59750f8 [Joseph K. Bradley] * Updated Strategy to check numClassesForClassification only if algo=Classification. * Updates based on comments: ** DecisionTreeRunner *** Made dataFormat arg default to libsvm ** Small cleanups ** tree.Node: Made recursive helper methods private, and renamed them.
52e17c5 [Joseph K. Bradley] Merge remote-tracking branch 'upstream/master' into decisiontree-bugfix
da50db7 [Joseph K. Bradley] Added one more test to DecisionTreeSuite: stump with 2 continuous variables for binary classification.  Caused problems in past, but fixed now.
8ea8750 [Joseph K. Bradley] Bug fix: Off-by-1 when finding thresholds for splits for continuous features.
2283df8 [Joseph K. Bradley] 2 bug fixes.
73fbea2 [Joseph K. Bradley] Merge remote-tracking branch 'upstream/master' into decisiontree-bugfix
5f920a1 [Joseph K. Bradley] Demonstration of bug before submitting fix: Updated DecisionTreeSuite so that 3 tests fail.  Will describe bug in next commit.
….Map instead of scala.collection.immutable.Map

Since we let users create Rows. It makes sense to accept mutable Maps as values of MapType columns.

JIRA: https://issues.apache.org/jira/browse/SPARK-2779

Author: Yin Huai <huai@cse.ohio-state.edu>

Closes #1705 from yhuai/SPARK-2779 and squashes the following commits:

00d72fd [Yin Huai] Use scala.collection.Map.
…JDK 6

Author: GuoQiang Li <witgo@qq.com>

Closes #1683 from witgo/SPARK-2766 and squashes the following commits:

d0db00c [GuoQiang Li] ScalaReflectionSuite  throw an llegalArgumentException in JDK 6
Now the factors are persisted in memory only. If they get kicked off by later jobs, we might have to start the computation from very beginning. A better solution is changing the storage level to `MEMORY_AND_DISK`.

srowen

Author: Xiangrui Meng <meng@databricks.com>

Closes #1700 from mengxr/als-level and squashes the following commits:

c103d76 [Xiangrui Meng] change ALS factors storage level to MEMORY_AND_DISK
getRanks computes the wrong rank when numPartition >= size in the input RDDs before this patch. added units to address this bug.

Author: Doris Xin <doris.s.xin@gmail.com>

Closes #1710 from dorx/correlationBug and squashes the following commits:

733def4 [Doris Xin] bugs and reviewer comments.
31db920 [Doris Xin] revert unnecessary change
043ff83 [Doris Xin] bug fix for spearman corner case
Author: Haoyuan Li <haoyuan@cs.berkeley.edu>

Closes #1651 from haoyuan/upgrade-tachyon and squashes the following commits:

6f3f98f [Haoyuan Li] upgrade tachyon to 0.5.0
…ing class definition.

Without this patch, it imports everything available in the scope.

```scala

scala> val a = 10l
val a = 10l
a: Long = 10

scala> import a._
import a._
import a._

scala> case class A(a: Int) // show
case class A(a: Int) // show
class $read extends Serializable {
  def <init>() = {
    super.<init>;
    ()
  };
  class $iwC extends Serializable {
    def <init>() = {
      super.<init>;
      ()
    };
    class $iwC extends Serializable {
      def <init>() = {
        super.<init>;
        ()
      };
      import org.apache.spark.SparkContext._;
      class $iwC extends Serializable {
        def <init>() = {
          super.<init>;
          ()
        };
        val $VAL5 = $line5.$read.INSTANCE;
        import $VAL5.$iw.$iw.$iw.$iw.a;
        class $iwC extends Serializable {
          def <init>() = {
            super.<init>;
            ()
          };
          import a._;
          class $iwC extends Serializable {
            def <init>() = {
              super.<init>;
              ()
            };
            class $iwC extends Serializable {
              def <init>() = {
                super.<init>;
                ()
              };
              case class A extends scala.Product with scala.Serializable {
                <caseaccessor> <paramaccessor> val a: Int = _;
                def <init>(a: Int) = {
                  super.<init>;
                  ()
                }
              }
            };
            val $iw = new $iwC.<init>
          };
          val $iw = new $iwC.<init>
        };
        val $iw = new $iwC.<init>
      };
      val $iw = new $iwC.<init>
    };
    val $iw = new $iwC.<init>
  };
  val $iw = new $iwC.<init>
}
object $read extends scala.AnyRef {
  def <init>() = {
    super.<init>;
    ()
  };
  val INSTANCE = new $read.<init>
}
defined class A
```

With this patch, it just imports  only the necessary.

```scala

scala> val a = 10l
val a = 10l
a: Long = 10

scala> import a._
import a._
import a._

scala> case class A(a: Int) // show
case class A(a: Int) // show
class $read extends Serializable {
  def <init>() = {
    super.<init>;
    ()
  };
  class $iwC extends Serializable {
    def <init>() = {
      super.<init>;
      ()
    };
    class $iwC extends Serializable {
      def <init>() = {
        super.<init>;
        ()
      };
      case class A extends scala.Product with scala.Serializable {
        <caseaccessor> <paramaccessor> val a: Int = _;
        def <init>(a: Int) = {
          super.<init>;
          ()
        }
      }
    };
    val $iw = new $iwC.<init>
  };
  val $iw = new $iwC.<init>
}
object $read extends scala.AnyRef {
  def <init>() = {
    super.<init>;
    ()
  };
  val INSTANCE = new $read.<init>
}
defined class A

scala>

```

This patch also adds a `:fallback` mode on being enabled it will restore the spark-shell's 1.0.0 behaviour.

Author: Prashant Sharma <scrapcodes@gmail.com>
Author: Yin Huai <huai@cse.ohio-state.edu>
Author: Prashant Sharma <prashant.s@imaginea.com>

Closes #1635 from ScrapCodes/repl-fix-necessary-imports and squashes the following commits:

b1968d2 [Prashant Sharma] Added toschemaRDD to test case.
0b712bb [Yin Huai] Add a REPL test to test importing a method.
02ad8ff [Yin Huai] Add a REPL test for importing SQLContext.createSchemaRDD.
ed6d0c7 [Prashant Sharma] Added a fallback mode, incase users run into issues while using repl.
b63d3b2 [Prashant Sharma] SPARK-2632, SPARK-2576. Fixed by only importing what is necessary during class definition.
Author: Sandy Ryza <sandy@cloudera.com>

Closes #1642 from sryza/sandy-spark-2738 and squashes the following commits:

a923e4e [Sandy Ryza] SPARK-2738. Remove redundant imports in BlockManagerSuite
sryza and others added 21 commits August 17, 2014 22:39
Author: Sandy Ryza <sandy@cloudera.com>

Closes #1826 from sryza/sandy-spark-2900 and squashes the following commits:

43f9091 [Sandy Ryza] SPARK-2900
mengxr Please review the code. Adding weights in reduceByKey soon.

Only output model entry for words appeared in the partition before merging and use reduceByKey to combine model. In general, this implementation is 30s or so faster than implementation using big array.

Author: Liquan Pei <liquanpei@gmail.com>

Closes #1932 from Ishiihara/Word2Vec-improve2 and squashes the following commits:

d5377a9 [Liquan Pei] use syn0Global and syn1Global to represent model
cad2011 [Liquan Pei] bug fix for synModify array out of bound
083aa66 [Liquan Pei] update synGlobal in place and reduce synOut size
9075e1c [Liquan Pei] combine syn0Global and syn1Global to synGlobal
aa2ab36 [Liquan Pei] use reduceByKey to combine models
mengxr
Documentation for Word2Vec

Author: Liquan Pei <liquanpei@gmail.com>

Closes #2003 from Ishiihara/Word2Vec-doc and squashes the following commits:

4ff11d4 [Liquan Pei] minor fix
8d7458f [Liquan Pei] code reformat
6df0dcb [Liquan Pei] add Word2Vec documentation
mengxr
Remove  transform(dataset: RDD[String]) from public API.

Author: Liquan Pei <liquanpei@gmail.com>

Closes #2010 from Ishiihara/Word2Vec-api and squashes the following commits:

17b1031 [Liquan Pei] remove transform(dataset: RDD[String]) from public API
…ems or not

FIX: ShuffledDStream run tasks only when dstream has partition items
…ems or not

FIX: ShuffledDStream run tasks only when dstream has partition items
…ems or not

FIX: ShuffledDStream run tasks only when dstream has partition items
…ems or not

FIX: ShuffledDStream run tasks only when dstream has partition items
…ems or not

FIX: ShuffledDStream run tasks only when dstream has partition items
@guowei2 guowei2 closed this Aug 19, 2014
sunchao pushed a commit to sunchao/spark that referenced this pull request Dec 8, 2021
wangyum pushed a commit that referenced this pull request May 26, 2023
github-actions Bot pushed a commit to MaxGekk/spark that referenced this pull request Nov 2, 2026
…pache#1295)

### What changes were proposed in this pull request?

Adds row 548 to the milestone 8 plan (`sql/varka/plans/m8/PLAN.md`): two new rules for `dev/varka_lint.py`.

- **`global-fault`:** a `static` field that is not `final`, in a class whose name holds `Fault`, under `sql/catalyst/src/main`. A test fault read during emission must belong to the compile that plants it. Otherwise a planted fault leaks into other compiles running in the same JVM, and a faulty kernel class can be cached under a clean shape key. The 128-bit decimal pair's review found its signed low-word fault doing exactly that and moved it into the emit options; `VarkaFloatingFault`'s `private static volatile` field on master has the same hazard.
- **`arch-list`:** two or more of the literals `"amd64"`, `"x86_64"` and `"aarch64"` on one line outside `VarkaHostIsa`. The two-lane decline's review (apache#1262) found a test helper repeating `VarkaHostIsa`'s list of x86 `os.arch` names, which drifts from the compiler's host fact as soon as either list changes. A single literal, as a test's constructed host reading uses, still passes.

The row also moves `VarkaFloatingFault` into the emit options, so master passes its own rule.

**Done when** both rules report their planted cases in `--selftest`, `VarkaFloatingFault` holds no mutable static and its planted fault gets a shape key of its own, and the lint passes on master.

Also in this pull request:

- **Row 549**, small: every baseline benchmark section declared to fuse whole is checked at run time to run as a kernel. A Varka node can hand a batch back to the row path, and the existing check knows projections only, so the filter baselines (the decimal one among them, apache#1258) time a kernel nobody checked. The day-time baseline's `requireKernel` moves into `VarkaSqlBenchmarkBase` for every baseline.
- **Row 550**, medium: kernels driven at the int lane or at a narrow lane load and store their epilogue with masked `BYTE` and `SHORT` operations, which C2 does not lower without AVX512BW, so on CI's AVX2 runners most batches run the Vector API's Java loop once. apache#1291 fixed this for long-lane kernels only. The width audit never saw it because its probe's 256 rows divide every lane count, so the row first makes the audit probe a row count no lane count divides.
- **Scope item 129** in `m9/SCOPE.md`: build each pull request merged with current master before it merges. It is harness work outside milestone 8's type goals.
- **`sql/varka/AGENTS.md`**: before pushing a change to emitted code, run the preferred-width width audit under `-XX:UseAVX=2`, since the laptop is AVX-512 and CI's runners are AVX2.

### Why are the changes needed?

Both slips reached review more than once in two days. The fault one can make a test run give wrong answers depending on what else the JVM is compiling, and a line check catches both at commit time instead of in a review round.

### Does this PR introduce _any_ user-facing change?

No. Plan documents and contributor notes only.

### How was this patch tested?

The plan lint and the quote check pass on this head. The PR Build runs.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
github-actions Bot pushed a commit to MaxGekk/spark that referenced this pull request Nov 2, 2026
…pache#1299)

### What changes were proposed in this pull request?

Plan documents only, from what the recent pull requests learned about the compiler.

- **Row 551 in `m8/PLAN.md`, medium.** Today each choice that depends on the CPU reads its own signal. The 64-bit division form reads the `-XX:UseAVX` level. The two-lane decline (apache#1262) counts long lanes. The narrow epilogue fix (apache#1291) reads nothing and moves rows one at a time on every host, including the AVX-512 hosts whose C2 does lower masked byte and short operations. The row builds one record from HotSpot's CPU feature list (architecture, AVX512BW, AVX512DQ, AVX512VL, vector width), with one named question per x86 matcher rule the emitter relies on, and has every such choice read it. The session resolves the record on the driver and the plan carries it to the executors, as `useAVX` is carried today, so the default emit options stay the same on every host. The epilogue then takes the masked form where AVX512BW holds, but only if a committed pair measures it faster.
- **Scope item 130 in `m9/SCOPE.md`.** The compiler's entry points take each per-compile setting as a separate parameter, so adding one changes signatures and breaks callers other branches have just added, as happened to apache#1262's Build. The item folds them into one settings record.
- **Scope item 131 in `m9/SCOPE.md`.** apache#1262's two-lane refusal is a hand-written rule for one host shape. Once the capability record exists, the emit cost model could make that decision from the host's capabilities and a measurement.

### Why are the changes needed?

Every new data type in this milestone has met a C2 rule that depends on the CPU, and each fix keyed on whatever signal its author found first. One record keeps those decisions consistent and lets a kernel use the faster form where the host supports it.

### Does this PR introduce _any_ user-facing change?

No. Plan documents only.

### How was this patch tested?

The plan lint and the quote check pass on this head. The PR Build runs.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Nov 3, 2026
…pache#1291)

### What changes were proposed in this pull request?

Varka now fuses the casts among Spark's integral types and `BOOLEAN` under LEGACY and ANSI. Before this change Spark evaluated them on its row path, so any fused expression containing one of them ended its kernel at the cast.

**One table, four kinds.** A new family, `VarkaIntegralCastCompiler`, with its own switch `integralCast`, classifies each (source, target) pair instead of hand-writing an arm per pair:
- **Widen**, such as `TINYINT` to `BIGINT`: a sign extension.
- **Narrow**, such as `INT` to `TINYINT`. LEGACY keeps the low bits, as Java's cast does. ANSI puts a range guard of the target's range under the narrowing, so a batch holding an out-of-range value goes back to the row engine, which raises `CAST_OVERFLOW` exactly where Spark does.
- **Test**: a number to `BOOLEAN` is `x != 0`.
- **Select**: a `BOOLEAN` to a number is 1 or 0 in the target's own lane, so `CAST(b AS TINYINT)` runs in the byte lane.

The target ranges come from one function of the lane, `VarkaTypes.integralRange`. `try_cast` narrowings still decline: they need a null-producing guard that later work adds.

**Narrow values beside a `BIGINT`.** A kernel driven at the long lane can now hold:
- a `TINYINT` or `SMALLINT` column read as a value;
- a bigint or an int narrowed to a narrow type, at an output or inside the tree;
- comparisons of these, and the connectives over them.

Other narrow arithmetic, choices or literals beside a bigint still decline by name. A narrow store at the long lane stores whole vectors in the loop body and masks only the tail, where the lane count allows it. AVX2 has no masked byte or short store, so a mask on every iteration would run lane by lane.

The rule for which narrow nodes a long kernel may hold is one exhaustive switch over the IR, read by both the analysis and the plan, so a new IR node is a compile error there.

**What checks it:**
- **`VarkaEmitterIntegralCastSuite`** checks every row against Spark's own cast:
  - every `TINYINT` and `SMALLINT` value to every target, in all three modes, on both lane arms;
  - `BOOLEAN` to each integral type at every length up to 129;
  - named boundary cases, each next to a null;
  - the narrow load and store in a long kernel at 2, 4 and 8 long lanes, and with no lane count baked.
- **SMT proofs.** A new `sql/varka/proofs/casts.smt2` (18 checks) proves the 64-bit narrowings and their guards under Z3 and cvc5. The 16-bit sources are covered by the existing narrow-range proofs.
- **The IR fuzzer** gains a cast draw over every composition, guard mode and lane, including narrowings that another node reads. Each draw may be refused only for its width. Its first run found a real bug, now fixed: a narrow select of a boolean column at an unbaked width stored past the end of the batch.
- **The harness** now catches an output lane the kernel never wrote, even when the sentinel happens to be a correct cast answer. It now reads an int kernel's narrow outputs at their own width.
- **Coverage.** 20 rows in two new families, plus a family-switch query test.

**Generated files**, regenerated in the documented order:
- `coverage.json` and `docs/sql-varka.md` gain the new rows and the switch.
- `width_audit.json` gains the new rows.
- `emitted_bytes.json` gains the new rows' entries. Only the option-arm digests that hash every shape move.
- `casts_fused.tsv` and `casts.tsv` show the in-scope pairs as fused.

### Why are the changes needed?

Integral casts are everywhere in real queries, both written by users and inserted by type coercion when a narrow column meets a wider one. Each one forced the expression around it back onto Spark's row path. The row-path baseline for these casts is a separate pull request, and the paired measurement follows once both merge.

### Does this PR introduce _any_ user-facing change?

Yes, for users who enable Varka: these casts are now evaluated by Varka's vector kernels, with the same answers, including `CAST_OVERFLOW` under ANSI. A new family switch, `spark.sql.codegen.varka.family.integralCast.enabled`, turns them off.

### How was this patch tested?

- The first PR Build failed the width audit on the AVX2 runner: without AVX-512BW, C2 has no lowering for a masked byte or short load or store, and a long kernel that mixes lanes ran its last group's narrow rows that way. That epilogue now moves narrow rows one at a time with constant-index lane inserts and extracts, which every x86 with SSE4.1 lowers. The preferred-width audit passes under `-XX:UseAVX=2`, and only those shapes' epilogues moved in `emitted_bytes.json`.

- On the laptop:
  - the integral-cast, narrow, boolean, IR-fuzz (also at two other seeds), composition-fuzz, emitted-bytes, width-audit and coverage suites, with no failures;
  - the conformance suites;
  - `VarkaCoverageHarnessSuite` (1,394 tests);
  - the proofs under both solvers.
- A self-review (`/code-review high`, then two medium rounds on the fixes) found and fixed:
  - gaps in the fuzzer and the harness's checks;
  - a masked store in the loop body;
  - duplicated classification logic;
  - an int kernel's narrow outputs read at the wrong width.
- Errorprone, lint-java, lint-scala and the plan and quote checks are clean. The PR Build and the option matrix run on this head.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
MaxGekk pushed a commit to MaxGekk/spark that referenced this pull request Nov 3, 2026
The merge of master (apache#1291's integral casts beside this branch's floating ones) left the
emitted-bytes digests and two docs blocks stale; dev/varka_regen_generated.sh recomputed them.

- sql/varka/emitted_bytes.json: only the option-arm digests change, each taken over every kernel
  of the corpus, which now holds both families' kernels; no single kernel's bytes change.
- docs/sql-varka.md: the family switch table gains the integralCast row, and the verification
  counts include apache#1291's rows.
- The width audit and coverage regenerate unchanged.

Generated-by: Claude Code (Opus 5.5)
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Nov 5, 2026
…l requests (apache#1370)

### What changes were proposed in this pull request?

Seventeen rows of `sql/varka/plans/m8/PLAN.md` still read as before work that has merged. Each is corrected against its merged pull requests, which `git log` lists by the row's `[VARKA-n]` tag:

- **Now `Done`:** row 497 (one `IN` arm for every lane, apache#1259), row 333 (apache#1260) and row 365 (the Arrow cache's small decimals read as vanilla Spark reads them, apache#1306). The done-when of each is met by that pull request, and the "left" text that waited on it is gone.
- **Still `Started` or `Done in part`, with merged parts named:** rows 157, 330, 331, 332, 333, 340, 341, 342, 343, 344, 348, 349, 377, 503 and 538. Branch names that stood for work now merged become the pull request numbers and dates (for example 348's four parts, apache#1321, apache#1323, apache#1324 and apache#1349), and a "left" item that merged is dropped (538's flip, apache#1345; 341's mask crossing, closed by 343a3 and 343a3b; 377's decimal class, apache#1055).
- Row 377 now says what is still open: the floating baseline does not state whether its data holds denormals, which its done-when of 27 October 2026 asks.
- Rows 332 and 333 are read against their done-when. Row 333 is `Done` (apache#1260: its outcome records the census, the coverage rows and the unmoved `date_add` bytes). Row 332 stays `Started`: its 14 non-identity casts fuse (apache#1291), and what is left is 332b's in-range conformance value sets, the measurement against the baseline (no results file exists), two gaps from the 2 November review, and row 352's fuzz productions.

Only row text changes; no code, result or generated file.

### Why are the changes needed?

A reader who takes a row's state at its word re-plans or restarts work that merged, which the triage of 4 November 2026 found for these rows.

### Does this PR introduce _any_ user-facing change?

No.

### How was this patch tested?

`dev/varka_plan_lint.py` and `dev/varka_quote_check.py` pass. Every pull request number and date in the new text was read from `git log` of master.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Sonnet 5.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.