You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "suhuruli (via GitHub)" <gi...@apache.org> on 2026/07/09 02:31:59 UTC
[PR] initial autocdc type1 docs [spark]
suhuruli opened a new pull request, #57149:
URL: https://github.com/apache/spark/pull/57149
---
What changes were proposed in this pull request?
This PR documents Auto CDC (Change Data Capture) support for Spark Declarative Pipelines (SDP) in the programming guide.
It adds a new section, "Change Data Capture (CDC) with Auto CDC," to docs/declarative-pipelines-programming-guide.md, placed after the SQL programming section and before "Writing Data to External Targets with Sinks." The section covers:
- Concept - what Auto CDC does, its SCD Type 1 semantics (keep only the current version of each row), and how it handles inserts, updates, deletes, and out-of-order/duplicate events, with a worked before/after example.
- Requirements - the target must be a pre-created streaming table, the source must be a streaming source, and keys plus a sequencing expression are required.
- Python API reference - the create_auto_cdc_flow function with a full parameter table.
- SQL reference - both supported syntax forms (CREATE FLOW ... AS AUTO CDC INTO and CREATE STREAMING TABLE ... FLOW AUTO CDC), including required clause ordering.
- End-to-end quickstart - a spark-pipelines init -> run walkthrough.
- How-tos - handling deletes, selecting columns, out-of-order events, composite keys, and changing the key set (full refresh).
- Limitations/considerations - SCD Type 1 only, streaming-table target only, immutable key set, and table-format requirements.
No functional code is changed; this is documentation only. The content is grounded in the existing implementation: create_auto_cdc_flow in python/pyspark/pipelines/api.py, the autoCdcCommand grammar in sql/api/.../SqlBaseParser.g4, and the AutoCdcFlowDetails / SCDType definitions in sql/connect/common/src/main/protobuf/spark/connect/pipelines.proto.
Why are the changes needed?
Auto CDC was added to SDP but was undocumented in the programming guide, leaving users with no reference for how to apply change data capture to a target table. A new user landing on the SDP docs had no way to discover the feature, its Python or SQL syntax, or its semantics and limitations. This PR closes that gap so users can adopt Auto CDC from the official documentation.
Does this PR introduce any user-facing change?
Yes, but documentation only. It adds a new section to the Spark Declarative Pipelines programming guide. There is no change to behavior, APIs, or output.
How was this patch tested?
No tests were added; this is a documentation-only change. The Markdown was verified locally to ensure it is ASCII-only (per the repository convention) and that the internal anchor link (#spark-pipelines-run) resolves to an existing heading. All code snippets and API parameters were cross-checked against the current implementation (create_auto_cdc_flow, the autoCdcCommand SQL grammar, and the pipelines.proto definitions).
Was this patch authored or co-authored using generative AI tooling?
Yes
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho closed pull request #57149: [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1)
URL: https://github.com/apache/spark/pull/57149
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on PR #57149:
URL: https://github.com/apache/spark/pull/57149#issuecomment-5187670413
Narrowing this PR to **SCD Type 1 only** to keep it reviewable. The SCD Type 2 material - the `__START_AT` / `__END_AT` validity interval, `TRACK HISTORY ON`, and the Type 2 walkthrough - is removed here and will come as a follow-up under [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). The diff drops from 536 to 356 added lines.
Everything from your review stands: keys and sequence values are still defined before use, the sequencing constraints are still documented, the examples still carry a genuine out-of-order event, and the two-run end-to-end walkthrough is unchanged.
One deliberate choice worth flagging. I did not restore the old "SCD Type 1 is the only mode currently supported" wording, because that is no longer true on master - Type 2 landed in SPARK-58247 / SPARK-58261 / SPARK-58321. Instead, the two places where a reader would otherwise be misled - the `stored_as_scd_type` parameter and the `STORED AS SCD TYPE` clause, both of which accept `2` - say Type 2 is accepted and link SPARK-58570. Narrower scope for this PR, without the guide making a false claim in the meantime.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] initial autocdc type1 docs [spark]
Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3626462546
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
Review Comment:
what's a sequence value? Do you want to introduce that first? (a set of columns defining the event order)
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
Review Comment:
this has no out-of order events for any of the keys, would it make sense?
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
Review Comment:
_v2 is a bit weird for a name. Would "alicia" be a more natural update?
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
Review Comment:
can the sequence really be an arbitrary expression?
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
Review Comment:
target table?
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target.
Review Comment:
Maybe add: This is not recommended, because it would include the operation column in the target.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
Review Comment:
for example, `"id"` or `col("id")`, but not `"source.id"`
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers. They cannot be qualified references such as `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The clauses must appear in this order:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`. Both forms target SCD Type 1; there is no SQL clause to select the SCD type.
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests a stream of customer change events and maintains a `customers` table containing the latest state of each customer. It uses Delta as the table format, but Auto CDC works with any format that supports the required row-level operations.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Add a transformation that defines the CDC source, the target streaming table, and the Auto CDC flow. Place the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+
+# Ingest the raw change events as a streaming table. In a real pipeline this
+# would read from Kafka, cloud storage, or a CDC feed; here it reads a Delta
+# table that another process appends change events to.
+@dp.table(name="cdc_events", format="delta")
+def cdc_events():
+ return spark.readStream.format("delta").load("/path/to/cdc_source")
+
+# Declare the target streaming table that Auto CDC will maintain.
+dp.create_streaming_table("customers", format="delta")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Suppose the source receives two batches of change events. The first batch inserts two customers:
+
+| id | name | version | op |
Review Comment:
again, no out-of-order events. What about an example that has an out-of order late update (or delete) in batch 2? And you run the pipeline after each batch? Then it wold demonstrate that the late event had no effect.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1 and Type 2) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3715807567
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
Review Comment:
Good catch - it was used before being defined. Added a "Keys and sequencing" subsection ahead of "What Auto CDC does" that introduces keys and defines a sequence value as the value of the sequencing expression for an event, with examples of what feeds usually carry (version/commit number, commit timestamp).
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
Review Comment:
Yes - reworded to say the target keeps only the current version of each row. The two SCD modes are now introduced together here, since Type 2 is supported as of SPARK-58247/58261/58321 and the old "Type 1 is the only mode" text was stale.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
Review Comment:
Agreed, the example did not exercise what the text above it claimed. Added a stale re-delivered event for id 1 (version 1, arriving after version 2) and called out explicitly that the events are not in version order. There is now a per-key walkthrough showing the late event being discarded and the row keeping `alicia`.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
Review Comment:
Agreed, changed to `alicia` throughout (concept example, end-to-end example, and the SCD2 sections).
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
Review Comment:
Yes, it can be an arbitrary SQL expression over the source columns, not just a column reference. But your question exposed that the real constraints were undocumented, so I added them: the result type must be orderable (`AUTOCDC_SEQUENCING_COLUMN_NOT_ORDERABLE`), values must be non-null, and the result type must not change across incremental runs (`SEQUENCING_TYPE_DRIFT`, needs a full refresh). Also noted that ties are broken arbitrarily, so a per-event-unique expression is preferable.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
Review Comment:
Adopted your wording in both places it appears (the `keys` row of the parameter table and the paragraph below it).
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target.
Review Comment:
Added: the text now says leaving both column lists unset is usually not what you want for a CDC feed, since the operation column and other change-feed bookkeeping would land in the target, and points at the `except_column_list=["op"]` the examples use.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1 and Type 2) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3715808679
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+
+Auto CDC, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|----------|---------|
+| 1 | alice_v2 | 2 |
+| 3 | carol | 1 |
+
+Row 1 is updated to its latest version, row 2 is deleted, and row 3 is inserted.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide a **key** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table.
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers (for example `["id"]`, not `col("source.id")`). |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers. They cannot be qualified references such as `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The clauses must appear in this order:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`. Both forms target SCD Type 1; there is no SQL clause to select the SCD type.
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests a stream of customer change events and maintains a `customers` table containing the latest state of each customer. It uses Delta as the table format, but Auto CDC works with any format that supports the required row-level operations.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Add a transformation that defines the CDC source, the target streaming table, and the Auto CDC flow. Place the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+
+# Ingest the raw change events as a streaming table. In a real pipeline this
+# would read from Kafka, cloud storage, or a CDC feed; here it reads a Delta
+# table that another process appends change events to.
+@dp.table(name="cdc_events", format="delta")
+def cdc_events():
+ return spark.readStream.format("delta").load("/path/to/cdc_source")
+
+# Declare the target streaming table that Auto CDC will maintain.
+dp.create_streaming_table("customers", format="delta")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Suppose the source receives two batches of change events. The first batch inserts two customers:
+
+| id | name | version | op |
Review Comment:
Restructured the end-to-end example along these lines: it now writes batch1, runs, shows the target, then appends batch2 and runs again. Batch 2 ends with a late duplicate of the original id-1 event, and the text points out that the row keeps `alicia` because version 1 is below the recorded version 2 - and that arrival-order processing would have wrongly reverted it. I used a directory of JSON files as the source so the two-batch flow is something a reader can actually reproduce by appending a file.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3768812448
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
Review Comment:
Good catch @szehon-ho, and apologies @anew - a readability pass trimmed the out-of-order event out of the concept example, which is exactly what you had asked to see here. I have restored it, following the edits above:
1. Re-added the trailing `| 1 | alice | 1 | UPSERT |` row.
2. Restored the lead-in noting the events are not in `version` order (the last `id 1` event is a stale re-delivery of version 1 arriving after version 2).
3. Added the discard clause to the by-key walkthrough: the stale version 1 event is discarded because a higher sequence value has already been applied.
The target table is unchanged, as you noted - the highest sequence value per key still wins. I also replayed this exact six-event batch through the merge engine to confirm (`id 1 -> alicia@2`, `id 2` gone, `id 3 -> carol@1`). Pushed in the latest revision.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3752646276
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+- **Target must be a streaming table** - You cannot apply an Auto CDC flow to a materialized view or an external table.
Review Comment:
Prefer avoid second person
- line 865: "You cannot apply an Auto CDC flow to a materialized view or an external table" -> "An Auto CDC flow cannot target a materialized view or an external table"
- line 870: "Your source cannot contain a column with that name" -> "The source cannot contain a column with that name"
- line 871: "If you declare a schema on the target streaming table, it must currently include..." -> "A schema declared on the target streaming table must currently include..."
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3761873939
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,273 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### What Auto CDC does
+
+Given an ordered stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order events** - Events don't have to arrive in order. Auto CDC uses the sequencing expression to determine the latest state per key, so a late-arriving event with a lower sequence value doesn't overwrite newer data.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, given these change events (ordered by `version`):
+
+| id | name | version | op |
+|----|----------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alice_v2 | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
Review Comment:
@anew heads up: the out-of-order event that was added for this thread is no longer in the concept example. The latest force-push (e9f1e5f) trimmed that table back to five in-order events and collapsed the by-key walkthrough, so the first example no longer shows an out-of-order arrival. Line 562 now forwards to the end-to-end example instead, which does still demonstrate it -- batch 2 carries `id 1`'s two events newest-first, and batch 3 re-delivers the stale one in a later run.
Nothing is inaccurate as written, so this is a call on where the behavior is best shown rather than a correctness issue.
If it should be shown here again, it is a cheap change: a stale re-delivery cannot alter a Type 1 result, since the highest sequence value per key still wins, so the target table below stays exactly as printed -- and this is the same example that was already replayed through the merge engine in the earlier revision. Three edits:
1. Re-add the trailing row to the change-events table:
`| 1 | alice | 1 | UPSERT |`
2. Restore the lead-in on line 545: "For example, take these change events. They are **not** in `version` order - the last event for `id 1` is a stale re-delivery of version 1, arriving after version 2:"
3. Add the discard clause to line 562: "...then updated to `alicia` at version 2, and the stale version 1 event arriving last is discarded because a higher sequence value has already been applied; ..."
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1 and Type 2) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on PR #57149:
URL: https://github.com/apache/spark/pull/57149#issuecomment-5184046721
Thanks for the review - all eight comments are addressed, replies inline on each thread.
One thing worth surfacing beyond the individual comments. Your point about the examples not exercising out-of-order events prompted me to actually run the quickstart instead of only re-reading it, and it did not work: `create_streaming_table("customers")` produces a Parquet target, and the flow fails at startup with
```
[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
operations.
```
Auto CDC requires a target whose connector implements the DSv2 `SupportsRowLevelOperations` interface (`DatasetManager.requireAutoCdcTargetSupportsRowLevelOps`), and no format built into Spark does. I also checked Delta, since the earlier revision claimed it worked: `DeltaTableV2` does not implement that interface either, routing MERGE through its own planner extension instead. So that claim was simply wrong and is now gone.
The guide has a new "Choosing a target format" subsection covering this, and the examples use a placeholder `lakehouse` catalog. **If there is a connector you would rather name outright, please say so** - I did not want to name one whose DSv2 row-level-operation support I could not verify.
A related snag: a second `spark-pipelines run` in the same project fails with `LOCATION_ALREADY_EXISTS`, because the warehouse directory persists while the default in-memory metastore does not. Since the two-run example depends on incremental behavior, that is noted too.
Other changes from your comments: keys and sequence values are now defined before use, with the real sequencing constraints (orderable type, non-null, type stable across runs); the concept and end-to-end examples both carry a genuine out-of-order event and walk through why it is discarded; `alice_v2` is now `alicia`; and leaving the column lists unset now carries the warning that the operation column would land in the target.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on PR #57149:
URL: https://github.com/apache/spark/pull/57149#issuecomment-5271280742
**Merge Summary:**
- merged into master https://github.com/apache/spark/commit/e1f3e22f4274cfbc13168763e4a71e3673c0a8c5
- merged into branch-4.x https://github.com/apache/spark/commit/0a53e3af216531386977d071a3e649c7ac8e13c7
- merged into branch-4.3 https://github.com/apache/spark/commit/256e58d06a7074785e18f5a5cb953fba17e848b1
*Posted by `merge_spark_pr.py`*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3755740384
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
Review Comment:
Prefer avoiding second person, as elsewhere in this section:
- 522: "You have to match events to existing rows, apply them in the right order, and handle..." -> "Matching events to existing rows, applying them in the right order, and handling out-of-order and duplicate events without corrupting the table is the hard part."
- 540: "a delete condition you supply" -> "a delete condition"
- 541: "you don't need to de-duplicate the source" -> "the source does not need to be de-duplicated"
- 631: "If you specify neither ... usually not what you want for a CDC feed" -> "If neither is specified ... usually wrong for a CDC feed"
- 637: "a streaming table you have already declared" -> "an already-declared streaming table"
- 685: "consult your connector's documentation" -> "consult the connector's documentation"
- 687: "Add your catalog ... substituting your own catalog name and connector class" -> "Add the catalog ... substituting the catalog name and connector class"
- 700: "substitute your own row-level-operation-capable catalog" -> "substitute a row-level-operation-capable catalog"
- 709: "add your catalog" -> "add the catalog"
- 830: "If you don't supply a delete condition" -> "If no delete condition is supplied"
- 834: "metadata columns ... that you don't want in the target table" -> "metadata columns ... that do not belong in the target table"
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
Review Comment:
Within a microbatch this is accurate -- `Scd1BatchProcessor.deduplicateMicrobatch`: "When multiple events share the same key and the same sequence value, the row selected is non-deterministic and undefined."
Across runs the behavior is defined rather than arbitrary. In the merge conditions, `incomingWinsUpsert` uses `>=`, so an equal-sequence upsert overwrites the committed row, while `incomingWinsDelete` uses `>`, so a delete needs a strictly greater sequence ("an arbitrary but deliberate choice to maintain that upserts get priority over deletes on duplicate sequencing").
Suggest scoping the sentence to ties within a microbatch; the recommendation to pick a per-event-unique expression stands either way.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
Review Comment:
"first" reintroduces the ordering implication that Requirements now explicitly rules out on line 571: "Order within the source file does not matter; the graph is resolved after all definitions are registered." Line 620 reads the same way ("It must already be defined in the pipeline"). Dropping "first" and "already" keeps the three statements consistent.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` produces - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+Auto CDC needs a table provider that implements row-level operations, configured as a catalog in the pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; consult your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface Auto CDC requires. The catalog must also persist metadata across runs, per [Requirements](#requirements).
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Add your catalog to the generated `spark-pipeline.yml` - substituting your own catalog name and connector class - without disturbing the `name`, `storage`, and `libraries` values `spark-pipelines init` already wrote:
+
+```yaml
+catalog: lakehouse
+database: cdc_demo
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in three passes shows updates and deletes applied incrementally, out-of-order events reconciled within a batch, and a stale re-delivery in a later run discarded against committed state.
+
+It reads the change feed from a directory of JSON files, so appending a batch and re-running shows the incremental behavior. The target uses the `lakehouse` catalog from [Choosing a Target Format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+`spark-pipelines init` seeds `transformations/` with `example_python_materialized_view.py` and `example_sql_materialized_view.sql`. Delete them so only the CDC datasets run, then edit `spark-pipeline.yml` to add your catalog as shown in [Choosing a Target Format](#choosing-a-target-format), and put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, and inserts `id 3`. The update for `id 1` also arrives out of order within the batch, before its own earlier value:
Review Comment:
The prose and the data disagree: `batch2.json` writes `version: 1` before `version: 2`, so the update for `id 1` arrives *after* its earlier value, in arrival order. Line 791 repeats the claim ("landed in the same batch out of order").
Swapping the two `id 1` lines makes the text accurate. The rendered output is unaffected, since intra-batch reconciliation is a `max_by` group-by (`Scd1BatchProcessor.deduplicateMicrobatch`) and therefore insensitive to row order -- so the example's results do not need re-verifying.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` produces - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+Auto CDC needs a table provider that implements row-level operations, configured as a catalog in the pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; consult your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface Auto CDC requires. The catalog must also persist metadata across runs, per [Requirements](#requirements).
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Add your catalog to the generated `spark-pipeline.yml` - substituting your own catalog name and connector class - without disturbing the `name`, `storage`, and `libraries` values `spark-pipelines init` already wrote:
+
+```yaml
+catalog: lakehouse
+database: cdc_demo
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in three passes shows updates and deletes applied incrementally, out-of-order events reconciled within a batch, and a stale re-delivery in a later run discarded against committed state.
+
+It reads the change feed from a directory of JSON files, so appending a batch and re-running shows the incremental behavior. The target uses the `lakehouse` catalog from [Choosing a Target Format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+`spark-pipelines init` seeds `transformations/` with `example_python_materialized_view.py` and `example_sql_materialized_view.sql`. Delete them so only the CDC datasets run, then edit `spark-pipeline.yml` to add your catalog as shown in [Choosing a Target Format](#choosing-a-target-format), and put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, and inserts `id 3`. The update for `id 1` also arrives out of order within the batch, before its own earlier value:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The two `id 1` events landed in the same batch out of order; Auto CDC collapsed them to the highest sequence value per key before applying, so the row is `alicia`, not the earlier `alice`.
+
+Ordering also holds *across* runs, against state already committed. Add a third batch that re-delivers the original `id 1` event at version 1, as a re-sending source might:
+
+```bash
+cat > /tmp/cdc_demo/events/batch3.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run once more:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+The table is unchanged. This time the stale event is the only row in its batch, so there is nothing to collapse it against; Auto CDC compares its version against the state already recorded for `id 1` and discards it, because version 1 is below the committed version 2. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling Deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting Which Columns Land in the Target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling Out-of-Order and Duplicate Events
+
+The source need not be sorted or de-duplicated. Auto CDC orders events for a key by their sequence value, in two places: within a microbatch it collapses same-key events to the highest sequence value before applying them, and across runs it compares an incoming event against the state already committed for its key and discards anything older. The end-to-end example above shows both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a Composite Key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the Key Set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported: the run fails with `AUTOCDC_INVALID_STATE.KEY_SCHEMA_DRIFT`. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+Beyond the [Requirements](#requirements) above, two engine details are worth knowing:
+
+- **Reserved column names** - Auto CDC owns the `__spark_autocdc_` column-name prefix; it projects an internal `__spark_autocdc_metadata` column onto the target, and SCD Type 2 adds more. The source cannot contain any column whose name begins with `__spark_autocdc_`; a collision fails when the flow is constructed. Treat these as engine details rather than columns to query.
+- **Declaring a schema explicitly** - A schema declared on the target streaming table must currently include the reserved metadata column, because the declared schema has to match the flow's output schema exactly. Omitting the schema and letting Auto CDC derive it avoids this. [SPARK-58118](https://issues.apache.org/jira/browse/SPARK-58118) tracks relaxing it.
Review Comment:
This holds for Python `create_streaming_table(schema=...)` and for a separately declared `CREATE STREAMING TABLE`, but not for the combined SQL form, which rejects a column list outright rather than requiring the metadata column in it -- `SqlGraphRegistrationContext.CreateStreamingTableAutoCdcHandler`: "Explicit column lists are not supported for AUTO CDC streaming tables; omit the column list and let schema be inferred from the flow."
A clause noting that the combined form disallows an explicit schema entirely would cover both paths.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
Review Comment:
Worth stating what applies when the clause is omitted: `AutoCdcInto`'s `storedAsScdType` "Defaults to 1 when no `STORED AS` clause is specified" (`sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/AutoCdcInto.scala`). Since the section is scoped to Type 1, noting the default saves the reader from assuming the clause is required.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3759974262
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` produces - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+Auto CDC needs a table provider that implements row-level operations, configured as a catalog in the pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; consult your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface Auto CDC requires. The catalog must also persist metadata across runs, per [Requirements](#requirements).
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Add your catalog to the generated `spark-pipeline.yml` - substituting your own catalog name and connector class - without disturbing the `name`, `storage`, and `libraries` values `spark-pipelines init` already wrote:
+
+```yaml
+catalog: lakehouse
+database: cdc_demo
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in three passes shows updates and deletes applied incrementally, out-of-order events reconciled within a batch, and a stale re-delivery in a later run discarded against committed state.
+
+It reads the change feed from a directory of JSON files, so appending a batch and re-running shows the incremental behavior. The target uses the `lakehouse` catalog from [Choosing a Target Format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+`spark-pipelines init` seeds `transformations/` with `example_python_materialized_view.py` and `example_sql_materialized_view.sql`. Delete them so only the CDC datasets run, then edit `spark-pipeline.yml` to add your catalog as shown in [Choosing a Target Format](#choosing-a-target-format), and put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, and inserts `id 3`. The update for `id 1` also arrives out of order within the batch, before its own earlier value:
Review Comment:
Fixed. Swapped the two `id 1` lines in `batch2.json` so the newer value (version 2) now precedes the stale one (version 1) - the events are genuinely out of arrival order, matching the prose at line 791. As you note, the rendered output is unchanged since `deduplicateMicrobatch` is a `max_by` group-by, so no re-verification was needed.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
Review Comment:
Fixed all of these. Applied your suggested impersonal rewrites at 522, 540, 541, 631, 637, 685, 687, 700, 709, 830, and 834. The only remaining `your` in the section is inside the YAML placeholder `<your connector's catalog class>`, which reads naturally as a fill-in.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
Review Comment:
Fixed. Scoped the sentence to within a microbatch: "Within a microbatch, ties on the sequence value for a key are broken arbitrarily." You are right that across runs it is defined rather than arbitrary - I confirmed `incomingWinsUpsert` uses `>=` and `incomingWinsDelete` uses `>` in `Scd1BatchProcessor`. The per-event-unique recommendation stays.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
Review Comment:
Fixed. Dropped "first" (now "a target streaming table, which is defined with `create_streaming_table`") and dropped "already" from the `target` parameter row, so both read consistently with the Requirements note that definition order does not matter.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
Review Comment:
Added. The `STORED AS SCD TYPE` clause bullet now reads "Optional; defaults to Type 1 when omitted, which is the behavior described here", matching `AutoCdcInto`'s documented default.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,374 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and Sequencing
+
+Auto CDC needs two things to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC Does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This section covers **Slowly Changing Dimensions (SCD) Type 1**, where the target keeps only the current version of each row, with no history of prior values. SCD Type 2 is also supported; [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570) tracks documenting it.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under [Considerations](#auto-cdc-considerations)):
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last, but Auto CDC orders the events for a key by sequence value rather than arrival, so version 2 wins and the row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below. An Auto CDC flow cannot target a materialized view or an external table. Order within the source file does not matter; the graph is resolved after all definitions are registered.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a Target Format](#choosing-a-target-format).
+- The **target must have exactly one input flow.** An Auto CDC flow cannot share a target with other flows; a target fed by more than one flow, one of which is Auto CDC, fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. This rules out the fan-in pattern shown in "Using Multiple Flows to Write to a Single Target" above.
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- The **catalog's metadata must survive between runs**, since each incremental run re-resolves the tables an earlier run created. This is a property of the connector, not of setting `spark.sql.catalog.*`. Spark's default session catalog keeps metadata only for the life of the session, so a second `spark-pipelines run` against it fails with `LOCATION_ALREADY_EXISTS`; use a catalog whose metastore persists.
+- The flow must specify **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** The expression may change between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key for deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a Target
+# Format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Pass `1` (or `"1"`) for the Type 1 behavior described here. Type 2 is also accepted; see [SPARK-58570](https://issues.apache.org/jira/browse/SPARK-58570). |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`. (`sequence_by` is not restricted this way; it may be any expression over the source columns.)
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; use `1` for the Type 1 behavior described here.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` produces - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+Auto CDC needs a table provider that implements row-level operations, configured as a catalog in the pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; consult your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface Auto CDC requires. The catalog must also persist metadata across runs, per [Requirements](#requirements).
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Add your catalog to the generated `spark-pipeline.yml` - substituting your own catalog name and connector class - without disturbing the `name`, `storage`, and `libraries` values `spark-pipelines init` already wrote:
+
+```yaml
+catalog: lakehouse
+database: cdc_demo
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in three passes shows updates and deletes applied incrementally, out-of-order events reconciled within a batch, and a stale re-delivery in a later run discarded against committed state.
+
+It reads the change feed from a directory of JSON files, so appending a batch and re-running shows the incremental behavior. The target uses the `lakehouse` catalog from [Choosing a Target Format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+`spark-pipelines init` seeds `transformations/` with `example_python_materialized_view.py` and `example_sql_materialized_view.sql`. Delete them so only the CDC datasets run, then edit `spark-pipeline.yml` to add your catalog as shown in [Choosing a Target Format](#choosing-a-target-format), and put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql import DataFrame
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table
+def cdc_events() -> DataFrame:
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, and inserts `id 3`. The update for `id 1` also arrives out of order within the batch, before its own earlier value:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The two `id 1` events landed in the same batch out of order; Auto CDC collapsed them to the highest sequence value per key before applying, so the row is `alicia`, not the earlier `alice`.
+
+Ordering also holds *across* runs, against state already committed. Add a third batch that re-delivers the original `id 1` event at version 1, as a re-sending source might:
+
+```bash
+cat > /tmp/cdc_demo/events/batch3.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run once more:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+The table is unchanged. This time the stale event is the only row in its batch, so there is nothing to collapse it against; Auto CDC compares its version against the state already recorded for `id 1` and discards it, because version 1 is below the committed version 2. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling Deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting Which Columns Land in the Target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling Out-of-Order and Duplicate Events
+
+The source need not be sorted or de-duplicated. Auto CDC orders events for a key by their sequence value, in two places: within a microbatch it collapses same-key events to the highest sequence value before applying them, and across runs it compares an incoming event against the state already committed for its key and discards anything older. The end-to-end example above shows both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a Composite Key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the Key Set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported: the run fails with `AUTOCDC_INVALID_STATE.KEY_SCHEMA_DRIFT`. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+Beyond the [Requirements](#requirements) above, two engine details are worth knowing:
+
+- **Reserved column names** - Auto CDC owns the `__spark_autocdc_` column-name prefix; it projects an internal `__spark_autocdc_metadata` column onto the target, and SCD Type 2 adds more. The source cannot contain any column whose name begins with `__spark_autocdc_`; a collision fails when the flow is constructed. Treat these as engine details rather than columns to query.
+- **Declaring a schema explicitly** - A schema declared on the target streaming table must currently include the reserved metadata column, because the declared schema has to match the flow's output schema exactly. Omitting the schema and letting Auto CDC derive it avoids this. [SPARK-58118](https://issues.apache.org/jira/browse/SPARK-58118) tracks relaxing it.
Review Comment:
Fixed. The consideration now distinguishes the two paths: a separately declared schema (`create_streaming_table(schema=...)` or standalone `CREATE STREAMING TABLE`) must include the reserved metadata column, while the combined `CREATE STREAMING TABLE ... FLOW AUTO CDC` form takes no column list at all and infers the schema from the flow. Confirmed against `CreateStreamingTableAutoCdcHandler`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3754699236
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
Review Comment:
Fixed both snippets: added `from pyspark.sql import DataFrame` and `-> DataFrame` return annotations, and changed the end-to-end snippet from `@dp.table(name="cdc_events")` to bare `@dp.table` (the derived name is already `cdc_events`).
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
Review Comment:
Fixed. Removed `sequence_by` from the unqualified-identifier sentence (and from the Considerations entry, which is now gone -- see the triplication thread). You are right the docstring and `AUTOCDC_NON_COLUMN_IDENTIFIER` message make the same over-broad claim; I will file a separate PR for those since they are code, not docs.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
Review Comment:
Fixed both. The catalog-persistence requirement is now its own Requirements bullet stating that metadata must survive between runs because incremental runs re-resolve tables, that this is a connector property rather than a consequence of setting `spark.sql.catalog.*`, and that the default session catalog fails a second run with `LOCATION_ALREADY_EXISTS`. The "Choosing a Target Format" subsection no longer claims configuring a catalog makes it persistent.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
Review Comment:
Fixed. The spec block now shows only the lines to add (`catalog`, `database`, `configuration`), explicitly telling the reader not to disturb the generated `name`/`storage`/`libraries`. Added a sentence to delete the seeded `example_python_materialized_view.py` / `example_sql_materialized_view.sql` so only the CDC datasets run. On the `cdc_demo` name collision: the events path is now the only place the name is reused; I kept the project name `cdc_demo` but can rename the feed dir if you still find it confusing.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
Review Comment:
Fixed, and thank you -- this was the substantive bug. The example is now three runs. Batch 2 carries id 1's two events out of order in one microbatch (intra-batch reconciliation keeps `alicia`, labelled as such). Batch 3 re-delivers the stale id-1 event alone, so it exercises the recorded-state comparison against committed version 2 -- which is what @anew originally asked to see. Both paths are now demonstrated and labelled. Verified end-to-end against the merge engine.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
Review Comment:
Fixed -- now "is not supported: the run fails with `AUTOCDC_INVALID_STATE.KEY_SCHEMA_DRIFT`", matching how the section describes sequencing-type drift. The docstring's "undefined behavior" is code; I will fix that separately.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+- **Target must be a streaming table** - You cannot apply an Auto CDC flow to a materialized view or an external table.
Review Comment:
Fixed all three -- the reserved-name and schema bullets are impersonal now ("The source cannot contain...", "A schema declared on the target streaming table must currently include..."), and the materialized-view/external-table line moved into Requirements as "An Auto CDC flow cannot target...".
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+- **Target must be a streaming table** - You cannot apply an Auto CDC flow to a materialized view or an external table.
+- **Streaming source required** - The source must be read as a stream.
+- **Immutable key set** - Changing `keys` between incremental runs requires a full refresh (see above).
+- **Unqualified column identifiers** - `keys`, `sequence_by`, and the column lists must be plain, unqualified column names.
+- **Table format** - The target must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. Spark's built-in file formats, including Parquet, do not; see [Choosing a target format](#choosing-a-target-format).
+- **Reserved column names** - Auto CDC projects an internal `__spark_autocdc_metadata` column onto the target. Your source cannot contain a column with that name; a collision fails when the flow is constructed. Treat it as an engine detail rather than a column to query.
Review Comment:
Fixed. The Considerations entry now says the source cannot contain "any column whose name begins with `__spark_autocdc_`" and notes SCD Type 2 adds more reserved columns. Also corrected the schema bullet from plural "reserved columns" to the single metadata column for the Type 1 case.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
Review Comment:
Fixed -- this was the root cause the change author asked me to prioritize. Collapsed the triplication: Considerations dropped from eight bullets to two (reserved column names, explicit-schema caveat), the rest replaced by a cross-reference to Requirements. Requirements is now the single source for the shared facts, which is what let the `sequence_by` claim diverge before. The section did grow slightly overall because the end-to-end example gained a third run to fix the out-of-order bug above; if length is still a concern I am happy to trim the how-tos further.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on PR #57149:
URL: https://github.com/apache/spark/pull/57149#issuecomment-5270601946
Thanks, will merge when Ci green
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3754698619
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
Review Comment:
Fixed all four: the intro is now "Auto CDC does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains..."; "needs two things to make sense of a change feed"; "...with no `format` produces"; and the end-to-end intro now says "appending a batch and re-running shows the incremental behavior".
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
Review Comment:
Fixed. All section and how-to headings are now Title Case (Keys and Sequencing, What Auto CDC Does, Handling Deletes, Selecting Which Columns Land in the Target, Handling Out-of-Order and Duplicate Events, Using a Composite Key, Changing the Key Set).
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
Review Comment:
Deliberately keeping the "SCD Type 1 is the only mode currently supported" wording for now, at the request of the change author -- the intent is to add the SCD Type 2 documentation and remove this line in the same follow-up (SPARK-58570), so the guide never briefly describes Type 2 without documenting it. You are right that Type 2 is present on all shippable branches (I confirmed `ScdType.Type2` in `ChangeArgs.scala` on `branch-4.2`, `branch-4.x`, and `master`), so this is a scoping choice rather than a factual claim we stand behind long-term. If you would rather not merge with the line as-is, I will switch to the scoped phrasing you suggested.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
Review Comment:
Fixed. The sentence above the table now reads "...produces this target table (dropping the `op` column, and shown without the internal metadata column Auto CDC appends - covered under Considerations)", so both the `op` exclusion and the four-vs-three-column point are addressed before the table.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
Review Comment:
Added. New Requirements bullet: the target must have exactly one input flow, and a target fed by more than one flow (one being Auto CDC) fails with `AUTOCDC_MULTIPLE_FLOWS_TO_TARGET`. It explicitly calls out that this rules out the fan-in pattern from the "Using Multiple Flows..." sections above.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
Review Comment:
Fixed. Reworded to "The target must be a streaming table defined in the pipeline... Order within the source file does not matter; the graph is resolved after all definitions are registered."
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
Review Comment:
Fixed. "The flow must specify keys ... and a sequencing expression"; "The expression may change between incremental runs, but not its type"; "for deterministic results across replays".
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
Review Comment:
Fixed -- now `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT`, matching the qualified `AUTOCDC_MICROBATCH_VALIDATION.*` names in the two bullets above.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3752646182
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
Review Comment:
A few places where the second person is filler rather than addressing a reader action, and the sentence is tighter without it:
- here: "**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains..." -> "**Auto CDC** does this automatically. Given a source of change events and a rule for identifying and ordering them, SDP maintains..."
- line 528: "Auto CDC needs two things from you to make sense of a change feed" -> "...needs two things to make sense of a change feed"
- line 674: "which is what a `create_streaming_table("customers")` with no `format` gives you" -> "...with no `format` produces"
- line 704: "so you can append a batch and re-run to see what happens" -> "...so appending a batch and re-running shows the incremental behavior" ("to see what happens" does not tell the reader what to look for)
The rest of the second person in the section reads fine to me and matches the RDD and quick-start guides.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
Review Comment:
Heading case is mixed against the rest of the guide, which is Title Case at both `###` and `####` ("Creating a Streaming Table in Python", "Refresh Selection Behavior", "Sink Considerations"). Sentence case here and at line 535 ("What Auto CDC does"), line 798 ("Handling deletes"), and the other `####` how-to headings, while "Choosing a Target Format" and "End-to-End Example" are Title Case.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
Review Comment:
"SCD Type 1 is the only mode currently supported" is not true on any branch this can ship in. `ScdType.Type2` is present in `sql/pipelines/src/main/scala/org/apache/spark/sql/pipelines/autocdc/ChangeArgs.scala` on `master`, `branch-4.x`, *and* `branch-4.2`, with a full `Scd2BatchProcessor`, `TRACK HISTORY ON` in the grammar, `__START_AT` / `__END_AT` in `AutoCdcMergeFlow.schema`, and an `AUTOCDC_TRACK_HISTORY_REQUIRES_SCD2` error condition. Both front doors accept it:
- `python/pyspark/pipelines/api.py`: `stored_as_scd_type: Optional[Literal[1, 2, "1", "2"]]`, docstring "1 (or "1") and 2 (or "2") are supported"
- `SqlGraphRegistrationContext.scala:307-314`: `case 1 => ScdType.Type1; case 2 => ScdType.Type2`, and the rejection message for anything else reads "Only SCD TYPE 1 and SCD TYPE 2 are supported"
The same claim appears in two more places: line 624 (the `stored_as_scd_type` row, "Only `1` (or `"1"`) is supported") and line 666 (`STORED AS SCD TYPE 1`, "only Type 1 is supported").
Suggest scoping rather than denying, e.g. "This section covers SCD Type 1, where the target keeps only the current version of each row. SCD Type 2 is also supported; SPARK-58570 tracks documenting it." That keeps the diff narrow and leaves nothing to un-say later.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
Review Comment:
"Create it with `create_streaming_table` ... **before** defining the Auto CDC flow" reads as though ordering within the file matters. The graph is resolved after all definitions are registered, so `create_auto_cdc_flow` can precede `create_streaming_table` in the source.
Suggest: "The target streaming table must also be defined in the pipeline, via `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL), or declared together with the flow using the combined SQL form below."
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
Review Comment:
`SEQUENCING_TYPE_DRIFT` is a subcondition of `AUTOCDC_INVALID_STATE`, so the name a user sees and can search for is `AUTOCDC_INVALID_STATE.SEQUENCING_TYPE_DRIFT`. The two bullets above correctly qualify `AUTOCDC_MICROBATCH_VALIDATION.*`, so this reads as an oversight rather than a choice.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
Review Comment:
Every other Python snippet in the guide imports `DataFrame` and annotates the return type:
```python
from pyspark import pipelines as dp
from pyspark.sql import DataFrame
@dp.table
def basic_st() -> DataFrame:
```
Worth matching here and in the end-to-end example. Also line 730 uses `@dp.table(name="cdc_events")` on a function already named `cdc_events`, which diverges from the bare `@dp.table` in this snippet -- the guide introduces the `name=` argument specifically as the way to *override* the derived name.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
Review Comment:
This contradicts line 576, which says the sequencing expression "may be any SQL expression over the source columns, not just a bare column reference." Line 576 is the correct one.
In `PipelinesHandler.buildAutoCdcFlow`, the `asUnqualifiedColumnName` check (which raises `AUTOCDC_NON_COLUMN_IDENTIFIER`) is applied to `keys`, `column_list`, `except_column_list`, and the track-history lists, but the sequencing expression goes through `toColumn` with no attribute check:
```scala
val changeArgs = ChangeArgs(
keys = keys,
sequencing = toColumn(autoCdcDetails.getSequenceBy),
```
`Scd1BatchProcessorSuite` and `Scd1BatchProcessorMergeSuite` both pass `sequencing = F.lit(0L)`, so non-attribute expressions demonstrably work.
Dropping `sequence_by` from this sentence fixes it. Note that the `create_auto_cdc_flow` docstring and the `AUTOCDC_NON_COLUMN_IDENTIFIER` message text make the same over-broad claim, which is probably where this came from -- worth a separate PR. Same issue at line 868 in Considerations.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
Review Comment:
Two problems here, both affecting whether the two-run example actually reproduces:
1. "Configuring a catalog also gives you a persistent one" is not generally true -- persistence is a property of the specific connector, not of setting `spark.sql.catalog.*`. A reader who wires up a non-persistent catalog hits the same second-run failure the example depends on avoiding, with no hint why.
2. `LOCATION_ALREADY_EXISTS` has nothing to do with the target format; it comes from the in-memory catalog implementation. Someone debugging it will not look in a subsection titled "Choosing a Target Format".
Suggest promoting this to its own Requirements bullet ("a catalog whose metadata survives the session, since incremental runs re-resolve the tables an earlier run created") and stating concretely what to configure.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
Review Comment:
"produces undefined results" understates the engine, and will worry readers about a case it handles safely. Key drift is detected on every incremental run where the auxiliary table exists -- `DatasetManager.validateNoAutoCdcAuxConfigDrift` -> `AutoCdcAuxiliaryTable.validateNoKeyColumnDrift` -- and fails with `AUTOCDC_INVALID_STATE.KEY_SCHEMA_DRIFT`: "AutoCDC does not support changing key columns or their types across incremental pipeline runs. Correct the conflicting flow(s) or perform a full refresh of the target table."
Suggest "...is not supported: the run fails with `AUTOCDC_INVALID_STATE.KEY_SCHEMA_DRIFT`", which also matches how the section already describes sequencing-type drift. (`create_auto_cdc_flow`'s docstring still says "will produce undefined behavior" -- also worth fixing separately.)
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+- **Target must be a streaming table** - You cannot apply an Auto CDC flow to a materialized view or an external table.
Review Comment:
Register flips inside this list, and against the lists it parallels. `Sink Considerations`, `Python Considerations`, and `SQL Considerations` are uniformly declarative statements about the system ("Sinks currently support only streaming queries...", "The `PIVOT` clause is not supported in SDP SQL"), and half of these bullets match that while half switch to second person:
- line 865: "You cannot apply an Auto CDC flow to a materialized view or an external table" -> "An Auto CDC flow cannot target a materialized view or an external table"
- line 870: "Your source cannot contain a column with that name" -> "The source cannot contain a column with that name"
- line 871: "If you declare a schema on the target streaming table, it must currently include..." -> "A schema declared on the target streaming table must currently include..."
This also makes each bullet body agree with its own bold label. (Second person generally is fine and idiomatic here -- the guide uses it throughout -- it is the mid-list switch that reads oddly.)
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
Review Comment:
The stated reason is not what happens here. `batch2.json` carries both the `version 2` update and the late `version 1` duplicate for `id 1`, so run 2 sees both in a single microbatch and the stale one is dropped by intra-batch reconciliation, before any comparison against recorded state:
```
Scd1BatchProcessor.scala:46
* 1. [[deduplicateMicrobatch]]: collapse same-key events to the latest by sequence.
```
So "version 1 is below the version 2 already recorded for that key" describes a path the example never takes, and @anew's original request -- a late event arriving in a *later run* than the newer event, with the pipeline run after each batch -- still is not demonstrated.
Moving the late duplicate into a third `batch3.json` and running a third time would make the walkthrough match its explanation and cover the recorded-state comparison. Worth keeping the intra-batch case too, since it is a real behavior, just labelled as such.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
+
+- **Target must be a streaming table** - You cannot apply an Auto CDC flow to a materialized view or an external table.
+- **Streaming source required** - The source must be read as a stream.
+- **Immutable key set** - Changing `keys` between incremental runs requires a full refresh (see above).
+- **Unqualified column identifiers** - `keys`, `sequence_by`, and the column lists must be plain, unqualified column names.
+- **Table format** - The target must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. Spark's built-in file formats, including Parquet, do not; see [Choosing a target format](#choosing-a-target-format).
+- **Reserved column names** - Auto CDC projects an internal `__spark_autocdc_metadata` column onto the target. Your source cannot contain a column with that name; a collision fails when the flow is constructed. Treat it as an engine detail rather than a column to query.
Review Comment:
The reserved surface is the whole `__spark_autocdc_` prefix, not just this one column -- see `AutoCdcReservedNames.prefix` and `AUTOCDC_RESERVED_COLUMN_NAME_PREFIX_CONFLICT`, which is a separate error from the exact-name `AUTOCDC_RESERVED_COLUMN_NAME_CONFLICT`. Worth saying "any column name beginning with `__spark_autocdc_`".
Relatedly, line 871 says the declared schema "must currently include the reserved columns above" -- plural, for one named column.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
Review Comment:
Same register switch as in Considerations: the bullets around this one are impersonal ("The **target must be a streaming table**...", "The **source must be a streaming source**..."), then this one becomes "You must provide". Suggest "The flow must specify **keys** ... and a **sequencing expression**".
Ditto for the constraint list below: "Its type must be orderable" and "It must never be null", then line 580 "You may change the expression between incremental runs" -> "The expression may change between incremental runs, but not its type". And line 582, "if you need deterministic results across replays" -> "for deterministic results across replays".
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
Review Comment:
Missing requirement: an Auto CDC target must have exactly one input flow.
```scala
// GraphValidations.scala:39-46
// A multiflow table may not have an AutoCDC flow; AutoCDC targets must have exactly one
// input flow.
multiQueryTables.find { case (_, flows) => flows.exists(isAutoCdcFlow) }.foreach { ...
throw new AnalysisException("AUTOCDC_MULTIPLE_FLOWS_TO_TARGET", ...
```
This matters more than usual because the guide's "Using Multiple Flows to Write to a Single Target" sections sit immediately above this one, and the new SQL example uses the same `CREATE STREAMING TABLE t; CREATE FLOW f ...` shape those sections use for fan-in. A reader will try adding an append flow next to an Auto CDC flow. Worth a Requirements bullet and a Considerations entry.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
Review Comment:
Two small mismatches between this table and what a reader would actually see:
- `AutoCdcMergeFlow.schema` appends a non-nullable `__spark_autocdc_metadata` field to the Type 1 output schema, so `SELECT *` returns four columns, not three. Considerations mentions the column exists, but that is ~300 lines later. One clause here ("shown without the internal metadata column") closes the gap, and covers the two end-to-end tables as well.
- The output drops `op`, but no column selection has been introduced yet -- `except_column_list` first appears in the next subsection. Either mention it in the sentence above the table, or keep `op` in the output.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
Review Comment:
Two snags for a reader following this literally:
- The spec shown in "Choosing a target format" has `storage: file:///absolute/path/to/storage/dir`, but `spark-pipelines init` already wrote a working absolute `file://.../pipeline-storage` path. Pasting that block over the generated spec replaces a good value with a placeholder. Showing only the lines to add (`catalog`, `database`, `configuration`) avoids it.
- `init` also leaves `example_python_materialized_view.py` and `example_sql_materialized_view.sql` in `transformations/`, so they run alongside `customers_cdc.py`. Worth a word, since the walkthrough presents the run output as if only the CDC datasets exist.
Minor: `cdc_demo` names both the project directory and the unrelated `/tmp/cdc_demo/events` feed path, which reads as though they are connected.
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
+
+For example, take these change events. Note that they are **not** in `version` order: the last event for `id = 1` is a stale update that arrives after the newer one.
+
+| id | name | version | op |
+|----|--------|---------|--------|
+| 1 | alice | 1 | UPSERT |
+| 2 | bob | 1 | UPSERT |
+| 1 | alicia | 2 | UPSERT |
+| 2 | bob | 2 | DELETE |
+| 3 | carol | 1 | UPSERT |
+| 1 | alice | 1 | UPSERT |
+
+Auto CDC with `stored_as_scd_type=1`, keyed on `id` and sequenced by `version`, produces this target table:
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+Walking through it by key:
+
+- **id 1** was inserted as `alice`, then updated to `alicia` at version 2. The re-delivered `alice` event at version 1 arrives last but is ignored, because version 1 is older than the version 2 already applied. The row keeps `alicia`.
+- **id 2** was inserted, then deleted at version 2, so it is absent from the target.
+- **id 3** was inserted and never changed.
+
+### Requirements
+
+- The **target must be a streaming table** that already exists in the pipeline. Create it with `create_streaming_table` (Python) or `CREATE STREAMING TABLE` (SQL) before defining the Auto CDC flow, or use the combined SQL form shown below that does both at once.
+- The **target's format must support row-level operations.** Auto CDC maintains the target with MERGE, so the table must be backed by a connector implementing the DSv2 `SupportsRowLevelOperations` interface. A target that does not fails at startup with `AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE`. Spark's built-in file formats, including Parquet, do **not** qualify; see [Choosing a target format](#choosing-a-target-format).
+- The **source must be a streaming source** (read with `spark.readStream` in Python or `STREAM(...)` in SQL). CDC is an incremental operation over newly arriving change events.
+- You must provide **keys** (one or more columns that identify a row) and a **sequencing expression** (used to order events per key).
+
+The sequencing expression may be any SQL expression over the source columns, not just a bare column reference, so `SEQUENCE BY` on a struct of `(commit_ts, seq_no)` or a cast is fine. It must satisfy three constraints:
+
+- **Its type must be orderable.** A non-orderable type fails with `AUTOCDC_MICROBATCH_VALIDATION.NON_ORDERABLE_SEQUENCE`.
+- **It must never be null.** A microbatch containing a null sequence value fails with `AUTOCDC_MICROBATCH_VALIDATION.NULL_SEQUENCE` rather than guessing an order.
+- **Its result type must stay the same across runs.** You may change the expression between incremental runs, but not its type, or recorded values would stop being comparable; that fails with `SEQUENCING_TYPE_DRIFT` and needs a full refresh.
+
+Ties are broken arbitrarily, so prefer an expression that is unique per event for a key if you need deterministic results across replays.
+
+### Defining an Auto CDC Flow in Python
+
+Use `create_auto_cdc_flow` to write change events into a target streaming table. Create the target with `create_streaming_table` first.
+
+```python
+from pyspark import pipelines as dp
+
+# The source of change events: a streaming read of the CDC feed.
+@dp.table
+def cdc_events():
+ return spark.readStream.table("cdc_source")
+
+# The target that Auto CDC keeps in sync. It must be a streaming table, in a
+# catalog whose format supports row-level operations (see "Choosing a target
+# format" below).
+dp.create_streaming_table("customers")
+
+# The Auto CDC flow that applies the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+`create_auto_cdc_flow` accepts the following arguments:
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| `target` | Yes | Name of the target streaming table that receives the changes. It must already be defined in the pipeline. |
+| `source` | Yes | Name of the CDC source dataset to stream change events from. |
+| `keys` | Yes | The column or columns that uniquely identify a row. A list of column names (strings) or `Column` objects, given as unqualified identifiers: for example `"id"` or `col("id")`, but not `"source.id"`. |
+| `sequence_by` | Yes | An expression used to order change events for each key. The highest value wins. A SQL expression string or a `Column`. |
+| `apply_as_deletes` | No | A boolean expression identifying events that represent deletes. Matching rows are removed from the target. A SQL expression string or a `Column`. |
+| `column_list` | No | The columns to include in the target. Mutually exclusive with `except_column_list`. |
+| `except_column_list` | No | The columns to exclude from the target; all other columns are included. Mutually exclusive with `column_list`. Commonly used to drop operation/metadata columns such as `op`. |
+| `stored_as_scd_type` | No | The SCD type of the target. Only `1` (or `"1"`) is supported. |
+| `name` | No | The name of the flow. Defaults to the target table name. |
+| `spark_conf` | No | Spark confs to set while the flow runs. These override confs set on the destination, the pipeline, or the cluster. |
+
+If you specify neither `column_list` nor `except_column_list`, all columns from the source are written to the target. That is usually not what you want for a CDC feed: the operation column and any other change-feed bookkeeping would land in the target alongside the data. Exclude them explicitly, as the examples here do with `except_column_list=["op"]`.
+
+`keys`, `sequence_by`, `column_list`, and `except_column_list` must be given as unqualified column identifiers: `"id"` or `col("id")`, but not `"cdc_events.id"` or `col("cdc_events.id")`.
+
+### Defining an Auto CDC Flow in SQL
+
+SQL provides two forms. The first attaches an Auto CDC flow to a streaming table you have already declared:
+
+```sql
+CREATE STREAMING TABLE customers;
+
+CREATE FLOW customers_cdc AS AUTO CDC INTO customers
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+The second declares the streaming table and its Auto CDC flow together:
+
+```sql
+CREATE STREAMING TABLE customers
+FLOW AUTO CDC
+FROM STREAM(cdc_events)
+KEYS (id)
+APPLY AS DELETE WHEN op = 'DELETE'
+SEQUENCE BY version
+COLUMNS * EXCEPT (op);
+```
+
+`FROM STREAM(source)` and `KEYS (col, ...)` come first, in that order. The remaining clauses may appear in any order after them:
+
+- `FROM STREAM(source)` - the streaming CDC source. **Required, first.**
+- `KEYS (col, ...)` - the key columns that identify a row. **Required, second.**
+- `SEQUENCE BY expr` - the expression that orders events per key. **Required.**
+- `APPLY AS DELETE WHEN condition` - marks events that represent deletes. Optional.
+- `COLUMNS (col, ...)` or `COLUMNS * EXCEPT (col, ...)` - selects or excludes columns. Optional; if omitted, all source columns are written.
+- `STORED AS SCD TYPE 1` - selects the SCD type. Optional; only Type 1 is supported.
+
+`CREATE FLOW ... AS AUTO CDC INTO` also accepts an optional `COMMENT`, and `CREATE STREAMING TABLE ... FLOW AUTO CDC` accepts `IF NOT EXISTS`.
+
+### Choosing a Target Format
+
+Auto CDC applies each microbatch to the target with a MERGE, so the target has to be a table that supports row-level updates and deletes. Concretely, its connector must implement the DSv2 `SupportsRowLevelOperations` interface.
+
+Spark's built-in file-based formats do not. Pointing an Auto CDC flow at a plain Parquet target - which is what a `create_streaming_table("customers")` with no `format` gives you - fails when the flow starts:
+
+```
+[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE] Cannot start AutoCDC flow: the target table
+`spark_catalog`.`default`.`customers` (format: parquet) does not support row-level
+operations. AutoCDC requires a target backed by a connector that supports MERGE.
+```
+
+To use Auto CDC you need a table provider that implements row-level operations, configured as a catalog in your pipeline. Lakehouse connectors such as Apache Iceberg are the usual choice; check your connector's documentation for whether it implements the DSv2 row-level operation interfaces and how to register its catalog. Note that supporting the `MERGE INTO` SQL statement is not on its own sufficient: a connector can implement MERGE through its own planner extension without implementing the DSv2 interface that Auto CDC requires.
+
+Configuring a catalog also gives you a persistent one, which incremental runs need. Spark's default session catalog keeps table metadata only for the life of the session, so a second `spark-pipelines run` cannot find the tables the first run created and fails with `LOCATION_ALREADY_EXISTS`.
+
+The examples below use a catalog named `lakehouse` to stand in for such a connector. Substitute your own catalog name and set the corresponding `spark.sql.catalog.*` configuration in your pipeline spec:
+
+```yaml
+name: cdc_demo
+storage: file:///absolute/path/to/storage/dir
+catalog: lakehouse
+database: cdc_demo
+libraries:
+ - glob:
+ include: transformations/**
+configuration:
+ spark.sql.catalog.lakehouse: <your connector's catalog class>
+```
+
+### End-to-End Example
+
+This example builds a small pipeline that ingests customer change events and maintains a `customers` table holding the latest state of each customer. Running it in two passes shows both that updates and deletes are applied incrementally, and that a late event is correctly ignored.
+
+It reads the change feed from a directory of JSON files, so you can append a batch and re-run to see what happens. The target uses the `lakehouse` catalog from [Choosing a target format](#choosing-a-target-format); substitute your own row-level-operation-capable catalog.
+
+Create a pipeline project:
+
+```bash
+spark-pipelines init --name cdc_demo
+cd cdc_demo
+```
+
+Point the pipeline at your catalog by editing `spark-pipeline.yml` as shown in [Choosing a target format](#choosing-a-target-format), then put the following in `transformations/customers_cdc.py`:
+
+```python
+from pyspark import pipelines as dp
+from pyspark.sql.types import (
+ IntegerType, LongType, StringType, StructField, StructType)
+
+# An explicit schema keeps the streaming JSON read from having to infer one.
+SCHEMA = StructType([
+ StructField("id", IntegerType()),
+ StructField("name", StringType()),
+ StructField("version", LongType()),
+ StructField("op", StringType()),
+])
+
+# Ingest the raw change events. In a real pipeline this would read from Kafka,
+# cloud storage, or a database CDC feed; here it tails a directory of JSON files.
+@dp.table(name="cdc_events")
+def cdc_events():
+ return spark.readStream.schema(SCHEMA).json("file:///tmp/cdc_demo/events")
+
+# Declare the target streaming table that Auto CDC maintains.
+dp.create_streaming_table("customers")
+
+# Apply the change events to the target.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+ except_column_list=["op"],
+ stored_as_scd_type=1,
+)
+```
+
+Write the first batch of change events, inserting two customers:
+
+```bash
+mkdir -p /tmp/cdc_demo/events
+cat > /tmp/cdc_demo/events/batch1.json <<'EOF'
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline:
+
+```bash
+spark-pipelines run
+```
+
+`customers` now holds both rows, with the `op` column excluded:
+
+| id | name | version |
+|----|-------|---------|
+| 1 | alice | 1 |
+| 2 | bob | 1 |
+
+Now add a second batch. It updates `id 1`, deletes `id 2`, inserts `id 3`, and ends with a **late duplicate** of the original `id 1` event, which is what a re-delivering source might send:
+
+```bash
+cat > /tmp/cdc_demo/events/batch2.json <<'EOF'
+{"id": 1, "name": "alicia", "version": 2, "op": "UPSERT"}
+{"id": 2, "name": "bob", "version": 2, "op": "DELETE"}
+{"id": 3, "name": "carol", "version": 1, "op": "UPSERT"}
+{"id": 1, "name": "alice", "version": 1, "op": "UPSERT"}
+EOF
+```
+
+Run the pipeline again. Because `customers` is a streaming table, this run processes only the new file:
+
+```bash
+spark-pipelines run
+```
+
+| id | name | version |
+|----|--------|---------|
+| 1 | alicia | 2 |
+| 3 | carol | 1 |
+
+`alice` became `alicia`, `bob` is gone, and `carol` was inserted. The late `alice` event at version 1 did not resurrect the old name: version 1 is below the version 2 already recorded for that key, so Auto CDC discarded it. Had the pipeline applied events in arrival order, `id 1` would have wrongly reverted to `alice`.
+
+### How-Tos
+
+#### Handling deletes
+
+Change feeds usually mark deletes with an operation column or a tombstone flag rather than removing the row. Give Auto CDC a boolean expression that identifies delete events with `apply_as_deletes` (Python) or `APPLY AS DELETE WHEN` (SQL):
+
+```python
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ apply_as_deletes="op = 'DELETE'",
+)
+```
+
+When an event matches the delete condition, the row for its key is removed from the target. If you don't supply a delete condition, every event is treated as an insert or update.
+
+#### Selecting which columns land in the target
+
+CDC feeds often carry metadata columns (the operation type, a timestamp, source offsets) that you don't want in the target table. Use `except_column_list` / `COLUMNS * EXCEPT` to drop them, or `column_list` / `COLUMNS` to name exactly the columns to keep. The two options are mutually exclusive.
+
+```python
+# Keep everything except the operation column.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ except_column_list=["op"],
+)
+
+# Or keep only an explicit set of columns.
+dp.create_auto_cdc_flow(
+ target="customers",
+ source="cdc_events",
+ keys=["id"],
+ sequence_by="version",
+ column_list=["id", "name"],
+)
+```
+
+#### Handling out-of-order and duplicate events
+
+You don't need to sort or de-duplicate the source. The target holds only the current state of each key, so a late event whose sequence value is older than what has already been applied for its key is discarded, and a re-delivered event converges to the same result. The end-to-end example above demonstrates both. Choose a `sequence_by` expression that strictly orders changes for a key, such as a monotonically increasing version number or a commit timestamp.
+
+#### Using a composite key
+
+Pass multiple columns to `keys` when a single column doesn't uniquely identify a row:
+
+```python
+dp.create_auto_cdc_flow(
+ target="orders",
+ source="order_events",
+ keys=["region", "order_id"],
+ sequence_by="event_ts",
+)
+```
+
+#### Changing the key set
+
+The set and types of `keys` are part of the flow's persisted state. Changing keys across incremental runs - renaming, swapping, adding, removing, or changing the type of a key column - is not supported and produces undefined results. To change the key set, [fully refresh](#spark-pipelines-run) the target table so it is recomputed from scratch:
+
+```bash
+spark-pipelines run --full-refresh customers
+```
+
+### Auto CDC Considerations
Review Comment:
Requirements, How-Tos, and Considerations restate the same five facts (streaming-table target, streaming source, target format, unqualified identifiers, immutable key set, sequencing uniqueness); Considerations is close to a superset of Requirements. That triplication is what let the `sequence_by` claim diverge between line 576 and lines 630 / 868, and it will keep happening. Collapsing this list into cross-references -- or dropping Requirements in favor of it -- would cut length with no loss.
At 354 lines this is now the largest section in a guide whose other feature sections run 10-30 lines.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58569][SDP][DOCS] Add documentation for Auto CDC (SCD Type 1) [spark]
Posted by "suhuruli (via GitHub)" <gi...@apache.org>.
suhuruli commented on code in PR #57149:
URL: https://github.com/apache/spark/pull/57149#discussion_r3755382152
##########
docs/declarative-pipelines-programming-guide.md:
##########
@@ -517,6 +517,360 @@ AS INSERT INTO customers_us
SELECT * FROM STREAM(customers_us_east);
```
+## Change Data Capture (CDC) with Auto CDC
+
+Many source systems emit a stream of *change events* rather than a snapshot of the current data: each record describes an insert, update, or delete to a row, identified by a key. Applying these events correctly to a target table by hand is tricky. You have to match events to existing rows, apply them in the right order, and handle out-of-order and duplicate events without corrupting the table.
+
+**Auto CDC** does this for you. You point it at a source of change events and tell it how to identify and order them, and SDP maintains a target streaming table that always reflects the latest state for each key.
+
+### Keys and sequencing
+
+Auto CDC needs two things from you to make sense of a change feed:
+
+- The **keys** are the columns that identify a row across events. Events sharing a key describe the same logical row over time. In a customer feed, that is usually the customer id.
+- The **sequencing expression** says what order the events for a key happened in. Its value for an event is that event's **sequence value**, and Auto CDC treats the highest sequence value it has seen for a key as the most recent state. Change feeds normally carry something suitable already: a monotonically increasing version or commit number, or a commit timestamp.
+
+Sequence values matter because a change feed does not have to arrive in order. Sequencing is what lets Auto CDC recognize that an event it just received is older than what it already applied, and place it correctly, rather than letting arrival order corrupt the table.
+
+### What Auto CDC does
+
+Given a stream of change events, Auto CDC keeps the target table in sync with the source:
+
+- **Inserts and updates** - For each key, the event with the highest sequence value wins. If no row exists for the key, it's inserted; if one exists, it's overwritten with the latest values.
+- **Deletes** - Events that match a delete condition you supply remove the corresponding row from the target.
+- **Out-of-order and duplicate events** - Events don't have to arrive in order, and you don't need to de-duplicate the source. An event whose sequence value is older than the state already applied for its key is discarded, and a re-delivered event converges to the same result.
+
+This behavior implements **Slowly Changing Dimensions (SCD) Type 1**: the target keeps only the current version of each row, with no history of prior values. SCD Type 1 is the only mode currently supported.
Review Comment:
Updated per your suggestion. All three spots now scope rather than deny:
- Concept: "This section covers SCD Type 1... SCD Type 2 is also supported; SPARK-58570 tracks documenting it."
- `stored_as_scd_type` row: "Pass `1` for the Type 1 behavior described here. Type 2 is also accepted; see SPARK-58570."
- `STORED AS SCD TYPE 1`: "use `1` for the Type 1 behavior described here."
This keeps the PR scoped to Type 1 without the guide claiming Type 2 does not exist. Thanks for pushing on it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org