Skip to content

[SPARK-2490] Change recursive visiting on RDD dependencies to iterative approach - #1418

Closed
viirya wants to merge 4 commits into
apache:masterfrom
viirya:remove_recursive_visit
Closed

viirya wants to merge 4 commits into
apache:masterfrom
viirya:remove_recursive_visit

Conversation

@viirya

@viirya viirya commented Jul 15, 2014

Copy link
Copy Markdown
Member

When performing some transformations on RDDs after many iterations, the dependencies of RDDs could be very long. It can easily cause StackOverflowError when recursively visiting these dependencies in Spark core. For example:

var rdd = sc.makeRDD(Array(1))
for (i <- 1 to 1000) { 
  rdd = rdd.coalesce(1).cache()
  rdd.collect()
}

This PR changes recursive visiting on rdd's dependencies to iterative approach to avoid StackOverflowError.

In addition to the recursive visiting, since the Java serializer has a known bug that causes StackOverflowError too when serializing/deserializing a large graph of objects. So applying this PR only solves part of the problem. Using KryoSerializer to replace Java serializer might be helpful. However, since KryoSerializer is not supported for spark.closure.serializer now, I can not test if KryoSerializer can solve Java serializer's problem completely.

@viirya

viirya commented Jul 16, 2014

Copy link
Copy Markdown
Member Author

Another example of this problem is the PageRank example bundled in Spark. At this time, since the problem of Java serializer still exists, to avoid causing StackOverflowError after too many iterations, it is needed to call checkpoint() on the RDD.

@rxin

rxin commented Jul 20, 2014

Copy link
Copy Markdown
Contributor

Thanks for submitting this. I think we can still stack overflow in serialization, but I agree it's better to do this non-recursivley.

@rxin

rxin commented Jul 20, 2014

Copy link
Copy Markdown
Contributor

Actually it's late. I will review this tomorrow.

@markhamstra

Copy link
Copy Markdown
Contributor

ok to test

@markhamstra

Copy link
Copy Markdown
Contributor

Jenkins, ok to test.

@viirya

viirya commented Jul 26, 2014

Copy link
Copy Markdown
Member Author

Thanks for commenting. How about the review?

@mateiz

mateiz commented Jul 26, 2014

Copy link
Copy Markdown
Contributor

Jenkins, test this please

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.

Don't do a collect, if you want to force it to be computed, just do a foreach. Otherwise collect will try to bring all the data back to the driver.

@SparkQA

SparkQA commented Jul 26, 2014

Copy link
Copy Markdown

QA tests have started for PR 1418. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17228/consoleFull

@SparkQA

SparkQA commented Jul 26, 2014

Copy link
Copy Markdown

QA results for PR 1418:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17228/consoleFull

@mateiz

mateiz commented Jul 26, 2014

Copy link
Copy Markdown
Contributor

Hey @viirya, instead of modifying the PageRank example, what do you think of leaving it as-is until we have automatic checkpointing of long lineage chains? I think that will be better because the example is meant to be easy to understand and not that many people will run PageRank with hundreds of iterations (this particular algorithm usually converges much faster).

@mateiz

mateiz commented Jul 26, 2014

Copy link
Copy Markdown
Contributor

BTW the Jenkins failure is due to a code style issue: an if block without braces

Jenkins, this is ok to test

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.

This should have braces around the loop body

@mateiz

mateiz commented Jul 26, 2014

Copy link
Copy Markdown
Contributor

BTW you can run sbt scalastyle to check these style things locally

@viirya

viirya commented Jul 27, 2014

Copy link
Copy Markdown
Member Author

@mateiz Thanks for suggestion. I leave the PageRank example as-is. These braces are added to comply with code style.

@mateiz

mateiz commented Jul 27, 2014

Copy link
Copy Markdown
Contributor

Jenkins, test this please

@rxin

rxin commented Jul 29, 2014

Copy link
Copy Markdown
Contributor

Jenkins, retest this please.

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA tests have started for PR 1418. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17331/consoleFull

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA results for PR 1418:
- This patch PASSES unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17331/consoleFull

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.

why define a function here? seems like this is only used once? why not just inline it in the while?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I let the codes as the function getParentShuffleDependencies because it contains multiple indents and so put it under the case statement would not be readable. I can make it as inline if this is an issue.

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.

This should actually be called getAncestorShuffleDependencies because it's not just direct parents, it can be grandparents and such as well.

Also, please add a comment at the top of this saying that what it finds. In particular it only finds missing ones.

