≈ The Lake

Part 4 · Delta Lake protocol · Chapter 15

Change data feed, column mapping and type widening

Three features that change what readers must do: cdc files and the change type column, column mapping by name or id, and type widening metadata. Each one separates what the log says from what the Parquet files hold.

complete ~45 min

After this chapter you should be able to:
  • Read a change data feed for a version range and say, per version, whether cdc files or add/remove actions supply the rows.
  • Explain how UPDATE and DELETE produce change rows, and how deletion vectors change that.
  • Explain physical names and field ids under column mapping, and why rename and drop need them.
  • List the allowed type widenings, the Iceberg-compatible subset, and what readers must do with older files.

The previous chapters treated a data file as a bag of rows the log points at. This chapter covers three features that break that simplicity in different ways. The change data feed (CDF) adds files that aren’t table data at all, only a record of what changed. Column mapping makes the column names in Parquet files differ from the names in the schema. Type widening lets the files of one table disagree about a column’s type. In all three, a reader that ignores the feature returns wrong answers, which is why two of them are reader features.

All links are pinned to delta-io/delta commit 25561a5.

Change data feed

A change data feed answers “which rows changed between versions 5 and 9, and how?” Each change row carries the row’s columns plus _change_type, which is one of insert, update_preimage, update_postimage and delete. The reader adds _commit_version and _commit_timestamp.[PROTOCOL] In Spark you ask for it with .option("readChangeFeed", "true") plus a starting version or timestamp, or with the SQL function table_changes.[src]

changeDataFeed is a writer feature (writer version 4, or 7 with the feature listed). Writers must respect delta.enableChangeDataFeed. When it is true, they must produce change data for any operation that changes data.[PROTOCOL] Readers need no new capability, because a non-CDF reader never looks at change files.

Where change rows come from

The log already describes a lot of change. An add means its rows were inserted, and a remove means its rows were deleted. That covers INSERT and a DELETE that drops whole files. It breaks down when a file is rewritten. An UPDATE that changes one row of a 1,000-row file removes the file and adds a new one with 999 copied rows and one changed row. From the actions alone, that looks like 1,000 deletes and 1,000 inserts.

So writers may record the true changes in change data files, under _change_data/ at the table root, each committed with a cdc action. A cdc action has dataChange = false, because it adds nothing to the table. The spec makes the files optional: an operation that only adds or only removes data “can write only data files and commit them in add or remove actions without duplicating the data into change data files.”[PROTOCOL]

The reader rule is per version:[PROTOCOL]

  1. If the version has cdc actions, read only those, and skip its add and remove actions.
  2. Otherwise, read the rows of add actions as inserts and the rows of remove actions as deletes.

Spark’s CDCReader.changesToDF does exactly this. It also checks that CDF was enabled at the start version and was never disabled within the range, and fails with “change data not recorded” otherwise. When it infers changes from add and remove, it takes only actions with dataChange = true, so OPTIMIZE contributes nothing.[src][src]

How Spark writes change rows

Spark doesn’t run a second job to write change files. The command emits one stream of rows, each with a _change_type column that is null for table data and set for change data. TransactionalWrite.performCDCPartition adds a virtual partition column, __is_cdc = _change_type IS NOT NULL, ahead of the real partition columns. DelayedCommitProtocol then rewrites the paths: __is_cdc=false rows go to the normal location, and __is_cdc=true rows go under _change_data/, in files named cdc-…. Those become cdc actions.[src][src][src]

The commands decide the _change_type:

  • UPDATE: withUpdatedColumns packs each matched row into an array of three structs (preimage, postimage, and the new data row with a null change type) and explodes it. Unmatched rows that are copied get one row with a null type.[src]
  • DELETE: rewriteFiles normally filters out deleted rows. With CDF on, it keeps every row and sets _change_type to delete for matches and null for survivors, so the deleted rows end up in a change file.[src]
  • A DELETE whose condition uses only partition columns removes whole files and writes nothing. Readers infer the deletes from the remove actions.
