≈ The Lake

Part 9 · Query execution · Chapter 35

Streaming reads and writes on table formats

Structured Streaming with Delta and Iceberg as sources and sinks: how the Delta source turns the log into offsets, how rate limits split commits, what happens when the source table is updated, and how the checkpoint and transaction identifiers make the sink exactly-once.

complete ~25 min

After this chapter you should be able to:
  • Explain the Delta source offset and how the source tails the log.
  • Predict how a stream reacts to OPTIMIZE, DELETE and MERGE on its source table.
  • Explain exactly-once sinks using the checkpoint's offset and commit logs and transaction identifiers.

A table’s log is already a stream: an ordered sequence of commits, each adding and removing files. Structured Streaming needs two things from a source, an offset that says how far it has read and a way to get the data between two offsets. From a sink it needs a way to make a replayed batch harmless. This chapter shows how Delta and Iceberg provide each, and how Spark’s checkpoint ties them together.

The simulator in src/sim/delta/stream.ts ports the Delta source’s offset logic, Spark’s restart rule and the Delta sink’s idempotence check. Its tests crash the query at both dangerous points and check that the sink ends up with every source row exactly once.

The Delta source offset

A DeltaSourceOffset has four fields:[DeltaSourceOffset.scala]

  • reservoirId, the table id, used to detect a checkpoint pointed at another table;
  • reservoirVersion, the table version being processed;
  • index, “The index in the sequence of AddFiles in this version. Used to break large commits into multiple batches”;
  • isInitialSnapshot, “Whether this offset points into an initial full table snapshot at the provided reservoir version rather than into the changes at that version”. It is serialized as isStartingVersion.

Offsets compare by (reservoirVersion, index). Two special indexes bracket each version: BASE_INDEX (serialized as −1) is before the version’s first file, and END_INDEX is after its last.[DeltaSourceOffset: indexes]

getFileChanges(fromVersion, fromIndex, isInitialSnapshot) produces the ordered sequence of IndexedFiles that offsets point into.[getFileChanges] For a new stream without startingVersion, isInitialSnapshot is true. The sequence then starts with every file of the snapshot at fromVersion, ordered by modification time and path, followed by the commits from fromVersion + 1. Otherwise it walks commits from fromVersion. For each commit, filterAndIndexDeltaLogs makes two passes:[filterAndIndexDeltaLogs]

  1. validateCommitAndDecideSkipping reads the whole commit and decides whether to fail or skip it (next sections).
  2. filterAndGetIndexedFiles keeps only AddFiles with dataChange = true, numbers them from 0, and wraps them with a BASE_INDEX and an END_INDEX placeholder.[filterAndGetIndexedFiles]

The result is cut to files after the start offset (exclusive) and up to the end offset (inclusive).[filterFilesAfterStartOffset, takeFilesUntilEndOffset]

Quiz Check: offsetsAnswers are scheduled for spaced review on the Review page.

Q1. What does a Delta source offset identify?

How sure are you?

Q2. A new stream starts on a Delta table at version 500 without startingVersion. What does it read first?

How sure are you?

Rate limits and batches

latestOffset decides where the next batch ends. It runs getFileChangesWithRateLimit, which takes files while admissionControl.admit(_), and turns the last admitted file into an offset.[getFileChangesWithRateLimit] maxFilesPerTrigger defaults to 1000; maxBytesPerTrigger can replace or join it.[DeltaOptions] admit always lets placeholders through, so empty commits do not count. For a file, it admits “if we still have capacity before we take it”, which guarantees progress even when one file is larger than the limit.[AdmissionLimits]

buildOffsetFromIndexedFile handles the end of a version. If the last admitted entry is a version’s END_INDEX, the offset becomes (version + 1, BASE_INDEX), so the next batch does not reopen a finished version. Otherwise the offset is (version, index), which may sit in the middle of a commit.[buildOffsetFromIndexedFile] That is how one commit with 2,500 files is split over three batches.

Because only data-changing adds are indexed, maintenance is invisible. OPTIMIZE writes its adds and removes with dataChange = false, so the stream neither re-reads the compacted data nor fails on the removes.

Quiz Check: rate limitsAnswers are scheduled for spaced review on the Review page.

Q1. maxFilesPerTrigger is 1000 (the default) and a single commit adds 2,500 files. What happens?

How sure are you?

