Pair your devices with a code and playback position follows you: pause on this device, hit resume on the other. Position is saved to the site every minute and on pause.
Open this panel on your other device and enter the same code.
Target: a laptop. This lab deliberately does not need an AWS account: everything a lead has to demonstrate here — reading a plan, recognising a failure, reviewing code — reproduces in local mode. Part 6 is an optional AWS step.
You need: Java 17 and Python 3.11 or newer (the versions Spark 4.3.0 documents — lesson 1).
Cost: nothing for Parts 1–5. Part 6 is one read-only CLI call plus, if you choose to run it, one short EMR Serverless job; this lab did not execute Part 6 and quotes no price for it — read the EMR Serverless pricing page before you run it.
Every script in Parts 1–3 was run on 2026-11-22 on Spark 4.3.0, Scala 2.13.18, Java 17.0.18, macOS, local mode. The expected results are in the facilitator notes at the end — what was observed on that run, not what the docs say should happen.
Predict before you run. Each numbered question asks for a written answer before the command.
mkdir stl-lab && cd stl-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "pyspark==4.3.0" "pandas>=2.2.0,<3.0.0" "pyarrow>=18.0.0"
export SPARK_HOME="$(python -c 'import pyspark, os; print(os.path.dirname(pyspark.__file__))')"
export PYSPARK_PYTHON="$(which python)"
java -version # must say 17, 21 or 25
The pandas and PyArrow ranges are the ones the
4.3.0 install page
states (lesson 6). The pip package ships spark-shell, the Scala compiler and every Spark jar, so
you get a Scala REPL without installing Scala or sbt. SPARK_HOME must be set, or spark-shell fails
with /bin/spark-submit: No such file or directory.
⚠️ The verification run used pandas 3.1.1, outside the documented range; PySpark printed a warning and
these scripts still ran. Lesson 5 found pyspark.testing does not work with pandas 3 — keep the
pin above.
Save as part1.scala:
println(s"Spark ${spark.version} / Scala ${util.Properties.versionNumberString}")
import org.apache.spark.sql.functions._
case class Order(id: Long, country: String, amount: Double)
spark.range(100000).select(col("id"), when(col("id") % 3 === 0, "PH").otherwise("US").as("country"), (col("id") % 500).cast("double").as("amount")).write.mode("overwrite").parquet("data/orders")
val orders = spark.read.parquet("data/orders").as[Order]
println("--- A: column filter")
orders.filter($"amount" > 498).explain()
println("--- B: typed lambda filter")
orders.filter(o => o.amount > 498).explain()
println(orders.filter($"amount" > 498).count() + " " + orders.filter(o => o.amount > 498).count())
println("--- C: null into a primitive field")
val withNull = spark.sql("select 1L as id, 'PH' as country, cast(null as double) as amount").as[Order]
try { withNull.map(o => o.amount * 2).collect() } catch { case e: Throwable => println(e.getClass.getSimpleName + ": " + e.getMessage.take(160)) }
case class OrderOpt(id: Long, country: String, amount: Option[Double])
println(spark.sql("select 1L as id, 'PH' as country, cast(null as double) as amount").as[OrderOpt].map(o => o.amount.map(_ * 2)).collect().toList)
Q1. Before running: which Scala version will the first line print, and what artifact suffix does
that put on every Spark dependency in a build.sbt? What happens to a job jar built for the other
suffix? (Lesson 1.)
Q2. Filters A and B return the same rows. Write down what you expect in PushedFilters for each,
and whether you expect a DeserializeToObject node under filter B. (Lesson 2 — and be careful, the
folklore is half right.)
$SPARK_HOME/bin/spark-shell --master 'local[2]' -I part1.scala < /dev/null 2>&1 | grep -v WARN
Q3. Section C fails. Where does it fail — when .as[Order] is called, or inside a task? Why does
that distinction matter for a pipeline that has run cleanly for a month? What is the one-word change
to the case class that fixes it?
Q4. As a reviewer: a pull request contains filter B. Write the review comment you would leave — two sentences, naming the mechanism and the evidence, not "use columns instead".
Save as skew.py:
import time, sys
from pyspark.sql import SparkSession, functions as F
N = int(sys.argv[1]); aqe = sys.argv[2]; extra = sys.argv[3:]
b = (SparkSession.builder.master("local[4]").appName(f"stl-lab-skew-{N}-{aqe}")
.config("spark.sql.adaptive.enabled", aqe)
.config("spark.sql.autoBroadcastJoinThreshold", "-1")
.config("spark.ui.showConsoleProgress", "false"))
for kv in extra:
k, v = kv.split("=", 1); b = b.config(k, v)
spark = b.getOrCreate(); spark.sparkContext.setLogLevel("ERROR")
fact = (spark.range(N)
.withColumn("customer_id", F.when(F.col("id") % 10 < 9, F.lit(0)).otherwise(F.col("id") % 9999 + 1))
.withColumn("pad", F.sha2(F.col("id").cast("string"), 256)))
dim = spark.range(10_000).withColumnRenamed("id", "customer_id").withColumn("name", F.concat(F.lit("c"), F.col("customer_id")))
j = fact.join(dim, "customer_id")
t = time.time(); j.write.format("noop").mode("overwrite").save(); print("seconds", round(time.time() - t, 1))
import urllib.request, json
ui = spark.sparkContext.uiWebUrl; app = spark.sparkContext.applicationId
sqls = json.load(urllib.request.urlopen(f"{ui}/api/v1/applications/{app}/sql?details=true&planDescription=true"))
desc = sqls[-1]["planDescription"]
for word in ("skew=true", "coalesced and skewed", "coalesced", "isFinalPlan=true"):
print(f"{word!r:26} in final plan:", word in desc)
stages = json.load(urllib.request.urlopen(f"{ui}/api/v1/applications/{app}/stages"))
for s in sorted(stages, key=lambda s: s["stageId"]):
print("stage", s["stageId"], s["status"], "tasks", s["numTasks"], "shuffleReadMB", round(s["shuffleReadBytes"]/1e6))
spark.stop()
The script builds a fact table where ninety percent of rows share one key, disables broadcast so the join must shuffle, runs it, then asks the application's own REST API for the final plan and the stage list — the same evidence lesson 4 tells you to ask a junior for.
Q5. With AQE off at three million rows: how many tasks will the join stage have, and why that number? (Lesson 4's config table.)
python skew.py 3000000 false 2>/dev/null
Q6. Now AQE on, same data, default settings. Skew join handling is enabled by default. Will
skew=true appear in the final plan? Write yes or no and the reason before running.
python skew.py 3000000 true 2>/dev/null
Q7. Lesson 4 gives the two conditions a partition must meet to be treated as skewed. Use them to explain the result you just got. Then predict what five million rows does:
python skew.py 5000000 true 2>/dev/null
Q8. Go back to three million rows and make AQE split the hot partition without adding data:
python skew.py 3000000 true \
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes=32m \
spark.sql.adaptive.advisoryPartitionSizeInBytes=16m 2>/dev/null
Was that the right fix for a production job? Write what you would want to know before approving a pull request that sets those two keys.
Q9. The wall-clock seconds barely change between runs. A stakeholder asks "so did the tuning work?" Write the two-sentence answer.
Save as breaks.py (it reuses data/orders from Part 1):
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[2]").appName("stl-lab-breaks")
.config("spark.driver.maxResultSize", "1m").config("spark.ui.showConsoleProgress", "false").getOrCreate())
spark.sparkContext.setLogLevel("OFF")
def attempt(label, fn):
try:
print(label, "->", fn())
except Exception as e:
lines = [l for l in str(e).splitlines() if "[" in l or "maxResultSize" in l] or str(e).splitlines()
print(label, "-> RAISED", type(e).__name__, "|", lines[0].strip()[:170])
# Break 1 - ANSI
print("ansi =", spark.conf.get("spark.sql.ansi.enabled"))
attempt("1a overflow ", lambda: spark.sql("SELECT 2147483647 + 1 AS v").collect())
attempt("1b bad cast ", lambda: spark.sql("SELECT CAST('12x' AS INT) AS v").collect())
attempt("1c try_ variants ", lambda: spark.sql("SELECT try_add(2147483647, 1) AS a, try_cast('12x' AS INT) AS c").collect())
spark.conf.set("spark.sql.ansi.enabled", "false")
attempt("1d overflow, off ", lambda: spark.sql("SELECT 2147483647 + 1 AS v").collect())
spark.conf.set("spark.sql.ansi.enabled", "true")
# Break 2 - the re-run that deletes history
def parts():
return sorted(r.dt for r in spark.read.parquet("data/daily").select("dt").distinct().collect())
three = spark.createDataFrame([(1, "2026-11-20"), (2, "2026-11-21"), (3, "2026-11-22")], "id int, dt string")
today = three.filter("dt = '2026-11-22'")
three.write.mode("overwrite").partitionBy("dt").parquet("data/daily")
print("2 mode =", spark.conf.get("spark.sql.sources.partitionOverwriteMode"), "| before:", parts())
today.write.mode("overwrite").partitionBy("dt").parquet("data/daily")
print("2a static re-run ->", parts())
three.write.mode("overwrite").partitionBy("dt").parquet("data/daily")
today.write.mode("overwrite").option("partitionOverwriteMode", "dynamic").partitionBy("dt").parquet("data/daily")
print("2b dynamic re-run ->", parts(), "rows", spark.read.parquet("data/daily").count())
today.write.mode("append").partitionBy("dt").parquet("data/daily")
print("2c append re-run -> rows", spark.read.parquet("data/daily").count())
# Break 3 - the driver
big = spark.range(200_000).withColumn("pad", F.sha2(F.col("id").cast("string"), 256))
attempt("3 collect ", lambda: len(big.collect()))
# Break 4 - the filter nobody can push down
@F.udf("boolean")
def is_big(x):
return x is not None and x > 498
orders = spark.read.parquet("data/orders")
for label, df in (("4a column", orders.filter(F.col("amount") > 498)), ("4b python udf", orders.filter(is_big("amount")))):
plan = df._jdf.queryExecution().executedPlan().toString()
pushed = plan[plan.index("PushedFilters"):].split("]")[0] + "]"
print(label, "|", pushed, "| ArrowEvalPython" if "ArrowEvalPython" in plan else "| BatchEvalPython" if "BatchEvalPython" in plan else "| no python node", "| rows", df.count())
spark.stop()
For each break, write the prediction first.
Q10 — Break 1. On Spark 4.3.0 with no configuration, what does 2147483647 + 1 do? What does the
same expression do with ANSI mode off — the pre-4.0 default — and which of the two behaviours is the
dangerous one? (Lesson 6.)
Q11 — Break 2. A daily job writes one day with mode("overwrite").partitionBy("dt") to a path
that already holds three days. How many days are there afterwards, with defaults? (Lesson 5.) Which
single option makes the re-run safe, and why is append not the answer?
Q12 — Break 3. The driver's result limit is set to one megabyte and the script collects two hundred thousand rows. What is the documented default of that limit, and what is the review rule this error exists to enforce? (Lessons 4 and 5.)
Q13 — Break 4. Both filters return 200 rows. What differs in the plan? The Python UDF shows a node
whose name starts with Arrow even though the code never asked for Arrow — why? (Lesson 3.) Would
rewriting the UDF in Scala restore the pushed filter?
python breaks.py 2>/dev/null
Drop the 2>/dev/null once to see the raw stack traces — finding the one line that matters in one is
the skill.
In spark-shell and in pyspark, run the same aggregation over data/orders — group by country,
sum amount, count rows — and call explain() on each.
Q14. Predict the difference between the two physical plans. Then diff them.
Q15. Someone on the team proposes rewriting this job in Scala "for performance". Write the three questions you ask before agreeing to anything.
No Spark needed. This is the job. A teammate opens a pull request with this PySpark; the description says "nightly customer revenue rollup, tested on the dev sample". (The snippet is the exercise — it is not meant to be run.)
spark = SparkSession.builder.config("spark.sql.shuffle.partitions", "2000") \
.config("spark.sql.ansi.enabled", "false").getOrCreate()
orders = spark.read.csv("s3://lake/raw/orders/", header=True, inferSchema=True)
customers = spark.read.parquet("s3://lake/dim/customers/")
@udf("string")
def tier(amount):
return "gold" if amount > 1000 else "std"
df = orders.join(customers, orders.customer_id == customers.id, "left")
for c in ["amount", "tax", "shipping", "discount"]:
df = df.withColumn(c + "_usd", col(c) * col("fx_rate"))
df = df.withColumn("tier", tier(col("amount_usd")))
df = df.withColumn("row_id", monotonically_increasing_id())
active = [r.id for r in customers.filter("status = 'active'").collect()]
df = df.filter(col("customer_id").isin(active))
df.write.mode("overwrite").partitionBy("order_date").parquet("s3://lake/gold/revenue/")
Q16. Write your review. Find at least eight issues, order them by blast radius — silently wrong results first, then things that kill the job, then things that are merely slow — and for each give the mechanism in one sentence. Do not write "best practice" anywhere.
Q17. Which two of your comments would you make blocking, and which would you leave as a non-blocking note for a first-month engineer? Why does that choice matter for the next pull request they send you?
Lessons 5 and 6 both make the point that open-source Spark is 4.3.0 and the newest AWS runtimes are on
4.1.x. Check it against an account instead of the docs. Not executed for this lab, and no CLI
syntax is given here beyond what lesson 5 copied from the AWS documentation — look up the exact
commands with aws emr help and aws emr-serverless help.
emr-spark-8.x runtime labels appear in that list or only in the EMR Serverless release
documentation. Q18. Write down what you find — lesson 5 flags that the documentation disagrees
with itself here, so your account is the evidence.spark.version, using the start-job-run shape copied in
lesson 5.
Q19. Which features from lesson 6's 4.2 and 4.3 lists can you therefore not promise on that
runtime?deactivate
cd .. && rm -rf stl-lab # the venv, data/, and the three scripts
Local mode leaves nothing running once the scripts exit. If you ran Part 6, stop the EMR Serverless application or confirm its auto-stop setting, and delete the script you uploaded to S3.
_2.13 suffix means for a buildPushedFilters in a plan and explain an empty one for a typed lambda and for a UDFNULL in a primitive case-class field fails inside a task, not at .as[T]skew=true in a final plan — or its absenceoverwrite does to a partitioned path under the default modeObserved results, 2026-11-22, Spark 4.3.0 local mode.
| Q | Observed |
|---|---|
| Q1 | Spark 4.3.0 / Scala 2.13.18. Suffix _2.13; Scala 2.12 support was removed in 4.0.0 (lesson 1). The mixed-classpath failure itself was not reproduced — lesson 1 flags that |
| Q2 | A: PushedFilters: [IsNotNull(amount), GreaterThan(amount,498.0)]. B: PushedFilters: [], DataFilters: [], condition invoke(<lambda>.apply(newInstance(class Order))). No DeserializeToObject node for the filter; lesson 2 shows it appears for map. Both count 200 |
| Q3 | Fails inside a task: SparkRuntimeException: [NOT_NULL_ASSERT_VIOLATION] NULL value appeared in non-nullable field. .as[Order] succeeds, so the job only breaks the day a null arrives. The Option[Double] version printed List(None) |
| Q5 | Join stage: 200 tasks (the spark.sql.shuffle.partitions default), 207 MB shuffle read in total. None of coalesced, skew=true, isFinalPlan=true in the plan |
| Q6 | Join stage: 2 tasks. coalesced present, skew=true absent |
| Q7 | At 5M rows: 6 tasks, 345 MB shuffle read, skew=true and coalesced and skewed both present. Lesson 4 measured the hot partition at 185 MB for 3M rows — over five times the median but under the 256 MB threshold — and 308 MB for 5M |
| Q8 | 7 tasks, skew=true present |
| Q9 | 3.8 s for the AQE-off run here; lesson 4 recorded 4.8 s against 4.3 s at 5M. The honest answer is about task distribution and spill, not seconds |
| Q10 | [ARITHMETIC_OVERFLOW]; the bad cast gives [CAST_INVALID_INPUT]; try_add / try_cast return NULL; with ANSI off the sum is -2147483648 |
| Q11 | Mode STATIC. After the static re-run only 2026-11-22 remains. Dynamic keeps all three days, 3 rows. Append leaves 4 rows — a duplicate |
| Q12 | Total size of serialized results of 1 tasks (6.5 MiB) is bigger than spark.driver.maxResultSize (1024.0 KiB). Documented default 1g |
| Q13 | Column: filters pushed, no Python node. Python UDF: PushedFilters: [] and an ArrowEvalPython node — Arrow-optimized Python UDFs are the default since 4.2 (lesson 3). Lesson 3 ran the Scala-UDF version: still PushedFilters: [] |
| Q14 | Not re-run for this lab. Lesson 3 ran it: diff of the two explain() outputs was empty |
Q16 answer key — the issues the lessons justify, in blast-radius order:
overwrite + partitionBy under the default STATIC mode deletes every
order_date partition not in tonight's data (lesson 5; you just watched it in Break 2).customers.id multiplies revenue if id is not unique in the
dimension (lesson 5's fan-out example); nothing in the PR asserts uniqueness.inferSchema=True on CSV lets a column's type change with the data; it also
"requires one extra pass over the data" (lesson 5 quotes the CSV page). Declare the schema.monotonically_increasing_id is documented as non-deterministic — it
depends on partition IDs — so row_id is not stable across re-runs (lesson 5).tier compares amount > 1000 with no null guard, and a left join produces
nulls. It is also a Python UDF for something a when expression does — opaque to the optimizer
(lesson 3).collect() of every active customer ID, then isin(list). Use a join
(lesson 5 on collect; Break 3).--conf at submit time, so an operator cannot change
shuffle.partitions without a code change (lesson 5's precedence run); and 2000 is asserted with
no measurement (lesson 4: change one thing, measure).withColumn in a loop — the API doc warns it "can generate big plans"; use one
withColumns or select (lesson 5). Four columns will not hurt. The habit will.Q17. There is no single right pair, but 1 and 3 are the usual blockers: both corrupt the gold table without an error. The point to draw out is that a review with ten equally weighted comments teaches nothing; two blocking comments with mechanisms teach two things.
The mistake learners make: predicting Q6 as "yes — skew join is enabled by default". Enabled is not triggered. This is the single most useful ten minutes in the lab.
Second mistake: answering Q4 and Q16 with rules ("avoid UDFs", "don't use collect"). Make them rewrite each comment until it names what Spark does.
Timing: setup 10 min, Part 1 20 min, Part 2 30 min, Part 3 20 min, Part 4 10 min, Part 5 30 min. Run Part 5 as a group exercise if you have more than two people — compare the ordering, not the list.