≈ The Lake

Part 4 · Delta Lake protocol · Chapter 13

Deletion vectors and row tracking

Merge-on-read in Delta: the deletion vector descriptor, the Roaring bitmap storage format, inline vs on-disk DVs, how DELETE writes them and scans apply them, and row IDs and row commit versions.

complete ~45 min

After this chapter you should be able to:
  • Decode a deletion vector descriptor and locate its bitmap.
  • Explain how DVs change the actions a DELETE, UPDATE or MERGE commits.
  • Read the Roaring container layout and predict which container type a set of rows produces.
  • Explain baseRowId, defaultRowCommitVersion and the row ID high-water mark, including how conflicts reassign them.

Parquet files are immutable, so before deletion vectors, deleting one row meant rewriting its whole file. A DELETE that touched one row in each of 1,000 files rewrote 1,000 files. A deletion vector (DV) records “rows 3, 4 and 7 of this file are gone” in a small side file instead, and readers skip those rows. This is merge-on-read: writes get cheap, and reads pay a little to apply the DVs. Row tracking comes in the same chapter because it uses the same idea, a row’s position in its file, to give every row an id.

Merge-on-read in Delta

deletionVectors is a reader-writer feature: it needs reader 3, writer 7, and the name in both lists (chapter 12). The property delta.enableDeletionVectors controls only writing: “Writers must only write new Deletion Vectors (DVs) when this property is set to true”. Readers “must read the table considering the existence of DVs, even when the delta.enableDeletionVectors table property is not set”.[PROTOCOL]

A DV is attached to an add (or remove) as a deletionVector struct. The data file plus its DV is a logical file. Deleting more rows from a file that already has a DV commits two actions with the same path: a remove carrying the old DV and an add carrying the new one. This is why chapter 9 reconciles on (path, deletionVector.uniqueId) and not on path alone.[src]

{"remove": {"path": "part-0.parquet", "deletionVector": {"storageType": "u", "pathOrInlineDv": "ab^-aqEH.-t@S}K{vb[*k^", "offset": 1, "sizeInBytes": 44, "cardinality": 6}, ...}}
{"add":    {"path": "part-0.parquet", "deletionVector": {"storageType": "u", "pathOrInlineDv": "cd…", "offset": 1, "sizeInBytes": 46, "cardinality": 9}, ...}}
A deletion vector masks physical row positions
The Parquet file contains rows at positions 0 through 3. A deletion vector marks positions 1 and 3 as deleted. The scan returns rows 0 and 2, and the file still contains all four rows. Parquet file 4 physical rows Row 0 Visible Row 1 Masked Row 2 Visible Row 3 Masked Apply DV {1, 3} Scan output Row 0 Row 2
The vector stores positions within the data file. Publishing the new vector changes which rows a scan returns while keeping the Parquet bytes in place.[Delta protocol]

Two writer rules come with this. A logical file with a DV must have an accurate numRecords in its stats, and it must count the physical rows, not the surviving ones.[PROTOCOL][PROTOCOL] Min and max values may also be stale after a DV is added. stats.tightBounds = false tells data skipping that the bounds are wide: still safe to prune on, but not exact. The Spark connector sets wide bounds when it attaches a DV.[src]

Quiz Merge-on-readAnswers are scheduled for spaced review on the Review page.

Q1. A DELETE matches one row in each of 1,000 files. With DVs enabled, what does it write?

How sure are you?

Q2. A file already has a DV. A second DELETE removes more rows from it. Which actions are committed for that file?

How sure are you?

Q3. delta.enableDeletionVectors was turned off, but some files still have DVs. What must a reader do?

How sure are you?

Q4. A file has 100 physical rows and a DV with cardinality 10. What must stats.numRecords say?

How sure are you?

The descriptor

FieldMeaning
storageTypeu: a file under the table root, named from a UUID. i: inline in the log. p: an absolute path.
pathOrInlineDvFor u, an optional random prefix plus a 20-character Z85 UUID. For i, the Z85-encoded bitmap. For p, the path.
offsetWhere the DV starts in its file. Absent for i; treat as 0 if absent otherwise.
sizeInBytesThe serialized bitmap’s size, before Z85 encoding.
cardinalityHow many rows it deletes.