Finally, would it be possible to merge this with the code that calls it in getShuffleMapStage, e.g. have a method called registerShuffleDependencies? Might be easier to follow.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Add new commit for several changes including function name, comments. Please review if it is fine.

@mateiz

mateiz commented Aug 1, 2014

Copy link
Copy Markdown
Contributor

Jenkins, test this please

@SparkQA

SparkQA commented Aug 1, 2014

Copy link
Copy Markdown

QA tests have started for PR 1418. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17661/consoleFull

@SparkQA

SparkQA commented Aug 1, 2014

Copy link
Copy Markdown

QA results for PR 1418:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17661/consoleFull

@mateiz

mateiz commented Aug 1, 2014

Copy link
Copy Markdown
Contributor

Jenkins, test this please

@SparkQA

SparkQA commented Aug 1, 2014

Copy link
Copy Markdown

QA tests have started for PR 1418. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17687/consoleFull

@SparkQA

SparkQA commented Aug 1, 2014

Copy link
Copy Markdown

QA results for PR 1418:
- This patch PASSES unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17687/consoleFull

@mateiz

mateiz commented Aug 1, 2014

Copy link
Copy Markdown
Contributor

Thanks Liang-Chi; I've merged this in.

@asfgit asfgit closed this in baf9ce1 Aug 1, 2014
xiliu82 pushed a commit to xiliu82/spark that referenced this pull request Sep 4, 2014
…ve approach

When performing some transformations on RDDs after many iterations, the dependencies of RDDs could be very long. It can easily cause StackOverflowError when recursively visiting these dependencies in Spark core. For example:

    var rdd = sc.makeRDD(Array(1))
    for (i <- 1 to 1000) {
      rdd = rdd.coalesce(1).cache()
      rdd.collect()
    }

This PR changes recursive visiting on rdd's dependencies to iterative approach to avoid StackOverflowError.

In addition to the recursive visiting, since the Java serializer has a known [bug](http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4152790) that causes StackOverflowError too when serializing/deserializing a large graph of objects. So applying this PR only solves part of the problem. Using KryoSerializer to replace Java serializer might be helpful. However, since KryoSerializer is not supported for `spark.closure.serializer` now, I can not test if KryoSerializer can solve Java serializer's problem completely.

Author: Liang-Chi Hsieh <viirya@gmail.com>

Closes apache#1418 from viirya/remove_recursive_visit and squashes the following commits:

6b2c615 [Liang-Chi Hsieh] change function name; comply with code style.
5f072a7 [Liang-Chi Hsieh] add comments to explain Stack usage.
8742dbb [Liang-Chi Hsieh] comply with code style.
900538b [Liang-Chi Hsieh] change recursive visiting on rdd's dependencies to iterative approach to avoid stackoverflowerror.
@viirya
viirya deleted the remove_recursive_visit branch December 27, 2023 18:16
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Nov 10, 2026
…he#1418)

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

Varka now fuses `round`, `bround` and `truncate` over `TINYINT`, `SMALLINT` and `INT` at a constant scale, in every mode. It also fuses them over `BIGINT` when the scale is 0 or more. They join the rounding family (`VarkaRoundingCompiler`, switch `spark.sql.codegen.varka.family.rounding.enabled`), which already holds `rint` and the integral `floor` and `ceil`. No IR node is added. Every step is an existing node.

**What Spark computes.** For an integral operand, `Round`, `BRound` and `Truncate` are `BigDecimal(x).setScale(scale, HALF_UP | HALF_EVEN | DOWN)`. The result is then converted back to the operand's type: with `toInt`, `toShort` or `toByte` under LEGACY, which keeps the low bits of the exact integer, and with the `...Exact` forms under ANSI, which raise when the result leaves the type. A scale of 0 or more changes nothing.

**The kernel.** A scale of 0 or more compiles to the operand. A scale `-k` rounds to a multiple of `d = 10^k`. A `TINYINT` or `SMALLINT` operand is widened to the int lane first, so all three types share these steps on the int lane, each wrapping:

    q0 = x / d                  ConstDivide, Java's truncating division: q0 has x's sign
    r  = x - q0 * d             exact; r has x's sign and |r| < d
    HALF_UP:   q = q0 + [r >= h] - [r <= -h]                       h = d / 2
    HALF_EVEN: q = q0 + [r + (q0 & 1) > h] - [r - (q0 & 1) < -h]
    DOWN:      q = q0
    out = q * d                 wraps, giving the low 32 bits of the exact rounded integer

