≈ The Lake

Part 4 · Delta Lake protocol · Chapter 11

Checkpoints, sidecars and log compaction

How a reader finds a snapshot without replaying every commit: _last_checkpoint, classic, multi-part and V2 (UUID-named) checkpoints, sidecar files, log compaction files and metadata cleanup.

complete ~45 min

After this chapter you should be able to:
  • Say exactly what a checkpoint must and must not contain.
  • Compare classic, multi-part and V2 (UUID-named) checkpoints, and say why multi-part is deprecated.
  • Pick the checkpoint a reader will use from a listing, including incomplete and same-version cases.
  • Walk through how the Spark connector writes a V2 checkpoint with sidecars.
  • Explain how log compaction files are chosen, and what metadata cleanup must keep.

Chapter 9 replayed a log from version 0. Real tables have hundreds of thousands of commits, and nobody replays those. A checkpoint is the reconciled state at one version, written out so readers can start there. This chapter covers what goes into one, the three ways to name it, how a reader chooses among several, how the Spark connector writes one, and the two related files: log compaction files and _last_checkpoint.

What a checkpoint contains

“A checkpoint contains the complete replay of all actions, up to and including the checkpointed table version, with invalid actions removed”, plus the remove tombstones that have not expired yet.[PROTOCOL] It is exactly the output of InMemoryLogReplay.checkpoint from chapter 9. Each row is one action, stored as a struct column per action type. The checkpoint must contain:[PROTOCOL]

  • the protocol and the metadata,
  • files added and not yet removed, and files recently removed whose tombstones have not expired,
  • transaction identifiers, and domain metadata that has not been removed,
  • with V2 checkpoints, a checkpointMetadata action and any sidecar actions.

It must not contain commitInfo or cdc actions. remove rows also drop stats and tags, because “VACUUM tombstones do not require stats or tags”.

Two table properties decide how per-file statistics are stored. delta.checkpoint.writeStatsAsJson (default true) keeps the JSON string stats. delta.checkpoint.writeStatsAsStruct (default false) adds stats_parsed and, for partitioned tables, partitionValues_parsed: typed columns that a reader can prune on without parsing JSON. With typed columns, data skipping over a checkpoint can read just the stats columns it needs instead of parsing a JSON string per file.

A checkpoint can be written for any committed version, but only “after the associated delta file has been successfully written”. Readers “SHOULD NOT make any assumptions about the existence or frequency of checkpoints”, with one exception: metadata cleanup must leave a checkpoint for the oldest version it keeps.[PROTOCOL] The Spark connector checkpoints after committing any version that is a non-zero multiple of delta.checkpointInterval, which defaults to 10.[src]

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

Q1. Which of these must a checkpoint at version n contain? (select all that apply)

How sure are you?

Q2. Which actions must a checkpoint NOT contain?

How sure are you?

Q3. What does delta.checkpoint.writeStatsAsStruct = true add to a checkpoint?

How sure are you?

Two specs, three names

The protocol separates what is inside a checkpoint (the spec) from what it is called (the naming scheme).[PROTOCOL]

  • V1 spec: a flat file with every action in it.
  • V2 spec: exactly one checkpointMetadata action, then every non-file action, and then either all the add/remove actions inline or all of them in sidecar files referenced by sidecar actions. Mixing the two is not allowed. Requires the v2Checkpoint table feature (reader version 3, writer version 7).[PROTOCOL]
Naming schemeFile nameV1V2
Classicn.checkpoint.parquetvalidvalid
Multi-part (deprecated)n.checkpoint.o.p.parquet, part o of pvalidinvalid
UUID-namedn.checkpoint.<uuid>.json or .parquetinvalidvalid

A V2 checkpoint with sidecars looks like this. The top-level file is small. The file actions, which are almost all of the bytes, live in _delta_log/_sidecars/:

{"checkpointMetadata":{"version":364475,"tags":{}}}
{"metaData":{...}}
{"protocol":{...}}
{"txn":{"appId":"3ba13872-2d47-4e17-86a0-21afd2a22395","version":364475}}
{"sidecar":{"path":"3a0d65cd-4056-49b8-937b-95f9e3ee90e5.parquet","sizeInBytes":2341330,"modificationTime":1512909768000,"tags":{}}}
{"sidecar":{"path":"016ae953-37a9-438e-8683-9a9a4a79a395.parquet","sizeInBytes":8468120,"modificationTime":1512909848000,"tags":{}}}

