≈ The Lake

Part 4 · Delta Lake protocol · Chapter 9

The Delta log: actions and replay

The _delta_log directory, every action type and its fields, and the reconciliation rules that turn a sequence of commits into a snapshot.

complete ~55 min

After this chapter you should be able to:
  • Name the five things a snapshot consists of, and the action that sets each one.
  • Replay a log by hand into a snapshot, including tombstones and deletion vectors.
  • Explain the (path, deletionVector.uniqueId) primary key for logical files and why it matters for DVs.
  • Trace how a reader finds the files to read: _last_checkpoint, LIST, log segment, contiguity check.
  • Explain how Spark replays the log in parallel without breaking per-file ordering.

A Delta table is a directory of Parquet files plus a log that says which of them are in the table. Chapter 10 is about how a new entry gets into that log. This chapter is about the other direction: how a reader turns the log into a snapshot, the exact set of files and metadata at one version. That process is called log replay, and every query on a Delta table starts with it.

A table is a serial history of versions

The protocol defines a table as “a single serial history of atomic versions, which are named using contiguous, monotonically-increasing integers.”[PROTOCOL] The state at one version is a snapshot, and it has exactly five parts. Each part is set by one kind of action, and when several commits set the same part, the protocol’s reconciliation rules say which action counts:

PartSet byReconciliation rule
Protocol: reader and writer versions, table featuresprotocollatest wins
Metadata: id, schema, partition columns, configurationmetaDatalatest wins, and replaces the old one completely
Set of files, with their metadataaddnewest action per logical file decides
Set of tombstones (recently removed files)removesame rule, from the other side
Application transactionstxnlatest version per appId wins

The reconciliation rules add one more collection: the live domainMetadata per domain. commitInfo is not part of the reconciled state. You get the commitInfo of the snapshot’s own version only, read from that version’s JSON file.[PROTOCOL]

On disk, the example in the spec looks like this:

/mytable/_delta_log/00000000000000000042.json
/mytable/_delta_log/00000000000000000042.checkpoint.parquet
/mytable/_delta_log/00000000000000000043.json
/mytable/_delta_log/00000000000000000044.json
/mytable/_delta_log/00000000000000000045.json
/mytable/_delta_log/_last_checkpoint
/mytable/_change_data/cdc-00000-924d9ac7-....snappy.parquet
/mytable/part-00000-3935a07c-....snappy.parquet
/mytable/deletion_vector-0c6cbaaf-....bin

Each N.json is a delta file: newline-delimited JSON, one action per line, “an atomic set of actions that should be applied to the previous table state corresponding to version v-1, in order to construct the vth snapshot”.[PROTOCOL] A checkpoint is the same state written out in Parquet, so a reader can start there instead of at version 0. Chapter 11 covers checkpoints in depth; here we only need the fact that one exists.

Quiz Versions and snapshotsAnswers are scheduled for spaced review on the Review page.

Q1. Which of these are part of a Delta snapshot's reconciled state? (select all that apply)

How sure are you?

Q2. What does the delta file 00000000000000000007.json contain?

How sure are you?

Q3. A data file lives at date=2026-11-01/part-a.parquet. Where must a reader get its partition value from?

How sure are you?

The actions

Every line in a delta file is one JSON object with exactly one key, the action type. The ones that matter for replay:

ActionRequired fields (abridged)Notes
metaDataid, format, schemaString, partitionColumns, configurationThe first version must contain one. At most one per version. A later one “completely overwrite[s]” the current metadata.[PROTOCOL]
protocolminReaderVersion, minWriterVersion (+ readerFeatures at reader version 3, writerFeatures at writer version 7)Gates which clients may read or write. Chapter 12.
addpath, partitionValues, size, modificationTime, dataChangeOptional stats, tags, deletionVector, baseRowId, defaultRowCommitVersion, clusteringProvider.
removepath, dataChangedeletionTimestamp (optional) drives tombstone expiry. Optional partitionValues, size, stats, deletionVector.
txnappId, versionOptional lastUpdated. Chapter 10 covers how sinks use it.
domainMetadatadomain, configuration, removedremoved = true is a tombstone for the domain.
commitInfonone: any JSONProvenance. Must be first, with inCommitTimestamp, when in-commit timestamps are on.
cdcpath, partitionValues, size, dataChangeChange data files for CDF. dataChange is always false. Not part of the snapshot.

