Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# Changelog

## Unreleased

### Breaking Changes

- **`StreamingClient.write_dlo_deltas` and `write_dmo_deltas` require a `dedup_order` keyword argument.**

`dedup_order` is an ordered list of `{"column", "direction", "partition"}` entries (`partition` optional) that decides which row wins when several rows in a micro-batch share a target key. The SDK checks the shape and raises `ValueError` before the stream starts.

**Migration:** Add `dedup_order` to each call. `SOURCE_RECORD_STANDARD` (from `datacustomcode.io.dedup_order`) keeps the latest version of each source record and prefers UPSERT over DELETE; pass `[]` to fail the batch whenever two different rows share a key.

```python
# Before
client.write_dlo_deltas("Output__dll", df)

# After
from datacustomcode.io.dedup_order import SOURCE_RECORD_STANDARD

client.write_dlo_deltas("Output__dll", df, dedup_order=SOURCE_RECORD_STANDARD)
```

### Added

- **`datacustomcode.io.dedup_order`** – `SOURCE_RECORD_BY_LATEST_COMMIT_VERSION`, `SOURCE_RECORD_UPSERT_OVER_DELETE` and `SOURCE_RECORD_STANDARD` entries to start a `dedup_order` from.

## 7.0.0

### Breaking Changes
Expand Down
28 changes: 23 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ For a batch transform, use `Client`. You should only need the following methods:
For a streaming (delta) transform, use `StreamingClient`, which exposes the streaming counterparts:
* `read_dlo_deltas()` – Read the streaming change feed (deltas) of a Data Lake Object as a streaming DataFrame.
* `read_dmo_deltas()` – Read the streaming change feed (deltas) of a Data Model Object as a streaming DataFrame.
* `write_dlo_deltas(name, spark_dataframe)` – Write a streaming DataFrame of deltas to a Data Lake Object; returns the started `StreamingQuery`
* `write_dmo_deltas(name, spark_dataframe)` – Write a streaming DataFrame of deltas to a Data Model Object; returns the started `StreamingQuery`
* `write_dlo_deltas(name, spark_dataframe, dedup_order=...)` – Write a streaming DataFrame of deltas to a Data Lake Object; returns the started `StreamingQuery`
* `write_dmo_deltas(name, spark_dataframe, dedup_order=...)` – Write a streaming DataFrame of deltas to a Data Model Object; returns the started `StreamingQuery`

`find_file_path`, `llm_gateway_generate_text`, and `einstein_predict` are available on both clients.

Expand Down Expand Up @@ -206,6 +206,7 @@ Streaming BYOC transforms process a Data Lake Object's Change Data Feed continuo
from pyspark.sql.functions import col, upper

from datacustomcode import StreamingClient
from datacustomcode.io.dedup_order import SOURCE_RECORD_STANDARD

client = StreamingClient()

Expand All @@ -218,8 +219,10 @@ 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)
# choose the target table and how to pick one row per key (dedup_order).
query = client.write_dlo_deltas(
"Output__dll", transformed, dedup_order=SOURCE_RECORD_STANDARD
)
query.awaitTermination()
```

Expand All @@ -228,10 +231,25 @@ 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()
```

`dedup_order` is required on both write methods. It is an ordered list of entries `{"column", "direction", "partition"}`; each entry narrows, within its partition, to the rows tied for best 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.

Notes:

- These methods only run inside the Data Cloud streaming (`DELTA_SYNC`) runtime. Locally (`datacustomcode run`) they raise `NotImplementedError`, since there is no change feed to stream.
Expand Down
39 changes: 35 additions & 4 deletions src/datacustomcode/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@
from datacustomcode.config import config
from datacustomcode.einstein_predictions_config import spark_einstein_predictions_config
from datacustomcode.file.path.default import DefaultFindFilePath
from datacustomcode.io.dedup_order import validate_dedup_order
from datacustomcode.io.reader.base import BaseDataCloudReader
from datacustomcode.llm_gateway_config import spark_llm_gateway_config
from datacustomcode.named_credential_config import spark_named_credential_config
from datacustomcode.spark.default import DefaultSparkSessionProvider

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from pathlib import Path