Two fields are derived. uniqueId is <storageType><pathOrInlineDv>, plus @<offset> when there is an offset. absolutePath for u is <table>/<random prefix>/deletion_vector_<uuid>.bin.[PROTOCOL] The spec’s first example, ab^-aqEH.-t@S}K{vb[*k^, has the prefix ab; the last 20 characters decode to d2c639aa-8816-431a-aaf6-d3fe2512ff61. The random prefix spreads DV files across object-store key prefixes.

Z85 is ZeroMQ’s Base85 variant, chosen because it is “JSON-friendly”. Delta’s codec reads each big-endian 4-byte block as one number and writes it as 5 base-85 digits. Input that isn’t a multiple of 4 is zero-padded, and sizeInBytes tells the decoder how many bytes to keep.[src]

The bitmap format

A DV is a set of 64-bit row indexes. Delta stores it as a RoaringBitmapArray: an array of 32-bit Roaring bitmaps, one per value of the high 32 bits. A file with fewer than 2³² rows uses exactly one. Two serializations exist, each starting with a 4-byte little-endian magic number:[src][PROTOCOL]

FormatMagicHeaderPer bitmap
Portable (the spec’s format)1681511377bitmap count as 8 bytes4-byte key, then the Roaring bytes
Native (older, Delta-specific)1681511376bitmap count as 4 bytes4-byte size, then the Roaring bytes

readFrom accepts both. The DML path writes Portable.[src][src]

Inside, a 32-bit Roaring bitmap splits values again, by their high 16 bits, into containers of up to 65,536 values. There are three kinds:[RoaringFormatSpec]

  • array: sorted 16-bit values, 2 bytes each, for up to 4,096 values,
  • bitmap: 65,536 bits, always 8 KiB,
  • run: (start, length − 1) pairs, 4 bytes per run plus 2.

The 4,096 cutoff is where an array (2 × 4,096 = 8 KiB) gets as big as a bitmap. Before serializing, Delta’s bitmap aggregator calls runOptimize, which switches a container to runs when that is smaller.[src] Deleting rows 0 to 9,999 is one run container of 6 bytes. Deleting every other row up to 20,000 is a bitmap, because 10,001 runs would take about 40 KB.

The serialized 32-bit bitmap starts with a cookie. 12346 means no run containers, and is followed by the container count. Otherwise the low 16 bits are 12347, the high 16 bits are count − 1, and a bitset marks which containers are runs. Next comes a (key, cardinality − 1) pair per container. An offset per container follows, except when there are runs and fewer than 4 containers. Then come the containers themselves. Everything is little-endian.

DV files

On-disk DVs live in files that can hold many DVs. Byte 0 is the format version, 1. Then, for each DV, a 4-byte size, the bitmap, and a CRC-32 of the bitmap. These three fields are big-endian, unlike the bitmap inside.[PROTOCOL] In the Spark connector, offset points at the DV’s size field, not at the bitmap. The first DV in a file is at offset 1. The reader seeks there, checks that the size field equals sizeInBytes, reads the bitmap, and checks the CRC.[src][src]

Quiz Descriptor and bytesAnswers are scheduled for spaced review on the Review page.

Q1. What does storageType = 'i' mean?

How sure are you?

Q2. storageType = 'u', pathOrInlineDv = "ab^-aqEH.-t@S}K{vb[*k^". Where is the DV file?

How sure are you?

Q3. A DELETE removes rows 0 to 9,999 of a file. Which Roaring container holds them after runOptimize?

How sure are you?

Q4. Which byte order and magic number does a Portable RoaringBitmapArray use?

How sure are you?

Q5. In the Spark connector, the first DV in a new DV file has offset = 1. What is at byte 1?

How sure are you?

Try it

Delete rows from a 32-row file and watch every layer update: containers, Portable bytes, the inline descriptor, the on-disk descriptor and the reader’s output. The scale table shows which container type larger deletes produce. The engine (src/sim/delta/dv.ts) serializes byte for byte and is tested against the spec’s examples.

part-0.parquet: 32 rows

Click a row to delete it. Nothing in the data file changes; the DV records the row index.

What a reader returns

26 of 32 rows. With row tracking, each visible row's id is baseRowId (1000) + its index:

10001001100210051006100810091010101210131014101510161017101910201021102210231024102510261027102810301031

Containers at scale

key (high 16 bits)typevaluesbytes
0run10,0006

Arrays hold up to 4,096 values (2 bytes each), bitmaps are always 8 KiB, and runs cost 4 bytes per run. The writer calls runOptimize before serializing. BitmapAggregator ↗

Roaring containers

  • bitmap key 0, container 0: array, 6 values, 12 bytes

Serialized (Portable, little-endian): 44 bytes

d1d33964 01000000 00000000 00000000 3a300000 01000000 00000500 10000000 03000400 07000b00 12001d00

Magic 1681511377, the bitmap count as 8 bytes, then per bitmap its 4-byte key and the standard Roaring bytes. Portable format ↗

Inline descriptor

{
  "storageType": "i",
  "pathOrInlineDv": "^Bg9^0rr910000000000iXQKl0rr91000f55c8Xg0@@D72lkbi5=-{L",
  "sizeInBytes": 44,
  "cardinality": 6
}

uniqueId: i^Bg9^0rr910000000000iXQKl0rr91000f55c8Xg0@@D72lkbi5=-{L

On-disk descriptor (what Spark DML writes)

{
  "storageType": "u",
  "pathOrInlineDv": "ab^-aqEH.-t@S}K{vb[*k^",
  "offset": 1,
  "sizeInBytes": 44,
  "cardinality": 6
}

Resolves to s3://bucket/table/ab/deletion_vector_d2c639aa-8816-431a-aaf6-d3fe2512ff61.bin. Offset 1 is just past the file's version byte, where this DV's 4-byte size field starts. Writer.write ↗

Writing and reading DVs

DELETE, UPDATE and MERGE. With DVs enabled, the command first finds matching rows per file. It scans the candidate files with a row-index column and aggregates the matching indexes per file into a bitmap, using BitmapAggregator.[src] For each touched file:[src][src]

  1. If every row matched, it commits a plain remove; no DV is needed.
  2. If the file already had a DV, it loads that DV, merges the new bitmap into it, and stores the union. DVs only grow.
  3. The bitmap goes to a new on-disk DV file (storageType = 'u', with a random prefix). The DML path does not write inline DVs.[src]
  4. removeRows produces the remove (old DV) and add (new DV) pair for the same path, with wide-bound stats.

UPDATE and MERGE also write the new versions of changed rows to new data files. Only the old copies are marked deleted.

Scans. The planner rule PreprocessTableWithDVs adds a hidden __delta_internal_is_row_deleted column to every scan of a table with DVs, and a filter that keeps only rows where it is 0.[src] DeltaParquetFileFormat fills that column per row. It loads the file’s DV and, for each physical row index, marks the row deleted if the index is in the bitmap (DropMarkedRowsFilter).[src] The indexes must be physical positions in the whole file. When the scan uses Parquet’s own row-index metadata column, files can still be split. Otherwise isSplitable returns false, so the reader can count rows from the start of the file.[src]

Quiz Writing and readingAnswers are scheduled for spaced review on the Review page.

Q1. An UPDATE matches rows 5 and 9 in a file whose DV already holds 1 and 2. What DV does the new add carry?

How sure are you?

Q2. A DELETE matches every row of a file. What is committed for it?

How sure are you?

Row tracking

Row tracking gives every row an id that survives updates and compaction, and a version that says when the row last changed. It is a writer feature that requires domainMetadata. It has three states:[PROTOCOL]

  • Supported: rowTracking is in writerFeatures. Writers must assign ids and versions to new rows, but readers can’t rely on every row having one yet.
  • Enabled: also delta.enableRowTracking = true. Every row has an id and a version, and writers must preserve them.
  • Suspended: delta.rowTrackingSuspended = true. Writers stop assigning. This must not be combined with enabled, and DROP FEATURE uses it (chapter 12).

Row IDs

Every row has two ids. The fresh id identifies a row within one version and may change whenever its file is rewritten. The stable id survives updates, copies and RESTORE.[PROTOCOL]

  • Default generated ids cost almost nothing. Each add carries a baseRowId, and a row’s id is baseRowId plus its physical index in the file. This is the same index a DV uses. These ids are the fresh ones.
  • Materialized ids are stored in a hidden column named by delta.rowTracking.materializedRowIdColumnName. When a writer copies or updates a row, it writes the old stable id into this column. A null means “use the default”.

So a reader computes the stable id as coalesce(materialized, baseRowId + index).[PROTOCOL] When OPTIMIZE compacts a file, the new file gets a new baseRowId, so every row gets a new fresh id. Each row’s old id is written to the materialized column so its stable id stays the same.

To keep ids unique, writers track a high-water mark: the highest fresh id ever assigned. It is stored as {"domainMetadata": {"domain": "delta.rowTracking", "configuration": "{\"rowIdHighWaterMark\":149}", ...}}. A new file’s baseRowId must be above the mark.[PROTOCOL] The Spark connector’s assignFreshRowIds does exactly that. It gives each add without a baseRowId the value mark + 1, advances the mark by the file’s numPhysicalRecords, and appends one domainMetadata with the new mark. If stats are missing, it fails, because it can’t know how many ids to reserve.[src] On a table without a mark, the first baseRowId is 0.

Row commit versions

These work the same way. defaultRowCommitVersion on the add is the version that committed it. The fresh version of a row is that value, and the stable version comes from a materialized column when one is present.[PROTOCOL] A row that is copied unchanged keeps its stable commit version. A row that is updated gets the new version. Change-data consumers use this pair: two rows with the same stable id and the same stable version are the same version of the row.

Concurrent writers

Both values depend on the version and the mark a transaction read, so they are exactly what a lost race invalidates. The conflict checker fixes them instead of failing the transaction:[src]

Two inserts with row tracking
Writer T1INSERT 50 rows_delta_log/reads v4, HWM 149Writer T2INSERT 30 rows1. read v4: rowIdHighWaterMark = 1492. assignFreshRowIds: baseRowId 150, HWM 1993. assignFreshRowIds: baseRowId 150, HWM 1794. PUT 5.json ✓5. PUT 5.json ✗ (exists)6. reassignOverlappingRowIds: 150 → 2007. reassignRowCommitVersions: 5 → 68. PUT 6.json ✓
  1. read v4: rowIdHighWaterMark = 149. The mark lives in a domainMetadata action with domain delta.rowTracking. Both writers read the same snapshot.
  2. assignFreshRowIds: baseRowId 150, HWM 199. Each add without a baseRowId gets mark + 1, and the mark moves by the file's numRecords. A new domainMetadata with the new mark is appended. defaultRowCommitVersion is set to the version being committed, 5. RowId.assignFreshRowIds ↗
  3. assignFreshRowIds: baseRowId 150, HWM 179. T2 read the same mark, so its ids overlap T1's: rows 150 to 179 would exist twice. RowId.assignFreshRowIds ↗
  4. PUT 5.json ✓. T1 wins version 5.
  5. PUT 5.json ✗ (exists). T2 loses the race and runs the conflict checker against commit 5.
  6. reassignOverlappingRowIds: 150 → 200. Only ids this transaction assigned are moved, meaning baseRowId above the mark it read (149) or missing. They are renumbered from the winner's mark (199), so the new mark is 229. Files it merely copied keep their old ids. ConflictChecker ↗
  7. reassignRowCommitVersions: 5 → 6. Any defaultRowCommitVersion equal to the winner's version (or missing, if the winner just turned row tracking on) becomes winner + 1. ConflictChecker ↗
  8. PUT 6.json ✓. Inserts never conflict on data, so the retry commits with ids 200 to 229 and row commit version 6.
Numbers come from the simulator's tests. Follows RowId.assignFreshRowIds and ConflictChecker.reassignOverlappingRowIds / reassignRowCommitVersions at 25561a5.

The detail that matters is which ids move. Only adds with a baseRowId above the mark this transaction read, or with none, are renumbered. A file that UPDATE copied from an earlier version keeps its id, because that id already belongs to rows in the table.

Quiz Row trackingAnswers are scheduled for spaced review on the Review page.

Q1. rowTracking is in writerFeatures, but delta.enableRowTracking is not set. Which is true?

How sure are you?

Q2. OPTIMIZE rewrites a file with baseRowId = 100 into a new file with baseRowId = 500. What happens to the row that was at index 3?

How sure are you?

Q3. The high-water mark is 149. A commit adds files of 50 and 30 rows. What does the Spark connector assign?

How sure are you?

Q4. T2 read mark 149 and assigned baseRowId 150. T1 committed first with mark 199. T2 also copied a file whose baseRowId is 20. After conflict resolution?

How sure are you?

Q5. A row is copied unchanged by an UPDATE in version 8. It was inserted in version 3. What are its row commit versions?

How sure are you?

History

Roaring bitmaps come from Samy Chambi, Daniel Lemire, Owen Kaser and Robert Godin, “Better bitmap performance with Roaring bitmaps”, Software: Practice and Experience, 2016.[doi] The cross-language serialization Delta relies on is defined in the RoaringFormatSpec repository.

Summary

  • A DV marks deleted rows of one data file by physical index. Writes become cheap and reads filter rows. Readers must apply DVs even when delta.enableDeletionVectors is off.
  • Adding rows to an existing DV commits a remove and an add for the same path, so logical files are keyed by (path, dvId).
  • Descriptors are inline (i), UUID-relative (u) or absolute (p). uniqueId and the file path are derived from the descriptor.
  • The bitmap is a RoaringBitmapArray (Portable: magic 1681511377, little-endian) made of array, bitmap and run containers. DV files wrap each bitmap in a big-endian size and CRC-32.
  • Row ids are baseRowId + index unless a materialized value exists. A high-water mark in domainMetadata keeps them unique, and the conflict checker renumbers a losing writer’s new ids and bumps its commit versions.

Concepts in this chapter

Explained here

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