Three details in add and remove carry more weight than they look.

dataChange. When false, the action “only rearranges existing data or adds new statistics”. For add: “the logical file must already be present in the table or the records in the added file must be contained in one or more remove actions in the same version”.[PROTOCOL] OPTIMIZE writes dataChange = false, which is why streaming readers can skip its commits and why it can run at snapshot isolation (chapter 10).

Partition values are strings. A date is {year}-{month}-{day}, numbers are their string form, booleans are "true"/"false", and “an empty string for any type translates to a null partition value”.[PROTOCOL]

Statistics are a JSON string. stats holds numRecords, minValues, maxValues, nullCount and tightBounds. When a file has a deletion vector, numRecords “must equal the number of records in the data file, not the valid records in the logical file”, and min/max may be wide bounds that still include deleted rows.[PROTOCOL] Chapter 8 shows how scans use them.

Here is version 3 of the sample table used below: a copy-on-write DELETE that rewrote one file.

{"commitInfo":{"timestamp":1764000180000,"operation":"DELETE","operationParameters":{"predicate":"[\"(id = 2)\"]"},"isBlindAppend":false}}
{"remove":{"path":"date=2026-11-01/part-a.parquet","deletionTimestamp":1764000180000,"dataChange":true}}
{"add":{"path":"date=2026-11-01/part-d.parquet","partitionValues":{"date":"2026-11-01"},"size":850,"dataChange":true,"stats":"{\"numRecords\":2}"}}
Quiz ActionsAnswers are scheduled for spaced review on the Review page.

Q1. Version 6 contains a metaData action that only sets one new table property. What happens to the schema and partition columns from the previous metaData?

How sure are you?

Q2. What does dataChange: false on an add promise?

How sure are you?

Q3. An add has "partitionValues": {"country": ""}. What is the partition value?

How sure are you?

Q4. A file of 1,000 rows has a deletion vector marking 10 rows deleted. What must stats.numRecords say?

How sure are you?

Action reconciliation

A logical file is not a path. It is “a path to a data file, combined with an optional Deletion Vector (DV)”, and its primary key is the tuple (path, deletionVector.uniqueId), or (path, NULL) with no DV.[PROTOCOL] The rule is short: “scan all file actions and keep only the newest reference for each logical file.” Newest add means live; newest remove means tombstone; the two sets never share a key.[PROTOCOL]

One logical file through three commits
  1. v4 · add A A is live. Include it in the snapshot.
  2. v5 · remove A A becomes a tombstone. Skip it in scans.
  3. v6 · add A A becomes live again. Clear its tombstone.
A represents one logical key, consisting of a path and a deletion-vector ID or NULL. The last action for that key determines its state.[Delta protocol]

The reference implementation is InMemoryLogReplay. Trimmed, its append is the whole algorithm:[src]

def append(startVersion: Long, endVersion: Long, actions: Iterator[Action]): Unit = {
  assert(currentVersion == -1 || startVersion == currentVersion + 1, ...)  // no gaps
  currentVersion = endVersion
  actions.foreach {
    case a: SetTransaction                 => transactions(a.appId) = a
    case a: DomainMetadata if a.removed    => domainMetadatas.remove(a.domain)
    case a: DomainMetadata                 => domainMetadatas(a.domain) = a
    case a: Metadata                       => currentMetaData = a
    case a: Protocol                       => currentProtocolVersion = a
    case add: AddFile =>
      val key = add.toUniqueFileActionTuple(tableRoot, ...)      // (canonical URI, dv id)
      activeFiles(key) = add.copy(dataChange = false)
      cancelledRemoveFiles.remove(key)                            // only one action per key survives
      activeRemoveFiles.remove(key)
    case remove: RemoveFile =>
      val key = remove.toUniqueFileActionTuple(tableRoot, ...)
      activeFiles.remove(key) match {
        case Some(_) => cancelledRemoveFiles(key) = remove        // it cancelled a live add
        case None    => activeRemoveFiles(key) = remove           // nothing to cancel in this replay
      }
    case _: CommitInfo | _: AddCDCFile     => // not part of the state
  }
}