Rounding half away from zero and half to even are both symmetric in the sign, so the sign of the remainder picks which way to step. `r` and `h` are integers and `q0 & 1` is 0 or 1, so `r + (q0 & 1) > h` holds when `r > h`, or when `r == h` and `q0` is odd. That puts the tie test in one compare per side. An `Or` of an `And` would be one node deeper, and with it `bround` of a `TINYINT` under ANSI inside a `CASE` would pass the emitter's chain depth and decline. The two steps, `IfElse(up, d, 0)` and `IfElse(down, d, 0)`, are added to `q0 * d`. A guard reached from an `IfElse`'s condition is never qualified by an enclosing `CASE` arm, so the conditions read the unguarded operand and the ANSI guard sits on the value path alone, as `guarded - r`, which wraps to `q0 * d`. A `CASE` whose untaken arm rounds an overflowing value therefore still fuses, as it does for checked arithmetic. A narrow answer is then narrowed back to its type, keeping its low 8 or 16 bits, which is what `toByte` and `toShort` keep. Past the type's digits (`k > 2`, 4 or 9) every value rounds to 0, and the kernel multiplies by 0, which keeps the operand's nulls.

**ANSI.** A checked multiply is not used. Rounding is monotone in `x`, so the operands whose result leaves the type form two tails. At compile time `VarkaRoundingCompiler.window` bisects over `BigDecimal`'s own answer to find the window of operands that fit. A `GuardedRange` on that window declines a batch with a live lane outside it, and the row engine then raises Spark's error. For `INT` at `k = 1` the window is `[-2147483644, 2147483644]` for `round` and `[-2147483645, 2147483645]` for `bround`. At most scales there is no window, and `truncate` never has one.

**Declines.** Each decline names the row that owns the form. A decimal operand declines by its type (rows 351 and 363). This check runs before the lane lookup, because a decimal of precision 18 or less sits on the long lane as its unscaled value, and the integer rounding would ignore its scale. A floating operand declines as row 346's. A scale below -100 declines. A `BIGINT` at a negative scale declines as part 344a3 (see below).

**The proof.** `sql/varka/proofs/int_round.smt2` is rendered by `VarkaProofFiles` from the compiler's own windows and from `signedMagic`'s constants. It has 133 checks:
- for each `k` from 1 to 9, the multiply-high division by `10^k` is Java's `x / 10^k` for every int;
- each of the three forms equals the rounding over unbounded integers, wrapped to 32 bits, for every int;
- `bround`'s steps are not `round`, and `bround` without its odd test is not `bround` (two `sat` refutations);
- every value of each type is 0 one digit past the type;
- every ANSI window of the three types fits the type, and one past either end does not;
- the specification matches `BigDecimal` at sample values.

The file is stated under `(set-logic ALL)`. Every product is by a constant, and under `QF_NIA` cvc5 answered unknown on six of `bround`'s checks.

**Split.** Row 344's plan gives 344a2 the whole integral rounding. This pull request builds the int lane only. It measures 996 counted lines, under the 1000-line cap, and the long lane would add its pre-shift: `(|x| >>> k) / 5^k` to keep the dividend under `ConstDivide`'s `2^52` bound, a guard for `k <= 11`, the `k = 19` constant past the long, and a proof of those steps over the long range. On an earlier unmerged attempt that was about 270 lines of compiler and 250 of proof renderer. That work is now 344a3 in `VARKA-344.md` section 5.