from pyspark.sql import (
Expand Down Expand Up @@ -708,7 +710,12 @@ def read_dmo_deltas(self) -> PySparkDataFrame:
return self._reader.read_dmo_deltas() # type: ignore[no-any-return]

def write_dlo_deltas(
self, name: str, dataframe: PySparkDataFrame, **kwargs
self,
name: str,
dataframe: PySparkDataFrame,
*,
dedup_order: Sequence[Mapping[str, str]],
**kwargs,
) -> StreamingQuery:
"""Write a streaming DataFrame of deltas to a DLO in Data Cloud.

Expand All @@ -719,15 +726,32 @@ def write_dlo_deltas(
Args:
name: The name of the DLO to write to.
dataframe: The streaming PySpark DataFrame to write.
dedup_order: Entries ``{"column", "direction", "partition"}`` that
pick one row per target key. ``partition`` is optional, and
entries with it must come first. Start with
``*SOURCE_RECORD_STANDARD`` from
:mod:`datacustomcode.io.dedup_order`. Pass ``[]`` to fail the
batch when two different rows share a key.

Returns:
The started ``StreamingQuery``.

Raises:
ValueError: If ``dedup_order`` is malformed.
"""
self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DMO)
return self._writer.write_dlo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return]
entries = validate_dedup_order(dedup_order)
return self._writer.write_dlo_deltas( # type: ignore[no-any-return]
name, dataframe, dedup_order=entries, **kwargs
)

def write_dmo_deltas(
self, name: str, dataframe: PySparkDataFrame, **kwargs
self,
name: str,
dataframe: PySparkDataFrame,
*,
dedup_order: Sequence[Mapping[str, str]],
**kwargs,
) -> StreamingQuery:
"""Write a streaming DataFrame of deltas to a DMO in Data Cloud.

Expand All @@ -738,12 +762,19 @@ def write_dmo_deltas(
Args:
name: The name of the DMO to write to.
dataframe: The streaming PySpark DataFrame to write.
dedup_order: See :meth:`write_dlo_deltas`.

Returns:
The started ``StreamingQuery``.

Raises:
ValueError: If ``dedup_order`` is malformed.
"""
self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DLO)
return self._writer.write_dmo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return]
entries = validate_dedup_order(dedup_order)
return self._writer.write_dmo_deltas( # type: ignore[no-any-return]
name, dataframe, dedup_order=entries, **kwargs
)

def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None:
"""Write a PySpark DataFrame to a DLO in Data Cloud automatically picking
Expand Down
4 changes: 4 additions & 0 deletions src/datacustomcode/io/cdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,17 @@
COMMIT_VERSION: Final = "_commit_version"
COMMIT_TIMESTAMP: Final = "_commit_timestamp"
MERGE_RECORD_TYPE: Final = MERGE_RECORD_TYPE_COLUMN
SOURCE_TABLE_NAME: Final = "_source_table_name"
SOURCE_RECORD_KEY: Final = "_source_record_key"

CDF_METADATA_COLUMNS: Final = (COMMIT_VERSION, COMMIT_TIMESTAMP, MERGE_RECORD_TYPE)

__all__ = [
"COMMIT_VERSION",
"COMMIT_TIMESTAMP",
"MERGE_RECORD_TYPE",
"SOURCE_TABLE_NAME",
"SOURCE_RECORD_KEY",
"CDF_METADATA_COLUMNS",
"MergeRecordType",
]
129 changes: 129 additions & 0 deletions src/datacustomcode/io/dedup_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Copyright (c) 2025, Salesforce, Inc.
# SPDX-License-Identifier: Apache-2
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""``dedup_order`` entries for the streaming ``write_*_deltas`` methods.

Each entry is ``{"column", "direction", "partition"}``. Entries run in order and
each narrows, within its partition, to the rows tied for best on its column. An
entry without ``partition`` runs per target primary key. Entries with
``partition`` must come before entries without it.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
import re
from typing import Final

from datacustomcode.io import cdf

DIRECTIONS: Final = ("asc", "desc")

_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,254}")

_ENTRY_KEYS: Final = frozenset({"column", "direction", "partition"})

DedupOrderEntry = dict[str, str]

SOURCE_RECORD_BY_LATEST_COMMIT_VERSION: Final[DedupOrderEntry] = {
"column": cdf.COMMIT_VERSION,
"direction": "desc",
"partition": cdf.SOURCE_RECORD_KEY,
}

# "UPSERT" sorts after "DELETE", so descending puts UPSERT first.
SOURCE_RECORD_UPSERT_OVER_DELETE: Final[DedupOrderEntry] = {
"column": cdf.MERGE_RECORD_TYPE,
"direction": "desc",
"partition": cdf.SOURCE_RECORD_KEY,
}

SOURCE_RECORD_STANDARD: Final = (
SOURCE_RECORD_BY_LATEST_COMMIT_VERSION,
SOURCE_RECORD_UPSERT_OVER_DELETE,
)


def _validate_entry(index: int, entry: object) -> DedupOrderEntry:
where = f"dedup_order[{index}]"
if not isinstance(entry, Mapping):
raise ValueError(f"{where} must be a dict, got {type(entry).__name__}.")

unknown = sorted(str(key) for key in entry.keys() - _ENTRY_KEYS)
if unknown:
raise ValueError(
f"{where} has unknown key(s) {unknown}; "
"entries take 'column', 'direction' and optional 'partition'."
)

for key in ("column", "direction"):
if key not in entry:
raise ValueError(f"{where} is missing required key '{key}'.")

for key in ("column", "partition"):
if key in entry and not (
isinstance(entry[key], str) and _NAME.fullmatch(entry[key])
):
raise ValueError(
f"{where}['{key}'] must be a plain column name: letters, digits "
"and underscores, not starting with a digit."
)

if entry["direction"] not in DIRECTIONS:
raise ValueError(
f"{where}['direction'] must be one of {list(DIRECTIONS)}, "
f"got {entry['direction']!r}."
)

return dict(entry)


def validate_dedup_order(
dedup_order: Sequence[Mapping[str, str]],
) -> list[DedupOrderEntry]:
"""Check the shape of ``dedup_order`` and return it as a list of plain dicts.