Notice what this does and does not do.

  • The key includes the DV. A DELETE with deletion vectors writes remove(path, no DV) and add(path, DV d1) in one commit. Different keys: the old logical file becomes a tombstone, the new one is live, and both name the same Parquet file. A second DELETE on that file writes remove(path, d1) and add(path, d2). The protocol forbids the same path appearing twice with different DVs within the add set of one commit, so there is never ambiguity about which DV is current.[PROTOCOL]
  • dataChange is reset to false. It describes a change; a snapshot has no changes, only state.
  • Order matters only within a key. Two actions on different keys commute. That fact is what makes the distributed version below possible.
  • Tombstones are pruned on output, not on input. getTombstones drops removes whose deletionTimestamp is not after minFileRetentionTimestamp; getTransactions drops txns not updated after minSetTransactionRetentionTimestamp, if one is set.[src]

When the state is written out, for a checkpoint or for the cached snapshot, the order is protocol, metadata, domain metadata, transactions, then file actions sorted by path.[src]

Quiz ReconciliationAnswers are scheduled for spaced review on the Review page.

Q1. What is the primary key of a logical file during reconciliation?

How sure are you?

Q2. A commit contains remove(part-b.parquet, no DV) and add(part-b.parquet, DV u4fZ). After replay, what is in the state for part-b.parquet?

How sure are you?

Q3. You load a snapshot at version 42 from a checkpoint at 40 plus 41.json and 42.json. Where does the snapshot's commitInfo come from?

How sure are you?

Replay a log yourself

The sample table has eight commits. It is partitioned by date, gets an append, a streaming append with a txn, a copy-on-write DELETE, an OPTIMIZE, another streaming batch, a protocol upgrade that enables deletion vectors, and a DELETE that adds a DV to part-b. Step through it action by action. The engine is src/sim/delta/replay.ts, a direct port of append above, with tests that pin the outcome of every scenario on this page.

Read plan (getLogSegmentForVersion): list _delta_log/ from version 0, no usable checkpoint, then replay 0.json, 1.json, 2.json, 3.json, 4.json, 5.json, 6.json, 7.json.

0 / 25 actions

What gets replayed

  1. commitInfo CREATE TABLE
  2. protocol (1, 2)
  1. commitInfo WRITE
  2. add date=2026-11-01/part-a.parquet
  3. add date=2026-11-02/part-b.parquet
  1. commitInfo STREAMING UPDATE
  2. txn stream-orders → 0
  3. add date=2026-11-01/part-c.parquet
  1. commitInfo DELETE
  2. remove date=2026-11-01/part-a.parquet
  3. add date=2026-11-01/part-d.parquet
  1. commitInfo OPTIMIZE
  2. remove date=2026-11-01/part-c.parquet (dataChange=false)
  3. remove date=2026-11-01/part-d.parquet (dataChange=false)
  4. add date=2026-11-01/part-e.parquet (dataChange=false)
  1. commitInfo STREAMING UPDATE
  2. txn stream-orders → 1
  3. add date=2026-11-02/part-f.parquet
  1. commitInfo SET TBLPROPERTIES
  2. protocol (3, 7) deletionVectors
  1. commitInfo DELETE
  2. remove date=2026-11-02/part-b.parquet
  3. add date=2026-11-02/part-b.parquet + DV u4fZ

Snapshot state

protocol
–
metaData
–
txn
–
Live files (add) what a query reads
  • none
Tombstones (remove) kept for VACUUM
  • none

Things to try:

  • Step to version 3. remove part-a cancels a live add and becomes a tombstone.
  • Step through version 7. remove part-b (no DV) and add part-b + DV u4fZ have different keys, so you end with one live file and one tombstone for the same Parquet file.
  • Tick “Checkpoint exists at version 5” and replay again. The reader starts from the checkpoint’s reconciled state, which has no commitInfo and none of the cancelled history. The final state is identical.
  • With the checkpoint ticked, pick snapshot version 4. The checkpoint is newer than the version you asked for, so the reader cannot use it and replays from 0.