Also in this pull request:
- the baseline benchmark lists `rint(x)`, `floor(i)` (344a1's, which 344a1 did not list), `round(i, -2)` and `bround(i, -2)` as fusing sections;
- `sql/varka/fuzz/expected_errors.tsv` names the rounding family under ANSI's `ARITHMETIC_OVERFLOW`;
- the opt-in row of the rounding suite in `sql/varka/ci/sweeps.tsv` now includes the int sweep;
- `VARKA-344.md` section 10 has the outcome, and the PLAN.md row and the curated census are updated.

### Why are the changes needed?

Without this change, `round`, `bround` and `truncate` over an integral column send every query that uses them to the row engine. Each evaluation there builds a `BigDecimal`. The census names row 344 for these entries, and this change fuses them for `TINYINT`, `SMALLINT` and `INT`, and for `BIGINT` at a scale of 0 or more.

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

No change to answers or errors. Queries using these functions over the types above now run in a fused Varka kernel when Varka is enabled. Under ANSI, a batch that holds an overflowing value goes to the row engine, which raises Spark's own error.

### How was this patch tested?

On the laptop (AVX-512), 8 November 2026:

- `VarkaEmitterRoundingSuite` runs the emitted kernels against Spark's own `Round`, `BRound` and `Truncate` `eval`, in LEGACY and ANSI. It covers every `TINYINT` and `SMALLINT` value at every scale where the answer is not constant, and the ints at scales -1 to -10 over a 2^20-value slice: the ties of every scale on both parities and signs, the windows' ends, the extremes, then a stride. Under ANSI, a chunk the kernel answers must hold no value Spark raises on, and a chunk holding one must be declined. The full 2^32 sweep of every `INT` (60 sweeps) sits behind `-Dvarka.sweep=true` and was not run here. It is owed to the gate's sweep step.
- `VarkaRoundingSuite` (sql/core) runs every form end to end over cached cells, comparing against the row engine. Every cell sits on a valid lane, and a second copy of the cells is interleaved with nulls. Under ANSI, each cell of a form that can raise runs on its own, and Varka's answer or error must equal the row engine's.
- `VarkaExpressionCompilerSuite` checks each decline and the row it names. The decimal case reaches the family through a decimal comparison, so the family is asked rather than the decimal output store declining first.
- Proofs: `int_round.smt2` holds under Z3 (1.9 s) and cvc5 (0.5 s).
- `dev/varka_matrix.sh --defaults --module catalyst --split 4 -j 4`: 1260 passed, 5 failed, 88 canceled (the opt-in ones), 966 s. None of the five failures is from this change. Two are the `VarkaIrFuzzSuite` floating-cast tests (`an unsigned comparison ULE takes an integral lane, not FLOAT`), which also fail on master 9eefe2a and are being fixed separately. Two come with the 344a1 base (`fp_round.smt2` differs from its render; `floor and ceil over a double, a decimal or a cast name the row that owns it`), and the files involved are identical to that branch's. The fifth was this branch's decimal-decline test, whose expected reason text was out of date after the rebase. It is fixed and passes on a rerun.
- `dev/varka_matrix.sh --defaults --module sql --sbt-arg -Phive`: 2822 passed, 0 failed, 7 canceled, 971 s.
- `dev/lint-java`, `dev/varka_errorprone.sh`, `dev/varka_plan_lint.py`, `dev/varka_quote_check.py`, `dev/varka_census.py --check` and `dev/varka_precommit.sh` (on every commit) pass.
- Generated files were regenerated with `dev/varka_regen_generated.sh --all`. `emitted_bytes.json` gains the new coverage shapes, and no existing shape's bytes move.

### 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 10, 2026
…hes solvers (apache#1439)

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

Plan changes for CI stability, from what failed on 9 November 2026:

- **Row 590: a pull request's Build tests it merged with Varka's master.** Today the Build checks out the branch's own commit. It deliberately stopped merging onto apache/spark's master, which broke every branch whenever upstream edited a file Varka rewrote. Testing the head alone means a branch runs without the fixes master gained since it forked. apache#1413's Build hung for 2.5 hours, and apache#1418's and apache#1426's failed, on the width-audit hang that apache#1416 had fixed on master that morning. Separately, two pull requests that were each green alone broke master together (apache#1392 and apache#1393). The row merges onto Varka's own master only, with a fallback to the head when the merge conflicts.
- **Row 591: a benchmark that lands on the wrong CPU is rerun by CI.** `benchmark.yml` rightly fails a run that lands on anything but an EPYC 7763, but the retry has been a laptop script rerunning hourly. apache#1414's 128-bit run took four tries over about five hours.
- **Row 592: the proof solvers install from a cache, and a download retries.** The cvc5 download returned HTTP 504 twice today and failed the lint job before any proof ran.
- **Row 508 (note):** run a pull request's new coverage rows at PR time under `lanesOverride=16`, `validityByWidth=false` and 128-bit vectors. apache#1418, apache#1425 and apache#1428 each failed their option matrix hours in on new rows those configurations decline by design.
- **Row 513 (note, reopened in part):** bin b150 of apache#1426's matrix still failed at "Download the classpath, again", so the existing retry is not enough.

### Why are the changes needed?

Each of these cost hours of queue time or a manual merge-and-re-push on 9 November, and together they made most of the day's red CI runs that were not about the code under review.

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

No. It changes only the milestone plan.

### How was this patch tested?

`dev/varka_plan_lint.py --check --offline` reports no findings.

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

Generated-by: Claude Code (claude-opus-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.

5 participants