diff --git a/README.md b/README.md index a2951cf..c6e2cdb 100644 --- a/README.md +++ b/README.md @@ -449,3 +449,4 @@ If you're using OAuth Tokens authentication, the initial configure will retrieve - [Troubleshooting](./docs/troubleshooting.md) - [Contributing](./CONTRIBUTING.md) +- [Streaming CDF](./docs/streaming_cdf.md) diff --git a/docs/streaming_cdf.md b/docs/streaming_cdf.md index f781454..0b7d003 100644 --- a/docs/streaming_cdf.md +++ b/docs/streaming_cdf.md @@ -1,12 +1,228 @@ -### Streaming (delta) transforms +# Streaming (delta) Transforms -Streaming BYOC transforms process a Data Lake Object's Change Data Feed continuously instead of reading a bounded snapshot. Use a `StreamingClient` and its `*_deltas` methods in place of the batch `Client` read/write methods: +Streaming BYOC transforms process a Data Lake Object's Change Data Feed continuously instead of reading a bounded snapshot. +This is meant for data engineers who already work with streaming and change data, and who are comfortable with +* Structured Streaming basics: microbatches, stateless versus stateful operations, and why some DataFrame operations (window functions, sorting) aren't allowed on a stream. +* Change feeds: preimages and postimages, deletes, and several changes to one key in a short span. +* Data drift: source schemas and data can change while a stream runs, and your transform has to tolerate that. +* Merge semantics: how a MERGE treats an upsert and a delete, and why two rows for one key in a batch is an error. + +## What you Read +Streaming exposes additional columns per row of changed data to give you fine-grained control over the handling of the changes. +These columns are described below +| Column Name | Values | Notes | +| :--- | :--- | :--- | +| _change_type | insert, update_preimage, update_postimage, delete | | +| _commit_version | long | per-source DLO | +| _commit_timestamp | timestamp | when the commit landed in the source DLO, not exact | +| _source_table_name | string | the source DLO for the row | +| _source_record_key | string, opaque | An opaque string that identifies a source row. It is specific to each source DLO: two DLOs never share a value, even if their primary keys and row contents are identical. Rows with the same _source_record_key are versions of one source row. This can be a helpful partition for deduplication, for example to order by _commit_version. | + +## What you Write +The DataFrame you write must have: + +* _merge_record_type: UPSERT or DELETE. +* The target DLO's PK columns. + +The stream fails at start if any of these is missing. Columns that aren't in the target DLO, including every system column, aren't written. You must also drop the _change_type column. This is provided in the source only to help derive _merge_record_type. + +### Beware of Filtering Mutable Columns +Remember that streaming transforms operate on change data feeds. If you filter the rows based on a column that changed before deciding the _merge_record_type, +you may lose deletes and have stale data in your output. A safe rule of thumb is to filter only on immutable columns. For mutable columns, treat update_preimage +that matches a filter as a delete and update_postimage that matches as an upsert. + +```python +def to_merge_records(changes: DataFrame) -> DataFrame: + # Deletes and preimages become DELETE, everything else UPSERT + removed = F.col(cdf.CHANGE_TYPE).isin(cdf.ChangeType.DELETE, cdf.ChangeType.UPDATE_PREIMAGE) + return changes.withColumn( + cdf.MERGE_RECORD_TYPE, + F.when(removed, F.lit(cdf.MergeRecordType.DELETE)).otherwise(F.lit(cdf.MergeRecordType.UPSERT)), + ).drop(cdf.CHANGE_TYPE) + +``` +### Deduplication of Row Per-Microbatch +The written dataframe cannot contain two rows with the same primary key. The SDK includes a standard two-step deduplication pass that first picks the row with +the latest commit version and then picks upserts over deletes. Depending on the shape of your data, this may not be enough to pick a single row. Deduplication is configured by setting the dedup_order parameters in write_*_deltas methods. The parameter is an ordered list of entries `{"column", "direction", "partition"}`. Each entry narrows, within its partition, to the rows tied on its column. `partition` is optional and names any column in your DataFrame; an entry without it runs per target primary key. Entries with `partition` must come before entries without it. If more than one row is left for a key after the last entry, the batch fails. + +`SOURCE_RECORD_STANDARD` provides two dedup_order entries partitioned by `_source_record_key`: keep the latest by `_commit_version`, then prefer UPSERT over DELETE. Add your own entries after it to break ties across source records. + +```python +dedup_order=[ + *SOURCE_RECORD_STANDARD, + {"column": "lead_score__c", "direction": "desc"}, +] +``` + +Pass `dedup_order=[]` to fail the batch whenever two different rows share a key. + +#### Scenario 1 +Below is a concrete example based on lead scoring data from two source DLOs. In this case the script is reading the raw CDF and writing it by deriving the _merge_record_type as shown above. + +feed from read_dlo_deltas +| row_number | _source_table_name | _source_record_key | _change_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 1 | crm_contact__dll | c-100 | insert | 1 | 10:00:00 | jane@salesforce.com | 90 | +| 2 | crm_contact__dll | c-100| update_preimage| 2 | 10:05:00 | jane@salesforce.com | 90 | +| 3 | crm_contact__dll | c-100 | update_postimage | 2 | 10:05:00 | jane@salesforce.com | 40 | +| 4 | web_signup__dll | w-555 | insert | 1 | 10:02:00 | jane@salesforce.com | 60 | + +Dataframe sent to write_dlo_deltas. preimage is set to delete and every other row is sent as an upsert +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 1 | crm_contact__dll | c-100 | upsert | 1 | 10:00:00 | jane@salesforce.com | 90 | +| 2 | crm_contact__dll | c-100| delete | 2 | 10:05:00 | jane@salesforce.com | 90 | +| 3 | crm_contact__dll | c-100 | upsert | 2 | 10:05:00 | jane@salesforce.com | 40 | +| 4 | web_signup__dll | w-555 | upsert | 1 | 10:02:00 | jane@salesforce.com | 60 | + +After SOURCE_RECORD_STANDARD dedup step 1 the following rows are left based on highest commit version per source record key +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 2 | crm_contact__dll | c-100| delete | 2 | 10:05:00 | jane@salesforce.com | 90 | +| 3 | crm_contact__dll | c-100 | upsert | 2 | 10:05:00 | jane@salesforce.com | 40 | +| 4 | web_signup__dll | w-555 | upsert | 1 | 10:02:00 | jane@salesforce.com | 60 | + +After SOURCE_RECORD_STANDARD dedup step 2 which picks upsert over delete, only 2 rows remain +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 3 | crm_contact__dll | c-100 | upsert | 2 | 10:05:00 | jane@salesforce.com | 40 | +| 4 | web_signup__dll | w-555 | upsert | 1 | 10:02:00 | jane@salesforce.com | 60 | + +For the final selection, a dedup_order of [{"column": "lead_score__c", "direction": "desc"}] picks the winner. +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 4 | web_signup__dll | w-555 | upsert | 1 | 10:02:00 | jane@salesforce.com | 60 | + +#### Scenario 2 +Using the same raw data from scenario 1, but this adds a filter on the lead score before writing. +`df.filter(F.col("lead_score__c") >= 70)` + +Dataframe sent to write_dlo_deltas. preimage is set to delete and every other row is sent as an upsert +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 1 | crm_contact__dll | c-100 | upsert | 1 | 10:00:00 | jane@salesforce.com | 90 | +| 2 | crm_contact__dll | c-100| delete | 2 | 10:05:00 | jane@salesforce.com | 90 | + +After SOURCE_RECORD_STANDARD dedup step 1 only 1 row is left based on highest commit version per source record key. +This results in a delete of the record from the target which is the desired behavior since the CRM current score is 40 and web's is 60, neither of which meet the filtered threshold. +| row_number | _source_table_name | _source_record_key | _merge_record_type | _commit_version | _commit_timestamp | email | lead_score__c | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| 2 | crm_contact__dll | c-100| delete | 2 | 10:05:00 | jane@salesforce.com | 90 | + +This scenario also illustrates the importance of keeping the preimage rows when filtering on a mutable column. +Had these been filtered out, then only row 1 would have been kept and upserted stale data (lead score of 90) into the target. + +### Reading the dedup conflict message + +When `dedup_order` leaves more than one row for any primary key of the target, the streaming query +fails with a `DedupConflictException`: + +``` +3 primary key(s) for target table 'names_c__dll' still have more than one row after dedupOrder +[_commit_version desc per _source_record_key, _merge_record_type desc per _source_record_key]. +Add or adjust an entry that orders the differing columns. Conflicts by shape (up to 5): + - duplicate keys=3, differing columns=[name__c] +``` + +#### How the message is built + +1. Apply the `dedup_order` entries. `rank()` is used, so rows that tie on every ordered column + all survive. +2. Find the primary keys that still have more than one surviving row. These are the "tied keys". + Their count is the number in the first line. +3. For each tied key, look only at its tied rows and compute two things: + - **source tables**: the distinct `_source_table_name` values. That column only exists for DMO + sources; for a DLO source there are none and the `source tables=` part is left out. + - **differing columns**: every column that has more than one distinct value among those rows, + except the primary-key columns and the bookkeeping columns (`_commit_version`, + `_commit_timestamp`, `_source_table_name`, `_source_record_key`). `[]` means the rows are + identical. + The pair (source tables, differing columns) is the key's **shape**. +4. Group the tied keys by shape. Each group is one line: `duplicate keys=N` is how many tied keys have that + shape. Lines are sorted by `keys`, largest first, and at most 5 are printed. + +`duplicate keys=N` counts primary keys. It is not a count of rows or duplicates. + +#### Examples + +Target primary key is `id__c`. The tables show only the rows that survived `dedup_order` (the tied +rows). Columns: `id__c`, `name__c`, `email__c`. + +#### One shape: `duplicate keys=3` + +| id__c | name__c | email__c | +|---|---|---| +| 1 | A | a@x | +| 1 | A_dup | a@x | +| 2 | B | b@x | +| 2 | B_dup | b@x | +| 3 | C | c@x | +| 3 | C_dup | c@x | + +- Tied keys: 1, 2, 3, so the first line says `3 primary key(s)`. +- Only `name__c` differs for each of them, so they all have the same shape. + +``` +- duplicate keys=3, differing columns=[name__c] +``` + +Here that happens to be 3 keys with 2 rows each. Change key 1 to have 3 tied rows (`A`, `A_dup`, +`A_dup2`) and the output is identical, because rows are never counted. + +#### Several shapes + +| id__c | name__c | email__c | +|---|---|---| +| 1 | A | a@x | +| 1 | A_dup | a@x | +| 2 | B | b@x | +| 2 | B_dup | b@x | +| 3 | C | c@x | +| 3 | C_dup | c@x | +| 4 | D | d@x | +| 4 | D2 | d2@x | +| 5 | E | e@x | +| 5 | E | e@x | + +``` +5 primary key(s) ... still have more than one row ... +Conflicts by shape (up to 5): + - duplicate keys=3, differing columns=[name__c] + - duplicate keys=1, differing columns=[email__c, name__c] + - duplicate keys=1, differing columns=[] +``` + +- Keys 1-3 differ only in `name__c`: `duplicate keys=3`. +- Key 4 differs in `name__c` and `email__c`: its own shape. +- Key 5 has identical rows: `differing columns=[]`. Identical rows still conflict, because any + second row for a key counts. + +#### DMO source + +If the rows come from a DMO, the tied rows may come from different source tables, and the line +names them: + +``` +- duplicate keys=2, source tables=[orders_a__dll, orders_b__dll], differing columns=[status__c] +``` + +Two primary keys each have rows from both `orders_a__dll` and `orders_b__dll`, and they disagree +on `status__c`. + +### What to do with it + +`differing columns` names the columns you can order on. Add an entry for one of them, for example +`{"column": "name__c", "direction": "desc"}`, so one row per key wins. If it is `[]`, the rows are +identical and no column can break the tie; fix the upstream duplicate instead. + +## Example +Use a `StreamingClient` and its `*_deltas` methods in place of the batch `Client` read/write methods: ```python from pyspark.sql.functions import col, upper from datacustomcode import StreamingClient - +from datacustomcode.io.dedup_order import SOURCE_RECORD_STANDARD client = StreamingClient() # read_dlo_deltas returns a *streaming* DataFrame over the change feed. @@ -19,7 +235,7 @@ transformed = deltas.withColumn("description__c", upper(col("description__c"))) # write_dlo_deltas starts a streaming query and returns the StreamingQuery. # The runtime owns the trigger and checkpoint location; you # choose only the target table. -query = client.write_dlo_deltas("Output__dll", transformed) +query = client.write_dlo_deltas("Output__dll", transformed, dedup_order=SOURCE_RECORD_STANDARD) query.awaitTermination() ``` @@ -28,7 +244,7 @@ A streaming transform can also read and write Data Model Objects with `read_dmo_ ```python deltas = client.read_dmo_deltas() transformed = deltas.withColumn("description__c", upper(col("description__c"))) -query = client.write_dmo_deltas("Output__dlm", transformed) +query = client.write_dmo_deltas("Output__dlm", transformed, dedup_order=SOURCE_RECORD_STANDARD) query.awaitTermination() ```