Q2. OPTIMIZE compacts the source table while a stream reads it. What does the stream see?

How sure are you?

Updates and deletes in the source

A stream reads appends. When a commit removes data, the source cannot express “these rows are gone” as new rows, so validateCommitAndDecideSkipping decides:[validateCommitAndDecideSkipping]

val shouldAllowChanges = options.ignoreChanges || ignoreFileDeletion || skipChangeCommits
val shouldAllowDeletes = shouldAllowChanges || options.ignoreDeletes || ignoreFileDeletion
actions.foreach {
  case a: AddFile if a.dataChange => seenFileAdd = true
  case r: RemoveFile if r.dataChange =>
    skippedCommit = skipChangeCommits
    ...
}
if (removeFileActionPath.isDefined) {
  if (seenFileAdd && !shouldAllowChanges) throw DeltaErrors.deltaSourceIgnoreChangesError(...)
  else if (!seenFileAdd && !shouldAllowDeletes) throw DeltaErrors.deltaSourceIgnoreDeleteError(...)
}
  • A commit that only removes data, such as a DELETE of whole partitions, fails the stream unless ignoreDeletes is set.
  • A commit that removes and adds, such as UPDATE, MERGE or a DELETE that rewrites files, fails unless ignoreChanges or skipChangeCommits is set.
  • skipChangeCommits skips the whole commit, including its adds. ignoreChanges keeps the adds, so every rewritten file is emitted again, and rows that did not change arrive a second time. A third option, ignoreFileDeletion, is marked in the source as “Deprecated. Please use skipChangeCommits from now on.”

With deletion vectors, a DELETE adds the same path with a new DV and removes the old entry (chapter 34), which is a remove plus an add with dataChange = true, so it counts as a change. A stream that must see updates and deletes as events should read the change data feed instead (readChangeFeed, chapter 15), where the source also indexes RemoveFiles and CDC files.

Quiz Check: changes in the sourceAnswers are scheduled for spaced review on the Review page.

Q1. A DELETE rewrites some files of a streaming source table. Without options, what does the stream do?

How sure are you?

The micro-batch loop and the checkpoint

Spark’s MicroBatchExecution keeps two logs in the checkpoint directory. Before batch N runs, markMicroBatchStart writes offsets/N with every source’s end offset. After the sink has finished, markMicroBatchEnd writes commits/N.[markMicroBatchStart, markMicroBatchEnd] On restart, populateStartOffsets reads both:[populateStartOffsets]

Identify (from the offset log) the offsets used to run the last batch IF last batch exists THEN Set the next batch to be executed as the last recovered batch Check the commit log to see which batch was committed last IF the last batch was committed THEN … Setup for a new batch i.e., start = last batch end, and identify new end

So if offsets/7 exists without commits/7, batch 7 runs again with the same start and end offsets, and the Delta source returns exactly the same files. That makes the source replayable. Whether the replay duplicates output depends on the sink.

Where Spark can resume micro-batch 7
  1. Write offsets/7 Persist the source end offsets for the batch.
  2. Run batch 7 Read the selected source data and finish the sink write.
  3. Write commits/7 Record that the batch finished.
If Spark finds offsets/7 without commits/7 on restart, it replays batch 7. The sink needs an idempotent write to handle a completed output write followed by a crash.[Spark micro-batch execution]
Quiz Check: the checkpointAnswers are scheduled for spaced review on the Review page.

Q1. On restart, the checkpoint has offsets/7 but the latest commits entry is commits/6. What does Spark do?

How sure are you?

The Delta sink and transaction identifiers

The Delta protocol has an action for this case. It describes how the Delta sink uses it:[PROTOCOL.md: Transaction Identifiers]

  1. Check the current version of the transaction with appId = streamId in the target table. If this value is greater than or equal to the batch being written, then this data has already been added to the table and processing can skip to the next batch.
  2. Write the data optimistically into the table.
  3. Attempt to commit the transaction containing both the addition of the data written out and an updated appId version pair.

DeltaSink.addBatch does exactly that. It reads txn.txnVersion(queryId) and returns early with “Skipping already complete epoch” when it is at least batchId. Otherwise it writes the files and commits them with SetTransaction(appId = queryId, version = batchId, ...) in the same commit.[DeltaSink.addBatch][PendingTxn.commit] queryId is the query’s id, which is stored in the checkpoint and stays the same across restarts. Reading txnVersion also puts the appId into the transaction’s read set, so two writers that use the same appId conflict at commit time (chapter 10).