Raises:
ValueError: If ``dedup_order`` or any of its entries is malformed.
"""
if isinstance(dedup_order, (str, bytes, Mapping)) or not isinstance(
dedup_order, Sequence
):
raise ValueError(
"dedup_order must be a list of entries; pass [] to fail the batch "
f"when two different rows share a key. Got {type(dedup_order).__name__}."
)

entries = [_validate_entry(i, entry) for i, entry in enumerate(dedup_order)]

first_unpartitioned = next(
(i for i, entry in enumerate(entries) if "partition" not in entry), None
)
if first_unpartitioned is not None:
late = next(
(
i
for i, entry in enumerate(entries)
if i > first_unpartitioned and "partition" in entry
),
None,
)
if late is not None:
raise ValueError(
f"dedup_order[{late}] has a 'partition' but follows "
f"dedup_order[{first_unpartitioned}], which has none. "
"Entries with 'partition' must come before entries without."
)

return entries
18 changes: 16 additions & 2 deletions src/datacustomcode/io/writer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from datacustomcode.io.base import BaseDataAccessLayer

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence

from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession
from pyspark.sql.streaming import StreamingQuery

Expand Down Expand Up @@ -72,7 +74,11 @@ def auto_write_to_dmo(self, name: str, dataframe: PySparkDataFrame) -> None:
raise NotImplementedError

def write_dlo_deltas(
self, name: str, dataframe: PySparkDataFrame
self,
name: str,
dataframe: PySparkDataFrame,
*,
dedup_order: Sequence[Mapping[str, str]],
) -> StreamingQuery:
"""Write a streaming DataFrame of deltas to a Data Lake Object.

Expand All @@ -88,6 +94,8 @@ def write_dlo_deltas(
name: Target Data Lake Object name.
dataframe: Streaming PySpark DataFrame produced from a
``read_dlo_deltas`` source.
dedup_order: Validated ``dedup_order`` entries; see
:mod:`datacustomcode.io.dedup_order`.

Returns:
The started ``StreamingQuery``; the caller drives its lifecycle
Expand All @@ -104,7 +112,11 @@ def write_dlo_deltas(
)

def write_dmo_deltas(
self, name: str, dataframe: PySparkDataFrame
self,
name: str,
dataframe: PySparkDataFrame,
*,
dedup_order: Sequence[Mapping[str, str]],
) -> StreamingQuery:
"""Write a streaming DataFrame of deltas to a Data Model Object.

Expand All @@ -120,6 +132,8 @@ def write_dmo_deltas(
name: Target Data Model Object name.
dataframe: Streaming PySpark DataFrame produced from a
``read_dmo_deltas`` source.
dedup_order: Validated ``dedup_order`` entries; see
:mod:`datacustomcode.io.dedup_order`.

Returns:
The started ``StreamingQuery``; the caller drives its lifecycle
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
StreamingClient,
get_run_mode,
)
from datacustomcode.io.dedup_order import SOURCE_RECORD_STANDARD


def main():
Expand All @@ -41,7 +42,9 @@ def main():

# Start the streaming write. write_dlo_deltas returns the StreamingQuery;
# the trigger and checkpoint location are provided by the runtime.
query = client.write_dlo_deltas(target_dlo, transformed)
query = client.write_dlo_deltas(
target_dlo, transformed, dedup_order=SOURCE_RECORD_STANDARD
)

# Drive the query's lifecycle. In the streaming runtime this blocks until
# the job is stopped by the platform.
Expand Down
Loading
Loading