UPDATE with CDF, then reading the feed
UpdateCommandUPDATE … SET v = 'B' WHERE id = 2TransactionalWrite+ DelayedCommitProtocoltable dirdata + _change_data/_delta_log/CDF readertable_changes(t, 5, 6)1. explode each match → 3 rows2. writeFiles(rows + _change_type)3. __is_cdc=false → part-00004.parquet4. __is_cdc=true → _change_data/cdc-00005.parquet5. v5: remove part-00001, add part-00004, cdc …6. read v5 actions7. v5 has cdc → read only cdc-000058. v6 (DELETE with DV): no cdc9. diff DVs → row 0 is a delete
  1. explode each match → 3 rows. withUpdatedColumns turns each matched row into [preimage, postimage, new data row]. The first two carry _change_type; the data row and every copied row carry null. UpdateCommand.withUpdatedColumns ↗
  2. writeFiles(rows + _change_type). performCDCPartition adds a virtual partition column __is_cdc = _change_type IS NOT NULL, placed first so it splits every write in two. performCDCPartition ↗
  3. __is_cdc=false → part-00004.parquet. The data rows go to the normal location. The virtual partition directory is stripped from the path. DelayedCommitProtocol ↗
  4. __is_cdc=true → _change_data/cdc-00005.parquet. The preimage and postimage rows go under _change_data/, in a file named cdc-… rather than part-…. DelayedCommitProtocol ↗
  5. v5: remove part-00001, add part-00004, cdc …. The cdc action has dataChange = false: it adds no table data. Normal readers never look at it. Add CDC File ↗
  6. read v5 actions. The reader walks versions in order. For each, it first checks whether there are any cdc actions. CDCReader.changesToDF ↗
  7. v5 has cdc → read only cdc-00005. With cdc actions present, the add and remove in v5 are skipped. Otherwise the copied rows 1 and 3 would show up as deleted and re-inserted. Reader Requirements ↗
  8. v6 (DELETE with DV): no cdc. A DV delete commits remove(dv=[]) and add(dv=[0]) for the same path, and no cdc file.
  9. diff DVs → row 0 is a delete. Rows in the new DV but not the old are deletes. Rows in the old but not the new (RESTORE) are inserts. generateFileActionsWithInlineDv ↗
Follows UpdateCommand, TransactionalWrite, DelayedCommitProtocol and CDCReader at 25561a5.

Deletion vectors and CDF

A DELETE with deletion vectors writes no data and no change file. It commits a remove and an add for the same path, with the old and new DV (chapter 13). Reading those as “all rows deleted, then all rows inserted” would be wrong, so getDeletedAndAddedRows pairs up a path that is both removed and added in one version. generateFileActionsWithInlineDv then diffs the two DVs: rows in the new DV but not the old one are deletes, and rows in the old one but not the new are inserts (which happens on RESTORE). The diffs become inline DVs over the same file, so the reader scans only the changed rows.[src][src]

An UPDATE with DVs is different. It marks the old rows with a DV and writes the new rows through withUpdatedColumns, so the version has a change file. Rule 1 applies, and the DV diff is never consulted.

Quiz Change data feedAnswers are scheduled for spaced review on the Review page.

Q1. Version 7 has a remove, an add and a cdc action. How does a change data reader get version 7's changes?

How sure are you?

Q2. An UPDATE changes 1 row in a 1,000-row file by rewriting it. Without a change file, what would add/remove inference report?

How sure are you?

Q3. Why does an append on a CDF table usually write no change file?

How sure are you?

Q4. With CDF on, what rows does Spark's UPDATE produce for one matched row (before routing)? (select all that apply)

How sure are you?

Q5. A DELETE with deletion vectors commits remove(path=f, dv=[2]) and add(path=f, dv=[2,5]), and no cdc file. What does the change reader return for f?

How sure are you?

Q6. What does OPTIMIZE contribute to the change feed?

How sure are you?

Q7. CDF was turned off at version 8 and back on at 10. What does Spark do for a read of versions 6 to 12?

How sure are you?

Try it

Run INSERT, UPDATE, DELETE and OPTIMIZE against a three-row table, switching between file rewrites and deletion vectors. The log shows each version’s actions. The change feed shows every row the reader returns and where it came from: a cdc file, an add or remove action, or a DV diff. Turn CDF off to see what the reader would infer without change files. The engine is src/sim/delta/cdf.ts.

_delta_log/

  1. v0
    • commitInfo WRITE
    • add part-00000.parquet

Table now

idv
1a
2b
3c

Change feed, v0 to v0

_commit_versionidv_change_typefrom
01ainsertadd
02binsertadd
03cinsertadd

changesToDF ↗ · DV diff ↗ · UPDATE ↗

A non-CDF reader has one more rule. Data files in a CDF table may contain an extra _change_type column that isn’t in the schema, and readers must ignore it.[PROTOCOL]