Loading a snapshot

Replay needs a list of files to replay. Choosing that list is the job of SnapshotManagement, and it is where the object store’s listing behavior matters. Here is the sequence for loading the latest version of the sample table with a checkpoint at 5:

Loading the latest snapshot
ReaderSpark driver, DeltaLog_last_checkpointsmall JSON file_delta_log/commits, checkpointsExecutorsstate reconstructionTable directoryParquet data files1. GET _last_checkpoint2. {"version": 5, ...}3. LIST from 00…054. 5.checkpoint, 5.json, 6.json, 7.json5. getLogSegmentForVersion6. stateReconstruction7. repartition by path, sort by version8. state: adds, tombstones, txns9. read live files only
  1. GET _last_checkpoint. On first load, createSnapshotAtInit reads _last_checkpoint, a pointer "to near the end of the log", so the reader does not have to list a directory that may hold 10,000+ files. SnapshotManagement.scala ↗
  2. {"version": 5, ...}. A hint, not the truth: writers update it after writing the checkpoint, and it may lag. A missing file just means listing from version 0.
  3. LIST from 00…05. createLogSegment lists from max(0, lastCheckpointVersion). Because names are zero-padded to 20 digits, a lexicographic, paginated LIST starting at that prefix returns exactly the newer files. createLogSegment ↗
  4. 5.checkpoint, 5.json, 6.json, 7.json. Commits and checkpoints at or after version 5. Anything older is not needed and may already have been deleted by metadata cleanup. PROTOCOL.md ↗
  5. getLogSegmentForVersion. Pick the newest complete checkpoint not newer than the version to load, keep the deltas after it, and check they are contiguous (verifyDeltaVersions). A gap is an error, never a silent skip. getLogSegmentForVersion ↗
  6. stateReconstruction. The log segment becomes a Dataset: the checkpoint plus 6.json and 7.json, each action tagged with its commit version. Snapshot.scala ↗
  7. repartition by path, sort by version. All actions for one file land in one partition, in version order. Each partition runs its own InMemoryLogReplay. Actions with no path (protocol, metaData, txn) collocate in a single partition. InMemoryLogReplay.scala ↗
  8. state: adds, tombstones, txns. The reconciled state is cached. Queries use the add actions; remove tombstones only matter to VACUUM.
  9. read live files only. Scans read the files listed in add actions after pruning by partition values and per-file stats. A data file in the directory that no add references is invisible, however new it is. PROTOCOL.md ↗
Follows SnapshotManagement and Snapshot at 25561a5. The update() path for an already-loaded table reuses the previous snapshot's checkpoint instead of reading _last_checkpoint.

Three parts deserve a closer look.

Listing from a version. _last_checkpoint exists because “the Delta transaction log will often contain many (e.g. 10,000+) files”, and “due to the zero-padded encoding of the files in the log, the version id of this recent checkpoint can be used on storage systems that support lexicographically-sorted, paginated directory listing to enumerate any delta files or newer checkpoints”.[PROTOCOL] S3’s ListObjectsV2 with start-after is exactly such a listing. createLogSegment lists from max(0, lastCheckpointVersion).[src]

Choosing the segment. getLogSegmentForVersion partitions the listing into checkpoints and deltas, picks the newest complete checkpoint not newer than the version to load, keeps the deltas after it, and validates them.[src] Validation is strict: verifyDeltaVersions checks that the versions form an unbroken range, start right after the checkpoint and end at the requested version, and throws otherwise.[src] A missing 7.json between 6.json and 8.json is corruption or a listing anomaly, never something to skip.

Replaying in parallel. For a large table the log segment can hold millions of actions, so the Spark connector replays it as a Spark job:[src]