Why multi-part checkpoints are deprecated

A multi-part checkpoint was the old answer to “the state is too big for one file”: split it into p files, hash-partitioned by path (by (path, dvId) when deletion vectors are supported). The protocol now lists four problems, and the first two are about correctness:[PROTOCOL]

  1. A writer cannot validate the checkpoint before readers start using it, because the parts appear one by one.
  2. Two writers racing on the same version and part count can overwrite each other’s parts, “producing an arbitrary mix of checkpoint part files”.
  3. No room for optimizations such as skipping stats per part, or reusing parts across checkpoints.
  4. More files in _delta_log, so slower LIST.

A UUID-named V2 checkpoint fixes all four. Each writer’s top-level file has a unique name, so racers never collide; the top-level file appears in one PUT, after every sidecar it names is complete; sidecars can carry their own stats and be reused. When V2 checkpoints are enabled, writers should still occasionally write a classic-named checkpoint with the same content, so that old clients can find a protocol action and “fail gracefully with an invalid protocol version error”.[PROTOCOL]

Quiz Specs and namesAnswers are scheduled for spaced review on the Review page.

Q1. A V2 checkpoint has sidecars. Where may its add actions be?

How sure are you?

Q2. What is the main correctness problem with multi-part checkpoints?

How sure are you?

Q3. Which combination is invalid?

How sure are you?

Choosing a checkpoint

A listing can contain several checkpoints, at several versions, in several formats, some incomplete. The Spark connector turns each file name into a CheckpointInstance of (version, format, numParts, fileName). All parts of one multi-part checkpoint map to the same instance. Then getLatestCompleteCheckpointFromList keeps the instances not newer than the version to load, groups the files by instance, and keeps the complete ones:[src]

val complete = instances.filter(_ <= sentinelCv).groupBy(identity).filter {
  case (ci, matching) => ci.format match {
    case SINGLE     => matching.length == 1
    case WITH_PARTS => matching.length == ci.numParts.get   // every part must be listed
    case V2         => matching.length == 1
    ...
  }
}
if (complete.isEmpty) None else Some(complete.keys.max)

max uses CheckpointInstance.compare, which orders by version, then by format (SINGLE < WITH_PARTS < V2), then by number of parts, then by file name.[src] So at the same version a V2 checkpoint beats a multi-part one, which beats a classic one. The protocol leaves the choice open (“a client can choose which checkpoint to use”); this ordering is the Spark connector’s choice.

After that, getLogSegmentForVersion takes the commits after the chosen checkpoint and requires them to be contiguous, as in chapter 9.[src]

Loading version 15 from a checkpoint at 12
  1. Select checkpoint 12 Use the newest complete checkpoint at or before 15.
  2. Replay commits 13–15 Read every subsequent commit through the target.
  3. Snapshot 15 The checkpoint and replayed actions produce the requested state.
The checkpoint incorporates actions through version 12. Replay starts at version 13 and requires a contiguous suffix.[Delta log loading]

Try it. Toggle files in the listing and watch which checkpoint is chosen and what gets read. The selection code is src/sim/delta/checkpoints.ts, a port of the two functions above plus the compaction logic below, with tests for each case.

Files in _delta_log/

Commits 0.json to 24.json are always present unless removed below.

Checkpoint candidates

  1. v20 WITH_PARTS (2 parts)
    1 of 2 parts present: incomplete, ignored
  2. v10 SINGLEchosen
    single file present

Order: version, then format (SINGLE < WITH_PARTS < V2), then number of parts, then file name. compare ↗ · completeness ↗

Read plan

Snapshot version 24.

Start from 10.checkpoint.parquet

Then: 11.json12.json13.json14.json15.json16.json17.json18.json19.json20.json21.json22.json23.json24.json

Things to try:

  • Untick part 2 of the multi-part checkpoint at 20, or leave only part 1. The reader falls back to the checkpoint at 10.
  • Tick both parts and the V2 checkpoint at 20. V2 wins the tie.
  • Run metadata cleanup with no checkpoint ticked. The reader now has no way to rebuild versions 0 to 9, and refuses.
  • Make 22.json missing, then add the compaction 21.23.compacted.json. The reader still refuses: the compaction can stand in for the commits it covers, but the contiguity check runs on the plain commits first.