Column mapping

Without column mapping, a column’s name in the schema is its name in every Parquet file. Two operations then become expensive or unsafe:

  • Rename would mean rewriting every file, or the old files would no longer have a column with the new name.
  • Drop is a trap. If you drop amount from the schema and later add a new amount, the old files still hold the old amount, and readers would return the dropped data as if it belonged to the new column.

Column mapping separates the two names. Every column, nested or leaf, gets a physical name (metadata key delta.columnMapping.physicalName) and a unique 32-bit id (delta.columnMapping.id). The schema’s name becomes a display name that can change freely.[PROTOCOL]

{ "name": "d", "type": "integer", "nullable": false,
  "metadata": { "delta.columnMapping.id": 5,
                "delta.columnMapping.physicalName": "col-a7f4159c-53be-4cb0-b81a-f7e5240cfc49" } }

The mode is the table property delta.columnMapping.mode, one of none, name or id. It is honored only when the protocol supports the columnMapping feature: reader 2, or reader 3 with the feature, and writer 5 or 6, or writer 7 with the feature. So column mapping is a reader-writer feature. A reader that doesn’t understand it would look up display names in files written under physical names and find nothing.

A Delta rename changes the display name
Before rename
  1. Display name d
  2. Stored identity ID 5 · physical name col-a7f4159c-…
After rename
  1. Display name distance
  2. Stored identity ID 5 · physical name col-a7f4159c-…
The mapping remains stable across the rename, so the reader can still find the data in files written under the previous display name.[Delta protocol]

Writer rules

Writers must:[PROTOCOL]

  • write data files using physical names, and write each column’s id into the Parquet field_id of its SchemaElement;
  • record partition values, column statistics and clustering columns in the log by physical name;
  • give each new column a new physical name whose physical field path is unique across all versions of the table, and a new id. The highest id is tracked in the internal property delta.columnMapping.maxColumnId, which only increases.

That uniqueness rule is what fixes the drop trap. A column added after a drop gets a new physical name, so old files have no column by that name and readers return null.

The Spark connector generates physical names as "col-" + UUID.randomUUID() and assigns ids from maxColumnId + 1.[src][src] Turning on name mode for an existing table is the one mode change it allows (none to name). That upgrade reuses each column’s current display name as its physical name. The display names already have the properties physical names need, so no file is rewritten. Changing to id mode on an existing table is refused, and going back to none is allowed only behind an internal flag.[src][src]

Reader rules

Readers resolve each schema column in a data file by mode:[PROTOCOL]

ModeData file columns resolved byMissing column
nonedisplay name (name)—
namedelta.columnMapping.physicalNamenull
idParquet field_id = delta.columnMapping.idnull; a file with no field ids must be refused or read as all nulls

In both name and id modes, partition values and statistics are looked up by physical name. id mode suits files whose writers keep field ids stable while names change, which is how Iceberg identifies columns (chapter 21).

New table in·

Created in 'name' mode and wrote part-0.

Schema (mode name, maxColumnId 2)

display nameidphysicalName
id1col-5f43c859…
amount2col-5f456172…

assignColumnIdAndPhysicalName ↗ · mode changes ↗

Files, read with the current schema

filecolumns in the fileidamount
part-0.parquetcol-5f43c859…#1, col-5f456172…#2110
Quiz Column mappingAnswers are scheduled for spaced review on the Review page.

Q1. Without column mapping, why is DROP COLUMN amount followed by ADD COLUMN amount dangerous (if a writer allowed it)?

How sure are you?

Q2. Under column mapping, which must writers key by physical name or id? (select all that apply)

How sure are you?

Q3. What is delta.columnMapping.maxColumnId?

How sure are you?

Q4. Spark enables name mode on an existing table. What physical names do the existing columns get?

How sure are you?

Q5. In id mode, a data file has no Parquet field ids. What must the reader do?

How sure are you?

Q6. Why is column mapping a reader-writer feature rather than writer-only?

How sure are you?

Type widening

Parquet files are immutable, so a column’s type in old files is fixed. Type widening lets the schema change a column to a wider type without rewriting them. Readers then convert old values as they read. typeWidening is a reader-writer feature (reader 3, writer 7). Writers must reject widening unless delta.enableTypeWidening is true.[PROTOCOL]