// Snapshot.stateReconstruction (trimmed)
loadActions                                                // checkpoint + deltas, each row tagged with its commit version
  .withColumn("add_path_canonical",    when(col("add.path").isNotNull,    canonicalPath(col("add.path"))))
  .withColumn("remove_path_canonical", when(col("remove.path").isNotNull, canonicalPath(col("remove.path"))))
  .repartition(getNumPartitions, coalesce(col("add_path_canonical"), col("remove_path_canonical")))
  .sortWithinPartitions(COMMIT_VERSION_COLUMN)
  .mapPartitions { iter =>
    val state = new InMemoryLogReplay(Some(minFileRetentionTimestamp), minSetTransactionRetentionTimestamp, ...)
    state.append(0, iter.map(_.unwrap))
    state.checkpoint.map(_.wrap)
  }

Hash-partitioning by canonical path puts every action for a file in one partition, and sorting by commit version restores the only order that matters, the order within a key. Each partition runs its own InMemoryLogReplay with no coordination. Actions with no path (protocol, metadata, txn) all hash to the null key and “will be collocated to a single partition”. The result is cached as the snapshot’s state.

Quiz Loading a snapshotAnswers are scheduled for spaced review on the Review page.

Q1. What is _delta_log/_last_checkpoint for?

How sure are you?

Q2. The listing after checkpoint 5 returns 6.json and 8.json, but no 7.json. What does the Spark connector do?

How sure are you?

Q3. Spark replays a large log as a job. Why does it repartition by canonical path and sort by commit version within each partition?

How sure are you?

Tombstones, retention and time travel

Three table properties decide how much history survives. Their defaults are defined in DeltaConfig.scala:

PropertyDefaultWhat it bounds
delta.deletedFileRetentionDurationinterval 1 weekHow long remove tombstones stay in the state, and how old a file must be before VACUUM may delete it.[src]
delta.logRetentionDurationinterval 30 daysHow long JSON commits and checkpoints are kept before metadata cleanup.[src]
delta.setTransactionRetentionDurationunsetWhen set, txn entries older than this drop out of the state.[src]
delta.checkpointInterval10After committing version v, the writer checkpoints when v is a non-zero multiple of this.[src]

Tombstones exist “only for the benefit of the VACUUM command”.[PROTOCOL] A reader on an old snapshot may still be reading a file that a newer version removed, so physical deletion has to wait. The protocol says a tombstone expires when the current time, by the clock of whoever runs the cleanup, exceeds the remove’s timestamp plus the threshold.[PROTOCOL]

Time travel is replay with a versionToLoad. getSnapshotAtInternal ignores any checkpoint hint newer than the requested version, finds the last complete checkpoint at or before it, and builds the log segment from there.[src] So time travel needs two things to still exist: a checkpoint at or before the target, and every JSON commit from that checkpoint to the target. Metadata cleanup is designed around exactly that. It keeps the newest checkpoint not newer than the cutoff, plus “the JSON commit file at that version” (checkpoints do not keep commitInfo), and every commit after it.[PROTOCOL]

The data files are the other half. A snapshot whose files VACUUM has already deleted can be replayed but not read. When the session conf for it is enabled, the connector refuses to time travel further back than deletedFileRetentionDuration.[src]

Quiz Retention and time travelAnswers are scheduled for spaced review on the Review page.

Q1. There is a checkpoint at version 50. You query VERSION AS OF 45. Can the reader start from the checkpoint at 50?

How sure are you?

Q2. Why does a snapshot keep remove tombstones at all, and for how long by default?

How sure are you?

Q3. Metadata cleanup deletes old log files. Which must it keep for the oldest version it preserves? (select all that apply)

How sure are you?

Summary

  • A snapshot is protocol, metadata, live files, tombstones and app transactions, plus domain metadata. It is computed, never stored, except as a checkpoint of that computation.
  • A logical file is (path, deletionVector.uniqueId). The newest action per key decides: an add makes it live, a remove makes it a tombstone. Protocol and metadata: latest wins. txn: latest per appId wins.
  • A reader lists _delta_log/ from the last checkpoint, picks the newest usable checkpoint, and requires contiguous deltas after it.
  • Spark replays in parallel by hash-partitioning on the canonical path and sorting by commit version, because order matters only within a key.
  • Tombstones (default one week), log retention (default 30 days) and VACUUM together decide how far back time travel can go.

Concepts in this chapter

Explained here

From other chapters

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 16 quiz questions.

Review this chapter's cards → Review all due cards