Together:

  • A crash after offsets/N and before the sink commit leaves nothing in the table; the re-run writes batch N once.
  • A crash after the sink commit and before commits/N leaves txn version N in the table; the re-run reads the same files, the sink sees txnVersion >= N, and skips.

The protocol also says “Delta only ensures that the latest version for a given appId is available in the table snapshot”, and leaves the meaning of version to the application. A new checkpoint gives a new query id and starts over at batch 0, which is why reusing a checkpoint matters.

Quiz Check: the sinkAnswers are scheduled for spaced review on the Review page.

Q1. How does the Delta sink make a re-run of batch 7 harmless? (Select all.) (select all that apply)

How sure are you?

Q2. Two different streaming queries write to the same Delta table. Why don't their batch ids collide in the txn actions?

How sure are you?

Iceberg streaming

Iceberg’s Spark source uses a StreamingOffset(snapshotId, position, scanAllFiles): a snapshot, the position of the last scanned file in it, and whether to scan all files of the snapshot, as when a stream starts on existing data.[StreamingOffset.java] It walks snapshots from the starting one through the current snapshot’s ancestors, and shouldProcess decides per snapshot operation: append is read, replace (compaction) is skipped, and delete and overwrite fail the stream unless streaming-skip-delete-snapshots or streaming-skip-overwrite-snapshots is true, in which case they are skipped.[BaseSparkMicroBatchPlanner] This matches Delta’s behavior: appends are data, compaction is not, and changes need an explicit choice.

The sink is idempotent by snapshot summary. Each streaming commit sets spark.sql.streaming.queryId and spark.sql.streaming.epochId in the snapshot summary. Before committing, findLastCommittedEpochId walks back from the current snapshot through parents to the most recent snapshot of this query, and the epoch is skipped if it is not newer.[SparkWrite: BaseStreamingWrite]

Quiz Check: IcebergAnswers are scheduled for spaced review on the Review page.

Q1. An Iceberg table read as a stream gets an overwrite snapshot (from a MERGE). By default, what happens?

How sure are you?

Q2. How does Iceberg's Spark streaming sink avoid committing an epoch twice?

How sure are you?

Try it

The source table starts with five files in two commits. The stream starts with no checkpoint, so batch 0 reads the initial snapshot.

  • With maxFilesPerTrigger = 2, run triggers and watch the offsets move through version 2 by index, then jump to version 3 at BASE_INDEX (shown as −1).
  • Append 3 files and run again. Then OPTIMIZE: the commit is grey (dataChange = false) and the next trigger finds no new data.
  • DELETE some rows: the next trigger fails. Pick skipChangeCommits, restart and run; or pick ignoreChanges and see the rewritten file arrive, with the sink ending up ahead of the source.
  • Crash after sink commit, restart, run: the events show the re-run batch skipped by the txn check. Crash after offsets/N: the re-run commits once. In both cases the sink matches the source.
Source table:
Query:

Query running. Source has 500 rows; sink has 0 rows.

Source _delta_log
  1. CREATE TABLE
  2. WRITE +f01+f02+f03
  3. WRITE +f04+f05
Checkpoint
batchoffsets/N (end)commits/N
Sink _delta_log
  1. CREATE TABLE
Events

    Summary

    • The Delta source’s offset is (version, index, isInitialSnapshot). getFileChanges indexes each commit’s data-changing AddFiles between BASE_INDEX and END_INDEX placeholders, after an initial snapshot for new streams.
    • maxFilesPerTrigger (default 1000) can split a commit across batches. At least one file is always admitted.
    • dataChange = false commits such as OPTIMIZE are invisible. Commits that remove data fail the stream unless ignoreDeletes, ignoreChanges or skipChangeCommits allow them; only the change data feed carries deletes and updates as events.
    • Spark writes offsets/N before a batch and commits/N after it, and re-runs a batch with its logged offsets when the commit is missing.
    • The Delta sink commits each batch with txn(queryId, batchId) and skips batches whose id is not newer, so replays are harmless. Iceberg does the same with snapshot summary properties, and its source reads appends, skips replaces, and needs options for deletes and overwrites.

    Primary sources

    Review this chapter

    This chapter has 10 quiz questions.

    Review this chapter's cards → Review all due cards