The supported changes are:

  • integers: byte → short → int → long;
  • float → double, and byte, short or int → double;
  • date → timestamp_ntz;
  • decimal(p, s) → decimal(p + k1, s + k2) with k1 >= k2 >= 0;
  • byte, short or int → decimal(10 + k1, k2), and long → decimal(20 + k1, k2), with k1 >= k2 >= 0.

The decimal rule means the new type must keep at least as many digits before the point (p - s can’t shrink) and at least as many after it. decimal(6,2) → decimal(10,4) is fine, but decimal(6,2) → decimal(7,4) would lose an integer digit. The integer-to-decimal bases come from Parquet: byte, short and int are all stored as INT32, which needs decimal(10,0), and long is INT64, which needs decimal(20,0). Spark’s isTypeChangeSupported is the same list, with a Cast.canUpCast guard in front.[src] long → double is not on the list, because a double can’t hold every long exactly.

The type change history

Each change is recorded in the schema, under delta.typeChanges in the metadata of the nearest ancestor struct field. Changes to a map key or value or an array element add a fieldPath such as key, value or element.value:[PROTOCOL]

{ "name": "e", "type": "long", "nullable": true,
  "metadata": { "delta.typeChanges": [
    { "fromType": "short",   "toType": "integer" },
    { "fromType": "integer", "toType": "long" } ] } }

Writers must keep this metadata across later schema changes. They may delete it once every data file uses the current types, which is what dropping the feature does after rewriting the old files (chapter 12).[PROTOCOL] Readers must convert values from files written before a change to the current type, and must fail if the history holds a change they don’t support.[PROTOCOL] The history exists for that second rule: a reader can see from the schema alone whether the files might hold a type it can’t convert.

Two smaller sets

When IcebergCompatV1 or V2 is supported, writers must also reject changes Iceberg V2 can’t express: integer → double, date → timestamp_ntz, any decimal scale increase, and integer → decimal. The table’s Iceberg metadata must stay valid (chapter 21).[src]

Spark also applies only a subset automatically during schema evolution in INSERT and MERGE: integer widening, float → double, decimal → wider decimal, and date → timestamp_ntz. Changes such as int → double need an explicit ALTER TABLE … ALTER COLUMN … TYPE.[src]

  • ✓ Allowed by the spec (ALTER COLUMN … TYPE) src ↗
  • ✓ Applied automatically by schema evolution src ↗
  • ✓ Allowed with IcebergCompatV1/V2 src ↗
"delta.typeChanges": [{"fromType": "integer", "toType": "long"}]
Quiz Type wideningAnswers are scheduled for spaced review on the Review page.

Q1. Which type changes does the spec allow? (select all that apply)

How sure are you?

Q2. A column is decimal(6,2). Which new types are allowed? (select all that apply)

How sure are you?

Q3. Why is int → decimal(9,0) rejected but int → decimal(10,0) allowed?

How sure are you?

Q4. Where is the record of a column's type changes stored?

How sure are you?

Q5. What must a reader of a typeWidening table do? (select all that apply)

How sure are you?

Q6. IcebergCompatV2 is supported. Which type changes must a writer reject? (select all that apply)

How sure are you?

How the three interact

  • CDF and schema changes. A change feed spans versions, and the schema can change within the range. changesToDF checks every metaData in the range against the schema it reads with, and fails on a read-incompatible change rather than returning rows under the wrong columns.[src] Renames and drops under column mapping are the usual way to hit this.
  • Column mapping and change files. Change files are Parquet files written by the same write path, so they use physical names too.
  • Type widening and old files. Every file written before a change, data or change file, holds the old type. The reader’s upcast applies to all of them.

Summary

  • CDF: writers with delta.enableChangeDataFeed write change rows to _change_data/ as cdc actions. Readers use only cdc files in a version that has them, and otherwise read adds as inserts and removes as deletes.
  • Spark routes rows by a virtual __is_cdc partition. UPDATE emits preimage, postimage and data rows. DELETE keeps deleted rows as delete, and DV deletes are read by diffing the old and new DV of one path.
  • Column mapping gives every column a physical name and an id. Files use physical names and field_id, the log uses physical names, and new columns never reuse a physical field path. Readers resolve by display name, physical name or field id depending on the mode.
  • Type widening allows only lossless promotions. Each one is recorded in delta.typeChanges, readers upcast old values and reject unknown changes, and IcebergCompat narrows the list.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 19 quiz questions.

Review this chapter's cards → Review all due cards