Determinism on Replay

Concepts covered: Distributed Primitives

Every recovery in this lesson replays work: Spark recomputes a lost partition, a relaunched driver reruns the program, a backfill rebuilds a day. Each replay assumes that evaluating the same expression on the same input gives the same rows. Some expressions break that assumption, and the failure is silent: the job succeeds and the numbers are wrong.

Expressions that change between evaluations

ExpressionWhat it depends onReplace it with
`F.rand()` after a shuffleRow order inside a partition, which a shuffle does not fixA hash of a stable key, such as `F.xxhash64("user_id")`
`F.current_date()`, `F.current_timestamp()`The clock when the run startsThe run's date, passed in as a parameter
`F.monotonically_increasing_id()`Partition index and row positionAn id from the source, or a hash of the natural key
`dropDuplicates(["event_uuid"])`Which copy reaches the task first`row_number()` over a complete ordering
`row_number()` ordered on a column with tiesArrival order among the tied rowsA unique column added to the ordering
`F.first("event_type")` in a `groupBy`Which row reaches the task first`F.max`, `F.min`, or a ranked pick
`limit(n)` with no `orderBy`Which rows reach the limit firstAn `orderBy` on a unique column before the limit

How a partial recompute corrupts a count

F.rand() fixes its seed when the query is planned and runs a generator per partition, so the value a row gets depends on its position in the partition. A file scan reads rows in the same order every time. A shuffle does not: a reducer fetches blocks from many map tasks in whatever order they arrive. Take a job that reads user_events, repartitions by user_id (shuffle 1), tags each row with F.when(F.rand() < 0.5, "A").otherwise("B"), and counts rows per bucket (shuffle 2). Map task 7 of the middle stage reads 10,000 rows and writes 2 partial counts. Its executor dies after the bucket A reducer has fetched them and before the bucket B reducer does. Spark reruns task 7, which fetches its rows again in a new order and draws new numbers.

Task 7's outputAttempt 1RecomputedUsed by the reducer
Bucket A5,0124,9915,012
Bucket B4,9885,0095,009
Total10,00010,00010,021

The job reports 10,021 rows from a task that read 10,000. The Spark UI shows a fetch failure and a stage retry, the same as for any lost executor, and every task finishes successfully.

Reruns need a fixed clock

F.current_date() is fixed once per query, so every row of a run agrees. The trouble is the next run. A job that processes F.date_sub(F.current_date(), 1) and runs on 2024-03-15 handles March 14. Rerun it on 2024-03-16 to repair March 14 and it processes March 15 instead and overwrites that partition. The job reports success while March 14 stays broken. Pass the date the run is for as a parameter, like the run_day of the overwrite section, and a rerun reads and writes the same day whenever it happens.

This job is rerun on the same input for the same run_day. Which expression can make the rerun write different rows?

events = spark.table("user_events")
daily = (events
    .filter(F.col("event_date") == run_day)
    .withColumn("sample", F.xxhash64("user_id") % 10 == 0)
    .groupBy("country", "sample")
    .agg(F.countDistinct("user_id").alias("users"),
         F.first("event_type").alias("example_event")))

Deduplicate with a complete ordering

The same event_uuid can appear on several rows of app_event_deliveries, 1 per delivery, with different received_ts values. dropDuplicates(["event_uuid"]) keeps 1 row per event, but which row depends on which copy reached the task first after the shuffle, so a rerun can keep a different received_ts and move an event into a different hour. Ranking by received_ts and then delivery_id gives every pair of rows a strict order, so rank 1 is the same row on every run. Run the cell. Then delete F.col("delivery_id").asc() from the ordering and work out whether 2 deliveries with equal received_ts could still trade places.

Do
  • Pass the date a run is for into the job as a parameter
  • End every ranking order with a unique column, such as delivery_id
  • Build sample buckets and synthetic ids from a hash of a stable key
  • Pick 1 row per group with max or min, or with a row_number over a full ordering
Avoid
  • Read current_date() in a job that may be rerun on a later day
  • Feed rand() computed after a shuffle into a later shuffle
  • Count on dropDuplicates or first() to choose a particular row
  • Join other tables on monotonically_increasing_id()

This job keeps 1 delivery per event_uuid from app_event_deliveries. Two deliveries of one event share the received_ts 2024-03-14 09:00:00 and carry different delivery_id values. Which change to the window keeps the same delivery on every rerun?

from pyspark.sql import functions as F
from pyspark.sql.window import Window

w = Window.partitionBy("event_uuid").orderBy(F.col("received_ts").asc())

firsts = (spark.table("app_event_deliveries")
    .withColumn("rn", F.row_number().over(w))
    .filter(F.col("rn") == 1)
    .drop("rn"))

About this lesson

This section is part of the Fault Tolerance: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.