Quiz Choosing a checkpointAnswers are scheduled for spaced review on the Review page.

Q1. The listing has 10.checkpoint.parquet and two of the three parts of a checkpoint at 20. Which checkpoint does the reader use?

How sure are you?

Q2. At version 20 there is a classic checkpoint, a complete 2-part checkpoint and a UUID-named V2 checkpoint. Which does the Spark connector pick?

How sure are you?

Q3. You read VERSION AS OF 15. Checkpoints exist at 10 and 20. Which is used?

How sure are you?

Writing a checkpoint

Here is the sequence when the Spark connector writes a V2 checkpoint with sidecars after commit 30:

Writing a V2 checkpoint
Writerpost-commit hookExecutorsone task per sidecar_sidecars/Parquet, file actions_delta_log/top-level checkpointReaderany other client1. commit v=30 succeeded2. stateDS.repartition(n, path)3. PUT <uuid>.parquet × n4. file statuses, counts5. PUT 30.checkpoint.<uuid>.json6. LIST: sees the new checkpoint7. overwrite _last_checkpoint8. metadata cleanup
  1. commit v=30 succeeded. After a successful commit, isCheckpointNeeded is true when the committed version is non-zero and a multiple of delta.checkpointInterval (default 10). The checkpoint runs after the commit, and its exceptions are caught and logged: if it fails, the commit still stands. TransactionHelper.scala ↗
  2. stateDS.repartition(n, path). The snapshot state (already reconciled) is repartitioned by add.path/remove.path. With V2 checkpoints and no explicit part size, n = ceil((files + tombstones) / 50,000). Only add and remove go to sidecars; remove loses stats and tags. writeCheckpoint ↗
  3. PUT <uuid>.parquet × n. Each task writes one uniquely named sidecar. If the log store says a partially written file could be visible (isPartialWriteVisible), the task writes a hidden .<name>.<uuid>.tmp file and renames it into place; otherwise it writes the final name directly. getCheckpointWritePath ↗
  4. file statuses, counts. The driver checks that the number of add actions written equals snapshot.numOfFiles, and throws if not. checkpointMismatchWithSnapshot ↗
  5. PUT 30.checkpoint.<uuid>.json. The top-level V2 checkpoint: exactly one checkpointMetadata, then protocol, metaData, txn, domainMetadata and one sidecar action per sidecar file. Its unique name means racing writers never overwrite each other. PROTOCOL.md: V2 spec ↗
  6. LIST: sees the new checkpoint. Readers can use the checkpoint as soon as it is listed, even before _last_checkpoint moves. A reader that still finds the old pointer just lists a few more files.
  7. overwrite _last_checkpoint. Written after the checkpoint files, with version, size, sizeInBytes, numOfAddFiles, the schema and optionally a checksum. With V2 checkpoints, the writer may embed the checkpoint's non-file actions here so readers skip reading the top-level file. checkpointAndCleanUpDeltaLog ↗
  8. metadata cleanup. Then doLogCleanup. The procedure in the spec: keep the newest checkpoint not newer than the retention cutoff (delta.logRetentionDuration, default 30 days) and everything after it; delete older commits, checkpoints and checksum files, and sidecars that no checkpoint references and are more than a day old. PROTOCOL.md ↗
Follows Checkpoints.writeCheckpoint and checkpointAndCleanUpDeltaLog at 25561a5. With V2 checkpoints off, the same job writes one classic file (or legacy parts) instead of sidecars.

The core of writeCheckpoint, trimmed:[src]

val checkpointPartSize = sessionConf.getConf(DELTA_CHECKPOINT_PART_SIZE)
  .orElse(if (v2CheckpointEnabled) Some(50000L) else None)
val numParts = checkpointPartSize.map { partSize =>
  math.ceil((snapshot.numOfFiles + snapshot.numOfRemoves).toDouble / partSize).toLong.max(1L)
}.getOrElse(1L).toInt

val base = snapshot.stateDS
  .repartition(numParts, coalesce(col("add.path"), col("remove.path")))
