From b0c82581b12fcd2980ad1895fe803973ad00bf34 Mon Sep 17 00:00:00 2001 From: Mark DeLaVergne Date: Fri, 20 Nov 2026 11:25:57 -0500 Subject: [PATCH 1/3] Implement dedup_order for streaming --- CHANGELOG.md | 24 ++++ README.md | 28 +++- src/datacustomcode/client.py | 39 +++++- src/datacustomcode/io/cdf.py | 4 + src/datacustomcode/io/dedup_order.py | 129 ++++++++++++++++++ src/datacustomcode/io/writer/base.py | 18 ++- .../examples/streaming_deltas/entrypoint.py | 5 +- tests/io/test_dedup_order.py | 105 ++++++++++++++ tests/io/writer/test_print.py | 4 +- tests/test_client.py | 82 +++++++++-- 10 files changed, 414 insertions(+), 24 deletions(-) create mode 100644 src/datacustomcode/io/dedup_order.py create mode 100644 tests/io/test_dedup_order.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d43038fa..1ed557f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index aa979faf..b2f94c63 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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() @@ -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() ``` @@ -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. diff --git a/src/datacustomcode/client.py b/src/datacustomcode/client.py index 69f7ea1f..318d4058 100644 --- a/src/datacustomcode/client.py +++ b/src/datacustomcode/client.py @@ -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 ( @@ -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. @@ -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. @@ -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 diff --git a/src/datacustomcode/io/cdf.py b/src/datacustomcode/io/cdf.py index cd049be2..3f66c550 100644 --- a/src/datacustomcode/io/cdf.py +++ b/src/datacustomcode/io/cdf.py @@ -22,6 +22,8 @@ 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) @@ -29,6 +31,8 @@ "COMMIT_VERSION", "COMMIT_TIMESTAMP", "MERGE_RECORD_TYPE", + "SOURCE_TABLE_NAME", + "SOURCE_RECORD_KEY", "CDF_METADATA_COLUMNS", "MergeRecordType", ] diff --git a/src/datacustomcode/io/dedup_order.py b/src/datacustomcode/io/dedup_order.py new file mode 100644 index 00000000..d07c79fd --- /dev/null +++ b/src/datacustomcode/io/dedup_order.py @@ -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 + +import re +from collections.abc import Mapping, Sequence +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 diff --git a/src/datacustomcode/io/writer/base.py b/src/datacustomcode/io/writer/base.py index 56b89f9f..1718da74 100644 --- a/src/datacustomcode/io/writer/base.py +++ b/src/datacustomcode/io/writer/base.py @@ -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 @@ -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. @@ -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 @@ -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. @@ -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 diff --git a/src/datacustomcode/templates/script/examples/streaming_deltas/entrypoint.py b/src/datacustomcode/templates/script/examples/streaming_deltas/entrypoint.py index abe7981c..b0c2dd07 100644 --- a/src/datacustomcode/templates/script/examples/streaming_deltas/entrypoint.py +++ b/src/datacustomcode/templates/script/examples/streaming_deltas/entrypoint.py @@ -27,6 +27,7 @@ StreamingClient, get_run_mode, ) +from datacustomcode.io.dedup_order import SOURCE_RECORD_STANDARD def main(): @@ -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. diff --git a/tests/io/test_dedup_order.py b/tests/io/test_dedup_order.py new file mode 100644 index 00000000..e63802a8 --- /dev/null +++ b/tests/io/test_dedup_order.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import pytest + +from datacustomcode.io.dedup_order import ( + SOURCE_RECORD_BY_LATEST_COMMIT_VERSION, + SOURCE_RECORD_STANDARD, + SOURCE_RECORD_UPSERT_OVER_DELETE, + validate_dedup_order, +) + +SCORE = {"column": "lead_score__c", "direction": "desc"} + + +def test_empty_order_is_valid(): + assert validate_dedup_order([]) == [] + + +def test_constants_expand_to_plain_entries(): + assert SOURCE_RECORD_BY_LATEST_COMMIT_VERSION == { + "column": "_commit_version", + "direction": "desc", + "partition": "_source_record_key", + } + assert SOURCE_RECORD_UPSERT_OVER_DELETE == { + "column": "_merge_record_type", + "direction": "desc", + "partition": "_source_record_key", + } + assert SOURCE_RECORD_STANDARD == ( + SOURCE_RECORD_BY_LATEST_COMMIT_VERSION, + SOURCE_RECORD_UPSERT_OVER_DELETE, + ) + + +def test_defaults_then_customer_entry_is_valid(): + result = validate_dedup_order([*SOURCE_RECORD_STANDARD, SCORE]) + + assert result == [*SOURCE_RECORD_STANDARD, SCORE] + + +def test_accepts_tuple_and_returns_copies(): + result = validate_dedup_order(SOURCE_RECORD_STANDARD) + + assert result == list(SOURCE_RECORD_STANDARD) + result[0]["direction"] = "asc" + assert SOURCE_RECORD_BY_LATEST_COMMIT_VERSION["direction"] == "desc" + + +def test_partitioned_entries_may_use_any_column(): + entry = {"column": "updated_at__c", "direction": "asc", "partition": "region__c"} + + assert validate_dedup_order([entry]) == [entry] + + +@pytest.mark.parametrize("value", [None, "desc", b"x", {"column": "a"}, 3]) +def test_non_sequence_is_rejected(value): + with pytest.raises(ValueError, match="must be a list"): + validate_dedup_order(value) + + +def test_entry_must_be_a_dict(): + with pytest.raises(ValueError, match=r"dedup_order\[1\] must be a dict"): + validate_dedup_order([SCORE, "lead_score__c"]) + + +@pytest.mark.parametrize("missing", ["column", "direction"]) +def test_required_keys(missing): + entry = {k: v for k, v in SCORE.items() if k != missing} + + with pytest.raises(ValueError, match=f"missing required key '{missing}'"): + validate_dedup_order([entry]) + + +def test_unknown_key_is_rejected(): + with pytest.raises(ValueError, match=r"unknown key\(s\) \['rank'\]"): + validate_dedup_order([{**SCORE, "rank": ["a", "b"]}]) + + +@pytest.mark.parametrize("direction", ["DESC", "ascending", "", None]) +def test_direction_must_be_asc_or_desc(direction): + with pytest.raises(ValueError, match="must be one of"): + validate_dedup_order([{**SCORE, "direction": direction}]) + + +@pytest.mark.parametrize("key", ["column", "partition"]) +@pytest.mark.parametrize("value", ["", None, 1, "a.b", "a b", "1a", "x`y", "a" * 256]) +def test_column_and_partition_must_be_plain_names(key, value): + with pytest.raises(ValueError, match=f"\\['{key}'\\] must be a plain column name"): + validate_dedup_order([{**SCORE, key: value}]) + + +def test_partitioned_entry_after_unpartitioned_is_rejected(): + with pytest.raises( + ValueError, match=r"dedup_order\[1\] has a 'partition' but follows" + ): + validate_dedup_order([SCORE, SOURCE_RECORD_BY_LATEST_COMMIT_VERSION]) + + +def test_unpartitioned_entries_may_repeat_after_partitioned(): + result = validate_dedup_order( + [*SOURCE_RECORD_STANDARD, SCORE, {"column": "email", "direction": "asc"}] + ) + + assert len(result) == 4 diff --git a/tests/io/writer/test_print.py b/tests/io/writer/test_print.py index 258a765a..4c86e22d 100644 --- a/tests/io/writer/test_print.py +++ b/tests/io/writer/test_print.py @@ -62,13 +62,13 @@ def test_write_to_dmo(self, print_writer, mock_dataframe): def test_write_dlo_deltas_not_supported_locally(self, print_writer, mock_dataframe): """Streaming delta writes are not supported by the local writer.""" with pytest.raises(NotImplementedError) as exc_info: - print_writer.write_dlo_deltas("test_dll", mock_dataframe) + print_writer.write_dlo_deltas("test_dll", mock_dataframe, dedup_order=[]) assert "write_dlo_deltas" in str(exc_info.value) def test_write_dmo_deltas_not_supported_locally(self, print_writer, mock_dataframe): """Streaming delta writes are not supported by the local writer.""" with pytest.raises(NotImplementedError) as exc_info: - print_writer.write_dmo_deltas("test_dlm", mock_dataframe) + print_writer.write_dmo_deltas("test_dlm", mock_dataframe, dedup_order=[]) assert "write_dmo_deltas" in str(exc_info.value) def test_config_name(self): diff --git a/tests/test_client.py b/tests/test_client.py index 748c0fc9..e9691c02 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -24,6 +24,11 @@ SparkConfig, ) from datacustomcode.einstein_predictions.types import PredictionType +from datacustomcode.io.dedup_order import ( + SOURCE_RECORD_BY_LATEST_COMMIT_VERSION, + SOURCE_RECORD_STANDARD, + SOURCE_RECORD_UPSERT_OVER_DELETE, +) from datacustomcode.io.reader.base import BaseDataCloudReader from datacustomcode.io.writer.base import BaseDataCloudWriter, WriteMode @@ -416,13 +421,53 @@ def test_write_dlo_deltas(self, reset_client, mock_spark): client = StreamingClient(reader=reader, writer=writer) client._record_dlo_access("some_dlo") - result = client.write_dlo_deltas("test_dlo", mock_df, extra_param=True) + result = client.write_dlo_deltas( + "test_dlo", + mock_df, + dedup_order=[*SOURCE_RECORD_STANDARD, {"column": "a", "direction": "asc"}], + extra_param=True, + ) writer.write_dlo_deltas.assert_called_once_with( - "test_dlo", mock_df, extra_param=True + "test_dlo", + mock_df, + dedup_order=[ + dict(SOURCE_RECORD_BY_LATEST_COMMIT_VERSION), + dict(SOURCE_RECORD_UPSERT_OVER_DELETE), + {"column": "a", "direction": "asc"}, + ], + extra_param=True, ) assert result is mock_query + def test_write_dlo_deltas_requires_dedup_order(self, reset_client, mock_spark): + writer = MagicMock(spec=BaseDataCloudWriter) + client = StreamingClient( + reader=MagicMock(spec=BaseDataCloudReader), writer=writer + ) + + with pytest.raises(TypeError, match="dedup_order"): + client.write_dlo_deltas("test_dlo", MagicMock(spec=DataFrame)) + + writer.write_dlo_deltas.assert_not_called() + + def test_write_dlo_deltas_invalid_dedup_order_raises( + self, reset_client, mock_spark + ): + writer = MagicMock(spec=BaseDataCloudWriter) + client = StreamingClient( + reader=MagicMock(spec=BaseDataCloudReader), writer=writer + ) + + with pytest.raises(ValueError, match="dedup_order"): + client.write_dlo_deltas( + "test_dlo", + MagicMock(spec=DataFrame), + dedup_order=[{"column": "a"}], + ) + + writer.write_dlo_deltas.assert_not_called() + def test_write_dlo_deltas_after_dmo_read_raises_exception( self, reset_client, mock_spark ): @@ -435,7 +480,7 @@ def test_write_dlo_deltas_after_dmo_read_raises_exception( client._record_dmo_access("test_dmo") with pytest.raises(DataCloudAccessLayerException) as exc_info: - client.write_dlo_deltas("test_dlo", mock_df) + client.write_dlo_deltas("test_dlo", mock_df, dedup_order=[]) assert "test_dmo" in str(exc_info.value) writer.write_dlo_deltas.assert_not_called() @@ -450,13 +495,26 @@ def test_write_dmo_deltas(self, reset_client, mock_spark): client = StreamingClient(reader=reader, writer=writer) client._record_dmo_access("some_dmo") - result = client.write_dmo_deltas("test_dmo", mock_df, extra_param=True) + result = client.write_dmo_deltas( + "test_dmo", mock_df, dedup_order=[], extra_param=True + ) writer.write_dmo_deltas.assert_called_once_with( - "test_dmo", mock_df, extra_param=True + "test_dmo", mock_df, dedup_order=[], extra_param=True ) assert result is mock_query + def test_write_dmo_deltas_requires_dedup_order(self, reset_client, mock_spark): + writer = MagicMock(spec=BaseDataCloudWriter) + client = StreamingClient( + reader=MagicMock(spec=BaseDataCloudReader), writer=writer + ) + + with pytest.raises(TypeError, match="dedup_order"): + client.write_dmo_deltas("test_dmo", MagicMock(spec=DataFrame)) + + writer.write_dmo_deltas.assert_not_called() + def test_write_dmo_deltas_after_dlo_read_raises_exception( self, reset_client, mock_spark ): @@ -469,7 +527,7 @@ def test_write_dmo_deltas_after_dlo_read_raises_exception( client._record_dlo_access("test_dlo") with pytest.raises(DataCloudAccessLayerException) as exc_info: - client.write_dmo_deltas("test_dmo", mock_df) + client.write_dmo_deltas("test_dmo", mock_df, dedup_order=[]) assert "test_dlo" in str(exc_info.value) writer.write_dmo_deltas.assert_not_called() @@ -486,10 +544,12 @@ def test_streaming_read_write_flow(self, reset_client, mock_spark): with patch("datacustomcode.client.config") as mock_config: mock_config.streaming_source = "source_dll" df = client.read_dlo_deltas() - client.write_dlo_deltas("target_dll", df) + client.write_dlo_deltas("target_dll", df, dedup_order=[]) reader.read_dlo_deltas.assert_called_once_with() - writer.write_dlo_deltas.assert_called_once_with("target_dll", stream_df) + writer.write_dlo_deltas.assert_called_once_with( + "target_dll", stream_df, dedup_order=[] + ) assert "source_dll" in client._data_layer_history[DataCloudObjectType.DLO] def test_streaming_dmo_read_write_flow(self, reset_client, mock_spark): @@ -504,10 +564,12 @@ def test_streaming_dmo_read_write_flow(self, reset_client, mock_spark): with patch("datacustomcode.client.config") as mock_config: mock_config.streaming_source = "source_dlm" df = client.read_dmo_deltas() - client.write_dmo_deltas("target_dlm", df) + client.write_dmo_deltas("target_dlm", df, dedup_order=[]) reader.read_dmo_deltas.assert_called_once_with() - writer.write_dmo_deltas.assert_called_once_with("target_dlm", stream_df) + writer.write_dmo_deltas.assert_called_once_with( + "target_dlm", stream_df, dedup_order=[] + ) assert "source_dlm" in client._data_layer_history[DataCloudObjectType.DMO] def test_auto_write_to_dlo(self, reset_client, mock_spark): From 1eab5817fe6456b4736a7316a9535693e2221721 Mon Sep 17 00:00:00 2001 From: Mark DeLaVergne Date: Fri, 20 Nov 2026 13:33:17 -0500 Subject: [PATCH 2/3] Fix lint issue --- src/datacustomcode/io/dedup_order.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/datacustomcode/io/dedup_order.py b/src/datacustomcode/io/dedup_order.py index d07c79fd..5f60a5f6 100644 --- a/src/datacustomcode/io/dedup_order.py +++ b/src/datacustomcode/io/dedup_order.py @@ -22,8 +22,8 @@ from __future__ import annotations -import re from collections.abc import Mapping, Sequence +import re from typing import Final from datacustomcode.io import cdf From fd9edcc92121b072ae51586df69ec6d4d344edcf Mon Sep 17 00:00:00 2001 From: Mark DeLaVergne Date: Mon, 30 Nov 2026 11:56:14 -0500 Subject: [PATCH 3/3] Add _change_type related constant and enum values --- CHANGELOG.md | 1 + src/datacustomcode/io/cdf.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 917d8301..3971c560 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ ### 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. +- **`datacustomcode.io.cdf`** – `CHANGE_TYPE` column constant and `ChangeType` enum (`INSERT`, `UPDATE_PREIMAGE`, `UPDATE_POSTIMAGE`, `DELETE`). ## 7.1.0 diff --git a/src/datacustomcode/io/cdf.py b/src/datacustomcode/io/cdf.py index 3f66c550..c48b2501 100644 --- a/src/datacustomcode/io/cdf.py +++ b/src/datacustomcode/io/cdf.py @@ -15,10 +15,12 @@ from __future__ import annotations +from enum import Enum from typing import Final from datacustomcode.io.writer.base import MERGE_RECORD_TYPE_COLUMN, MergeRecordType +CHANGE_TYPE: Final = "_change_type" COMMIT_VERSION: Final = "_commit_version" COMMIT_TIMESTAMP: Final = "_commit_timestamp" MERGE_RECORD_TYPE: Final = MERGE_RECORD_TYPE_COLUMN @@ -27,7 +29,19 @@ CDF_METADATA_COLUMNS: Final = (COMMIT_VERSION, COMMIT_TIMESTAMP, MERGE_RECORD_TYPE) + +class ChangeType(str, Enum): + """Values of the _change_type column.""" + + INSERT = "insert" + UPDATE_PREIMAGE = "update_preimage" + UPDATE_POSTIMAGE = "update_postimage" + DELETE = "delete" + + __all__ = [ + "CHANGE_TYPE", + "ChangeType", "COMMIT_VERSION", "COMMIT_TIMESTAMP", "MERGE_RECORD_TYPE",