Count the jobs, stages and tasks a short PySpark snippet launches
Read the snippet and say, for each action, how many jobs it launches, how many stages each job has and how many tasks run in each stage.
Constraints: the first line turns AQE off; spark.sql.shuffle.partitions keeps its default of 200; the scan reads 40 input partitions; nothing is cached; ignore any job Spark runs only to list files or read the Parquet schema.
from pyspark.sql import functions as F
spark.conf.set("spark.sql.adaptive.enabled", "false")
orders = spark.read.parquet("s3://lake/orders")
paid = orders.filter(F.col("status") == "paid")
by_user = paid.groupBy("user_id").agg(F.sum("amount").alias("total"))
top = by_user.filter(F.col("total") > 1000)
top.write.mode("overwrite").parquet("s3://lake/top_users")
print(top.count())Determine the jobs, stages and tasks.
Two actions, two jobs; transformations run nothing. write has 2 stages split at the groupBy shuffle: 40 scan tasks, then 200 for the final sum, filter and write. count() recomputes from the source in 3 stages: 40, 200, then 1 task for the global count.
- Counting one job per line of code instead of one per action
- Assuming
count()reuses the write's work when nothing was cached - Equating the task count with executor cores instead of partitions
- How would the stage and task counts change with AQE left on?
- What would
top.cache()before the write change for thecount()job?
Only an action launches a job, a shuffle ends a stage, and there is one task per partition.
top.write.mode("overwrite").parquet("s3://lake/top_users")
# job 1
# stage 1: 40 tasks — scan, filter, partial sum, shuffle write
# stage 2: 200 tasks — shuffle read, final sum, filter, file write
print(top.count())
# job 2 — nothing is cached, so the plan runs again from the source
# stage 1: 40 tasks — scan, filter, partial sum
# stage 2: 200 tasks — final sum, filter, partial count
# stage 3: 1 task — global count (Exchange SinglePartition)The filter, groupBy and agg lines only build the plan. count() on a DataFrame is a keyless aggregation: each of the 200 tasks counts its share, and one task adds them up after another exchange — hence the third stage.
With AQE on (the default since Spark 3.2) the Spark UI looks different: each shuffle stage is materialised separately and shows up as its own job, and AQE coalesces the 200 post-shuffle partitions into fewer, based on the real data size.