// V2: keep only add/remove for the sidecars; non-file actions go in the top-level file later.
// Classic: drop commitInfo, cdc, checkpointMetadata, sidecar. Both: remove.stats/tags dropped.

Three properties make this safe:

  • It runs after the commit. A non-fatal failure is caught and logged rather than surfaced as a failed write (unless tests or the session conf behind DELTA_CHECKPOINT_THROW_EXCEPTION_WHEN_FAILED ask it to rethrow), because “from the perspective of the user, the commit has completed successfully”.[src]
  • It checks itself. If the number of add rows written differs from snapshot.numOfFiles, it throws checkpointMismatchWithSnapshot instead of publishing a wrong checkpoint.[src]
  • Order of publication. Sidecars first, then the top-level file that names them, then _last_checkpoint, then cleanup.[src] A reader that sees the top-level file can always read every sidecar it references.

delta.checkpointPolicy chooses between classic (the default) and v2.[src]

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

Q1. The checkpoint after commit 30 fails with an I/O error. What happens to commit 30?

How sure are you?

Q2. In which order does the Spark connector publish a V2 checkpoint with sidecars?

How sure are you?

Log compaction files

A log compaction file x.y.compacted.json holds the reconciled actions of commits x to y: the same reconciliation as a checkpoint, over a range instead of a prefix. Readers “can optionally consume” them, and “the compaction replaces the corresponding commits during action reconciliation”.[PROTOCOL] They help when the tail after the last checkpoint is long and full of small commits, such as frequent streaming appends.

The spec’s example: commits 4, 5 and 6 add f2, remove f1, add f3 and f4, remove f3, and bump a txn from 4389 to 4390. The compaction keeps add f2, add f4, remove f1, remove f3 and only the final txn.

The Spark connector selects them in useCompactedDeltasForLogSegment. It walks commits and compactions in file-name order, so x.y.compacted.json comes before x.json. It greedily takes a compaction when its start is after everything covered so far and its end does not pass the target version. Then it checks that the result covers every version from the checkpoint to the target exactly once, and falls back to plain commits otherwise.[src] A compaction that straddles the checkpoint, or runs past a time-travel target, is skipped.

The _last_checkpoint hint

_last_checkpoint is a small JSON file that is overwritten in place. Its fields are version and size (number of actions), plus optional parts, sizeInBytes, numOfAddFiles, checkpointSchema, tags and checksum.[PROTOCOL] The checksum is an MD5 over a canonical form of the JSON: sorted key paths, URL-encoded strings, and the checksum key itself excluded. It exists because the file is overwritten and can be read half-written or stale.

It is only a hint. The reader still lists from that version and trusts the listing. If the checkpoint it names is gone, the connector looks for an older one rather than failing outright.[src] With V2 checkpoints, a writer may embed the checkpoint’s non-file actions in _last_checkpoint, so a reader can learn the protocol and metadata from one small GET.[PROTOCOL]

Quiz Compaction and pointersAnswers are scheduled for spaced review on the Review page.

Q1. The latest checkpoint is at 5. The log has 4.6.compacted.json and commits 6 to 9. What does the reader replay after the checkpoint?

How sure are you?

Q2. _last_checkpoint says version 40, but a checkpoint at 50 was written a moment ago. What does a reader end up using?

How sure are you?

Q3. Metadata cleanup keeps the checkpoint at 100 as the oldest restore point. Why must it also keep 100.json?

How sure are you?

Summary

  • A checkpoint is the reconciled state at one version: protocol, metadata, live files, unexpired tombstones, txns, domain metadata. It never contains commitInfo or cdc.
  • V1 is flat. V2 has checkpointMetadata and puts either all file actions inline or all of them in sidecars. UUID-named checkpoints are V2 only; multi-part checkpoints are V1 only and deprecated, because they cannot be published atomically.
  • Readers ignore incomplete multi-part checkpoints and checkpoints newer than the version to load. The Spark connector breaks ties by format, then parts, then file name.
  • Writers publish sidecars, then the top-level checkpoint, then _last_checkpoint, then clean up. Checkpoint failures never fail the commit.
  • Log compaction files stand in for a range of commits only when they fit the segment exactly.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 14 quiz questions.

Review this chapter's cards → Review all due cards