diff --git a/CHANGELOG.md b/CHANGELOG.md index fb41eee5..d43038fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 7.0.0 + +### Breaking Changes + +- **`datacustomcode zip` and `datacustomcode deploy` no longer package symlinks.** + + Symlinks found inside the payload directory are skipped instead of being followed. A symlinked file logs a `Skipping symlink file ` warning and is left out of `deployment.zip`. + + **Why:** Following a symlink packaged the bytes of its target into the archive, even when the target was outside the payload (for example `payload/notes.txt -> ~/.ssh/id_rsa`). + + **Migration:** Replace any symlink in the payload with a real copy of the file or directory it points to: + + ```bash + # Before + ln -s ../shared/helpers.py payload/helpers.py + + # After + cp ../shared/helpers.py payload/helpers.py + ``` + +### Added + +- **`StreamingClient.write_dmo_deltas(name, dataframe)`** – start a streaming query that writes each micro-batch to the target DMO and return the `StreamingQuery` handle. It is the DMO counterpart to `write_dlo_deltas` and pairs with `read_dmo_deltas()`. + ## 6.1.0 ### Added diff --git a/README.md b/README.md index a9f5ae88..aa979faf 100644 --- a/README.md +++ b/README.md @@ -151,13 +151,14 @@ For a batch transform, use `Client`. You should only need the following methods: * `find_file_path(file_name)` – Resolve a bundled file (placed under `payload/files/`) to a `pathlib.Path` that exists. Works the same locally and inside Data Cloud — see [Bundled file resolution](#bundled-file-resolution) below for the full lookup order. Raises `FileNotFoundError` if the file isn't found. * `read_dlo(name)` – Read from a Data Lake Object by name * `read_dmo(name)` – Read from a Data Model Object by name -* `write_to_dlo(name, spark_dataframe, write_mode)` – Write to a Data Model Object by name with a Spark dataframe -* `write_to_dmo(name, spark_dataframe, write_mode)` – Write to a Data Lake Object by name with a Spark dataframe +* `write_to_dlo(name, spark_dataframe, write_mode)` – Write to a Data Lake Object by name with a Spark dataframe +* `write_to_dmo(name, spark_dataframe, write_mode)` – Write to a Data Model Object by name with a Spark dataframe 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` `find_file_path`, `llm_gateway_generate_text`, and `einstein_predict` are available on both clients. @@ -176,6 +177,27 @@ client.write_to_dlo('output_DLO') > [!WARNING] > Currently we only support reading from DMOs and writing to DMOs or reading from DLOs and writing to DLOs, but they cannot mix. +### Writing Currency fields + +A DLO or DMO with a Currency field has a system field, `cdp_sys_record_currency__c`, that holds each record's ISO currency code. Data Explorer UI uses it to display currency values, and shows a blank value if it's null (Query Editor still shows it). + +Code Extensions don't set `cdp_sys_record_currency__c` for you, since only your script knows what currency its amounts are in. When writing to an object with Currency fields, set it yourself: + +```python +from pyspark.sql.functions import lit + +# Either source has Currency fields: keep its cdp_sys_record_currency__c in your output +df = source.select("id__c", "amount__c", "cdp_sys_record_currency__c") + +# OR amounts are in a known currency +df = df.withColumn("cdp_sys_record_currency__c", lit("EUR")) +``` + +- Use an ISO code that exists in your org's configured currency rates. +- When aggregating, group by the currency code so amounts in different currencies aren't summed together. + +See [`docs/examples/script/currency_totals`](docs/examples/script/currency_totals) for a complete example. + ### 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: @@ -201,6 +223,15 @@ query = client.write_dlo_deltas("Output__dll", transformed) query.awaitTermination() ``` +A streaming transform can also read and write Data Model Objects with `read_dmo_deltas()` and `write_dmo_deltas()`: + +```python +deltas = client.read_dmo_deltas() +transformed = deltas.withColumn("description__c", upper(col("description__c"))) +query = client.write_dmo_deltas("Output__dlm", transformed) +query.awaitTermination() +``` + 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. @@ -224,6 +255,29 @@ If none of these exist, `find_file_path` raises `FileNotFoundError` with the lis `$LIBRARY_PATH` is set automatically to the root of the package at runtime inside Data Cloud. +### Generating lineage + +`generate_lineage` runs a script entry point locally and derives the field-level `dataLineage` section of `config.json` from the Spark plans of the DataFrames it writes: + +```python +from datacustomcode.lineage import generate_lineage + +result = generate_lineage("payload/entrypoint.py", sf_cli_org="my-org") +print(result.to_dict()["dataLineage"]) +# [{"targetField": "Output__dll.name__c", +# "sourceFields": ["Input__dll.first__c", "Input__dll.last__c"]}, ...] +``` + +The entry point runs exactly as it would locally (same config, reader, and credentials), except that writes are traced and validated against the target DLO instead of being performed. It runs in a separate Python process, which inherits your working directory, environment, and `sys.path`; errors raised by the script are re-raised from `generate_lineage`. Reads use the reader's `default_row_limit` (1000 by default; set it in your `config.yaml`). + +> **Review the output before you use it.** The generated lineage is a starting point for review, not a guarantee. It reflects only the code paths and data your local run exercised, and it can't see inside UDFs. Accurate and complete `dataLineage` in your package is your responsibility as the package author. + +- A target field's sources are the fields its *value* is computed from. Fields that only decide which rows, groups or branch are used aren't sources, however the logic is written: filter conditions, join keys, `groupBy` keys, sort keys, window `partitionBy`/`orderBy` keys, `when()`/`if()` conditions, and aggregate `FILTER (WHERE …)` clauses. For example, `groupBy("region").agg(sum("amount"))` and `sum("amount").over(Window.partitionBy("region"))` both trace to `amount` only. +- Fields computed only from literals are listed in `noSources`. So are fields whose value doesn't come from any input field's value, such as `row_number()`, `rank()`, `count("*")`, or `sum(when(cond, 1))`. +- Fields that can't be traced are listed in `unresolved` with a reason and get no lineage. This covers data that didn't come from `read_dlo`/`read_dmo` (for example a `toPandas()` → `createDataFrame` round trip), `mapInPandas`, and subqueries. +- `pairCount` is the total number of (target, source) field pairs. +- Only batch script packages are supported. + ## CLI @@ -339,6 +393,8 @@ Options: #### `datacustomcode zip` Zip a transformation job in preparation to upload to Data Cloud. Make sure to change directory into your code package folder (e.g., `my_package`) before running this command. +Symlinks inside the payload folder are not followed or packaged. Each symlinked file that is skipped is reported with a warning, and symlinked directories are not included. `datacustomcode deploy` zips the same way. + Arguments: - `PATH`: Path to the code directory i.e. the payload folder (default: "payload") diff --git a/docs/examples/script/README.md b/docs/examples/script/README.md new file mode 100644 index 00000000..c0481cde --- /dev/null +++ b/docs/examples/script/README.md @@ -0,0 +1,16 @@ +# Code Extension for Batch Transform — Examples + +End-to-end Code Extension scripts. Each subdirectory is a self-contained deploy package (`payload/entrypoint.py` + `config.json` + `requirements.txt` + any bundled assets) that can run against a Data 360 org. + +## Loading sample data + +Many examples ship with a `sample_data/` folder containing CSV(s) needed to exercise it. To load one: + +1. In Data 360, go to **Data Streams → New** and pick the **File Upload** connector. +2. Upload the CSV from `/sample_data/`. +3. Map columns to the target object listed in the example's README, in your dataspace. +4. Run the ingest. + +## Related + +- Developer guide — [Data 360 Code Extension](https://developer.salesforce.com/docs/data/data-cloud-code-ext/guide/use-custom-code.html). diff --git a/docs/examples/script/account_rollup/README.md b/docs/examples/script/account_rollup/README.md new file mode 100644 index 00000000..be3c76ee --- /dev/null +++ b/docs/examples/script/account_rollup/README.md @@ -0,0 +1,23 @@ +# Example: Iterative rollup of an account hierarchy + +A Code Extension for Batch Transform that walks a self-referencing `Account__dll` and produces `Account_Rollup__dll` with each account's **total-tree ARR** — its own ARR plus every descendant account's ARR. + +## What it demonstrates + +- Imperative control flow (a `while` loop with `isEmpty()` convergence) around DataFrame ops. +- `.persist()` on the frontier + growing set, so each iteration doesn't re-derive earlier hops. +- Alias-based joins (`accounts.alias("a")` / `descendants.alias("d")`) — required whenever the same DataFrame appears on both sides. + +## Prerequisites + +An `Account__dll` DLO in the target dataspace with columns: + +| Column | Type | Notes | +|-----------------|---------|---------------------------------------------| +| `id__c` | text | Primary key. | +| `parent_id__c` | text | Nullable. FK back to `Account__dll.id__c`. | +| `arr__c` | number | Annual recurring revenue for this account. | + +Data should be loaded via `sample_data/account.csv`. See [loading sample data](../README.md#loading-sample-data). + +Output DLO `Account_Rollup__dll` must also exist with `id__c` and `tree_arr__c` columns. diff --git a/docs/examples/script/account_rollup/payload/config.json b/docs/examples/script/account_rollup/payload/config.json new file mode 100644 index 00000000..a2f4973b --- /dev/null +++ b/docs/examples/script/account_rollup/payload/config.json @@ -0,0 +1,13 @@ +{ + "sdkVersion": "6.0.4", + "entryPoint": "entrypoint.py", + "dataspace": "default", + "permissions": { + "read": { + "dlo": ["Account__dll"] + }, + "write": { + "dlo": ["Account_Rollup__dll"] + } + } +} diff --git a/docs/examples/script/account_rollup/payload/entrypoint.py b/docs/examples/script/account_rollup/payload/entrypoint.py new file mode 100644 index 00000000..613cbe83 --- /dev/null +++ b/docs/examples/script/account_rollup/payload/entrypoint.py @@ -0,0 +1,62 @@ +from pyspark.sql.functions import ( + coalesce, + col, + lit, + sum as _sum, +) + +from datacustomcode.client import Client +from datacustomcode.io.writer.base import WriteMode + + +def main(): + client = Client() + + accounts = ( + client.read_dlo("Account__dll") + .select("id__c", "parent_id__c", "arr__c") + .persist() + ) + + descendants = accounts.select( + col("id__c").alias("root_id"), + col("id__c").alias("descendant_id"), + ).persist() + + frontier = descendants + while True: + next_hop = ( + frontier.alias("f") + .join( + accounts.alias("a"), + col("a.parent_id__c") == col("f.descendant_id"), + "inner", + ) + .select( + col("f.root_id").alias("root_id"), + col("a.id__c").alias("descendant_id"), + ) + ) + if next_hop.isEmpty(): + break + descendants = descendants.union(next_hop).persist() + frontier = next_hop + + totals = ( + descendants.alias("d") + .join( + accounts.alias("a"), + col("d.descendant_id") == col("a.id__c"), + "left", + ) + .select(col("d.root_id"), col("a.arr__c")) + .groupBy("root_id") + .agg(coalesce(_sum("arr__c"), lit(0)).alias("tree_arr__c")) + .withColumnRenamed("root_id", "id__c") + ) + + client.write_to_dlo("Account_Rollup__dll", totals, WriteMode.OVERWRITE) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/script/account_rollup/requirements.txt b/docs/examples/script/account_rollup/requirements.txt new file mode 100644 index 00000000..b4fc8840 --- /dev/null +++ b/docs/examples/script/account_rollup/requirements.txt @@ -0,0 +1 @@ +# Packages required for the custom code diff --git a/docs/examples/script/account_rollup/sample_data/account.csv b/docs/examples/script/account_rollup/sample_data/account.csv new file mode 100644 index 00000000..c58cc429 --- /dev/null +++ b/docs/examples/script/account_rollup/sample_data/account.csv @@ -0,0 +1,9 @@ +id,parent_id,arr +A1,,100000 +A2,A1,50000 +A3,A1,25000 +A4,A2,10000 +A5,A2,5000 +A6,,200000 +A7,A6,75000 +A8,A7,15000 diff --git a/docs/examples/script/currency_totals/README.md b/docs/examples/script/currency_totals/README.md new file mode 100644 index 00000000..aedbe71b --- /dev/null +++ b/docs/examples/script/currency_totals/README.md @@ -0,0 +1,33 @@ +# Example: Totals that keep their currency code + +A Code Extension for Batch Transform that sums `Payment__dll` amounts per customer and writes them to `Customer_Payment_Totals__dll`, a DLO with a Currency field, setting the `cdp_sys_record_currency__c` system field so Data Explorer UI can display the totals. + +## What it demonstrates + +- **Carrying `cdp_sys_record_currency__c` through** from the source rows to the output. Code Extensions don't auto-populate `cdp_sys_record_currency__c`. And if it's null, Data Explorer shows the Currency value as blank. See [Writing Currency fields](../../../../README.md#writing-currency-fields). +- **Grouping by currency** so EUR and USD amounts are never summed together. Customer `C1` gets one EUR row and one USD row. +- If all amounts are in one known currency, one can also use `lit("EUR")` instead of copying a column. + +## Prerequisites + +Input DLO `Payment__dll` in the target dataspace: + +| Column | Type | Notes | +|------------------------------|----------|------------------------------------------------------------------------| +| `id__c` | text | Primary key. | +| `customer_id__c` | text | | +| `amount__c` | Currency | | +| `cdp_sys_record_currency__c` | text | System field, added with the Currency field. From CSV `currency_code`. | + +Data should be loaded via `sample_data/payment.csv`. See [loading sample data](../README.md#loading-sample-data). + +Output DLO `Customer_Payment_Totals__dll` in the same dataspace: + +| Column | Type | Notes | +|------------------------------|----------|--------------------------------------------------| +| `id__c` | text | Primary key (`_`). | +| `customer_id__c` | text | | +| `total_amount__c` | Currency | | +| `cdp_sys_record_currency__c` | text | System field, added with the Currency field. | + +The ISO codes in `sample_data/payment.csv` must exist in your org's currency rates. diff --git a/docs/examples/script/currency_totals/payload/config.json b/docs/examples/script/currency_totals/payload/config.json new file mode 100644 index 00000000..bf3ec487 --- /dev/null +++ b/docs/examples/script/currency_totals/payload/config.json @@ -0,0 +1,13 @@ +{ + "sdkVersion": "6.1.0", + "entryPoint": "entrypoint.py", + "dataspace": "default", + "permissions": { + "read": { + "dlo": ["Payment__dll"] + }, + "write": { + "dlo": ["Customer_Payment_Totals__dll"] + } + } +} diff --git a/docs/examples/script/currency_totals/payload/entrypoint.py b/docs/examples/script/currency_totals/payload/entrypoint.py new file mode 100644 index 00000000..4edd056d --- /dev/null +++ b/docs/examples/script/currency_totals/payload/entrypoint.py @@ -0,0 +1,35 @@ +from pyspark.sql.functions import ( + col, + concat_ws, + sum as _sum, +) + +from datacustomcode.client import Client +from datacustomcode.io.writer.base import WriteMode + + +def main(): + client = Client() + + payments = client.read_dlo("Payment__dll").select( + "customer_id__c", "amount__c", "cdp_sys_record_currency__c" + ) + + totals = ( + payments.groupBy("customer_id__c", "cdp_sys_record_currency__c") + .agg(_sum("amount__c").alias("total_amount__c")) + .select( + concat_ws( + "_", col("customer_id__c"), col("cdp_sys_record_currency__c") + ).alias("id__c"), + col("customer_id__c"), + col("total_amount__c"), + col("cdp_sys_record_currency__c"), + ) + ) + + client.write_to_dlo("Customer_Payment_Totals__dll", totals, WriteMode.OVERWRITE) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/script/currency_totals/requirements.txt b/docs/examples/script/currency_totals/requirements.txt new file mode 100644 index 00000000..b4fc8840 --- /dev/null +++ b/docs/examples/script/currency_totals/requirements.txt @@ -0,0 +1 @@ +# Packages required for the custom code diff --git a/docs/examples/script/currency_totals/sample_data/payment.csv b/docs/examples/script/currency_totals/sample_data/payment.csv new file mode 100644 index 00000000..7def99b9 --- /dev/null +++ b/docs/examples/script/currency_totals/sample_data/payment.csv @@ -0,0 +1,7 @@ +id,customer_id,amount,currency_code +P1,C1,100.00,EUR +P2,C1,250.50,EUR +P3,C1,40.00,USD +P4,C2,1200.00,USD +P5,C2,300.00,USD +P6,C3,75.25,GBP diff --git a/docs/examples/script/json_explode/README.md b/docs/examples/script/json_explode/README.md new file mode 100644 index 00000000..5f21bac9 --- /dev/null +++ b/docs/examples/script/json_explode/README.md @@ -0,0 +1,33 @@ +# Example: Flatten a batched event stream from a JSON-array column + +A Code Extension for Batch Transform that reads a `User_Sessions__dll` DLO — one row per session, with each session's events packed into a JSON-array column — and writes one row per event into `User_Events__dll`. Parse-and-explode logic lives in a reusable module under `payload/py-files/`. + +## What it demonstrates + +- **`payload/py-files/`** — Split real logic into modules, unit-test them locally, reuse them across scripts. +- **`from_json` + `explode_outer`** to turn one row per session into one row per event, carrying the parent `session_id__c` and `user_id__c` through. +- **`to_timestamp()`** to parse ISO-8601 event timestamps into Spark `TimestampType`, which writes cleanly into Data 360's `DateTime` column. + +## Prerequisites + +Input DLO `User_Sessions__dll` in the target dataspace: + +| Column | Type | Notes | +|------------------|------|---------------------------------------------| +| `session_id__c` | text | Primary key. | +| `user_id__c` | text | | +| `events__c` | text | JSON array of `{event_id, event_type, ts, path, value}`. | + +Data should be loaded via `sample_data/user_sessions.csv`. See [loading sample data](../README.md#loading-sample-data). + +Output DLO `User_Events__dll` in the same dataspace: + +| Column | Type | Notes | +|-----------------|----------|---------------| +| `event_id__c` | text | Primary key. | +| `session_id__c` | text | | +| `user_id__c` | text | | +| `event_type__c` | text | | +| `event_ts__c` | DateTime | | +| `path__c` | text | | +| `value__c` | text | | diff --git a/docs/examples/script/json_explode/payload/config.json b/docs/examples/script/json_explode/payload/config.json new file mode 100644 index 00000000..10a7c110 --- /dev/null +++ b/docs/examples/script/json_explode/payload/config.json @@ -0,0 +1,13 @@ +{ + "sdkVersion": "6.0.4", + "entryPoint": "entrypoint.py", + "dataspace": "default", + "permissions": { + "read": { + "dlo": ["User_Sessions__dll"] + }, + "write": { + "dlo": ["User_Events__dll"] + } + } +} diff --git a/docs/examples/script/json_explode/payload/entrypoint.py b/docs/examples/script/json_explode/payload/entrypoint.py new file mode 100644 index 00000000..aaa98257 --- /dev/null +++ b/docs/examples/script/json_explode/payload/entrypoint.py @@ -0,0 +1,22 @@ +from events import parse_events +from pyspark.sql.functions import col + +from datacustomcode.client import Client +from datacustomcode.io.writer.base import WriteMode + + +def main(): + client = Client() + + sessions = client.read_dlo("User_Sessions__dll").select( + "session_id__c", "user_id__c", "events__c" + ) + exploded = parse_events(sessions, "session_id__c", "user_id__c", "events__c") + + output = exploded.filter(col("event_id__c").isNotNull()) + + client.write_to_dlo("User_Events__dll", output, WriteMode.OVERWRITE) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/script/json_explode/payload/py-files/events.py b/docs/examples/script/json_explode/payload/py-files/events.py new file mode 100644 index 00000000..877ef0fe --- /dev/null +++ b/docs/examples/script/json_explode/payload/py-files/events.py @@ -0,0 +1,50 @@ +from pyspark.sql.functions import ( + col, + explode_outer, + from_json, + to_timestamp, +) +from pyspark.sql.types import ( + ArrayType, + StringType, + StructField, + StructType, +) + +EVENT_SCHEMA = StructType( + [ + StructField("event_id", StringType(), True), + StructField("event_type", StringType(), True), + StructField("ts", StringType(), True), + StructField("path", StringType(), True), + StructField("value", StringType(), True), + ] +) +EVENT_ARRAY_SCHEMA = ArrayType(EVENT_SCHEMA, True) + + +def parse_events(df, session_col, user_col, events_col): + """One row per event, carrying its parent session + user. + + Handles both a real ArrayType column and a string column that + contains the JSON array. + """ + field = next(f for f in df.schema.fields if f.name == events_col) + events = ( + col(events_col) + if isinstance(field.dataType, ArrayType) + else from_json(col(events_col).cast("string"), EVENT_ARRAY_SCHEMA) + ) + return df.select( + col(session_col), + col(user_col), + explode_outer(events).alias("evt"), + ).select( + col("evt.event_id").alias("event_id__c"), + col(session_col), + col(user_col), + col("evt.event_type").alias("event_type__c"), + to_timestamp(col("evt.ts")).alias("event_ts__c"), + col("evt.path").alias("path__c"), + col("evt.value").alias("value__c"), + ) diff --git a/docs/examples/script/json_explode/requirements.txt b/docs/examples/script/json_explode/requirements.txt new file mode 100644 index 00000000..b4fc8840 --- /dev/null +++ b/docs/examples/script/json_explode/requirements.txt @@ -0,0 +1 @@ +# Packages required for the custom code diff --git a/docs/examples/script/json_explode/sample_data/user_sessions.csv b/docs/examples/script/json_explode/sample_data/user_sessions.csv new file mode 100644 index 00000000..e09df3ef --- /dev/null +++ b/docs/examples/script/json_explode/sample_data/user_sessions.csv @@ -0,0 +1,6 @@ +session_id,user_id,events +S1,U1,"[{""event_id"":""E1"",""event_type"":""page_view"",""ts"":""2026-09-22T14:00:00Z"",""path"":""/home"",""value"":null},{""event_id"":""E2"",""event_type"":""page_view"",""ts"":""2026-09-22T14:00:15Z"",""path"":""/pricing"",""value"":null},{""event_id"":""E3"",""event_type"":""click"",""ts"":""2026-09-22T14:00:42Z"",""path"":""/pricing"",""value"":""cta_upgrade""}]" +S2,U2,"[{""event_id"":""E4"",""event_type"":""page_view"",""ts"":""2026-09-22T14:05:00Z"",""path"":""/blog/announcing-x"",""value"":null},{""event_id"":""E5"",""event_type"":""scroll_50"",""ts"":""2026-09-22T14:05:22Z"",""path"":""/blog/announcing-x"",""value"":""50""}]" +S3,U1,"[{""event_id"":""E6"",""event_type"":""page_view"",""ts"":""2026-09-22T15:00:00Z"",""path"":""/dashboard"",""value"":null},{""event_id"":""E7"",""event_type"":""form_submit"",""ts"":""2026-09-22T15:01:11Z"",""path"":""/dashboard"",""value"":""support_request""},{""event_id"":""E8"",""event_type"":""page_view"",""ts"":""2026-09-22T15:01:20Z"",""path"":""/support/thanks"",""value"":null}]" +S4,U3,"[]" +S5,U4,"[{""event_id"":""E9"",""event_type"":""page_view"",""ts"":""2026-09-22T16:10:00Z"",""path"":""/home"",""value"":null}]" diff --git a/docs/examples/script/lead_scoring/README.md b/docs/examples/script/lead_scoring/README.md new file mode 100644 index 00000000..254d1367 --- /dev/null +++ b/docs/examples/script/lead_scoring/README.md @@ -0,0 +1,33 @@ +# Example: Score leads with a bundled scikit-learn model + +A Code Extension for Batch Transform that scores every lead in a `Lead__dll` DLO against a scikit-learn classifier **bundled directly with the deploy package**. + +## What it demonstrates + +- **Bundling a trained model as `payload/files/lead_scorer.zip`** (a zip wrapping `lead_scorer.joblib`). +- **Grid-join scoring** — instead of scoring each lead individually, the script enumerates every combination of the model's categorical inputs, scores that small grid with `predict_proba`, and turns the results into a reference DataFrame that is left-joined against the leads. + +## Regenerating the bundled model + +```sh +pip install -r requirements.txt +python train_model.py +``` + +## Prerequisites + +A `Lead__dll` DLO in the target dataspace with at least: + +| Column | Type | +|------------------|--------| +| `id__c` | text | +| `first_name__c` | text | +| `last_name__c` | text | +| `industry__c` | text | +| `employee_band__c` | text | +| `region__c` | text | +| `source__c` | text | + +Data should be loaded via `sample_data/lead.csv`. See [loading sample data](../README.md#loading-sample-data). + +Output DLO `Lead_Scored__dll` must also exist (same columns plus `score__c` number). diff --git a/docs/examples/script/lead_scoring/payload/config.json b/docs/examples/script/lead_scoring/payload/config.json new file mode 100644 index 00000000..e05a595c --- /dev/null +++ b/docs/examples/script/lead_scoring/payload/config.json @@ -0,0 +1,13 @@ +{ + "sdkVersion": "6.0.4", + "entryPoint": "entrypoint.py", + "dataspace": "default", + "permissions": { + "read": { + "dlo": ["Lead__dll"] + }, + "write": { + "dlo": ["Lead_Scored__dll"] + } + } +} diff --git a/docs/examples/script/lead_scoring/payload/entrypoint.py b/docs/examples/script/lead_scoring/payload/entrypoint.py new file mode 100644 index 00000000..1befa733 --- /dev/null +++ b/docs/examples/script/lead_scoring/payload/entrypoint.py @@ -0,0 +1,85 @@ +import itertools +from pathlib import Path +import tempfile +import zipfile + +import joblib +import pandas as pd +from pyspark.sql import Row +from pyspark.sql.functions import ( + coalesce, + col, + lit, +) + +from datacustomcode.client import Client +from datacustomcode.io.writer.base import WriteMode + +UNKNOWN = "__unknown__" +MODEL_ARCHIVE = "lead_scorer.zip" +MODEL_MEMBER = "lead_scorer.joblib" + +OUTPUT_COLUMNS = [ + "id__c", + "first_name__c", + "last_name__c", + "industry__c", + "employee_band__c", + "region__c", + "source__c", + "score__c", +] + + +def load_bundled_model(client): + archive_path = client.find_file_path(MODEL_ARCHIVE) + extract_dir = Path(tempfile.mkdtemp(prefix="lead_scorer_")) + with zipfile.ZipFile(archive_path) as zf: + zf.extract(MODEL_MEMBER, path=extract_dir) + return joblib.load(extract_dir / MODEL_MEMBER) + + +def build_score_grid(spark, bundle): + """Enumerate every combination of the model's known feature values, + score them, and return a small Spark DataFrame.""" + pipeline = bundle["pipeline"] + feature_cols = bundle["feature_cols"] + domain = bundle["feature_domain"] + + combos = list(itertools.product(*(domain[c] for c in feature_cols))) + grid_pd = pd.DataFrame(combos, columns=feature_cols) + grid_pd["score__c"] = pipeline.predict_proba(grid_pd)[:, 1] + + rows = [ + Row(**{c: r[c] for c in feature_cols}, score__c=float(r["score__c"])) + for r in grid_pd.to_dict(orient="records") + ] + return spark.createDataFrame(rows), feature_cols + + +def main(): + client = Client() + + leads = client.read_dlo("Lead__dll") + spark = leads.sparkSession + + bundle = load_bundled_model(client) + grid, feature_cols = build_score_grid(spark, bundle) + + normalized = leads + for c in feature_cols: + normalized = normalized.withColumn(c, coalesce(col(c), lit(UNKNOWN))) + + scored = ( + normalized.alias("l") + .join(grid.alias("g"), feature_cols, "left") + .withColumn("score__c", coalesce(col("score__c"), lit(0.0))) + ) + + client.write_to_dlo( + "Lead_Scored__dll", scored.select(*OUTPUT_COLUMNS), WriteMode.OVERWRITE + ) + + +if __name__ == "__main__": + main() diff --git a/docs/examples/script/lead_scoring/requirements.txt b/docs/examples/script/lead_scoring/requirements.txt new file mode 100644 index 00000000..7356fa59 --- /dev/null +++ b/docs/examples/script/lead_scoring/requirements.txt @@ -0,0 +1,4 @@ +# Packages required for the custom code +scikit-learn>=1.4 +joblib>=1.3 +pandas>=2.0 diff --git a/docs/examples/script/lead_scoring/sample_data/lead.csv b/docs/examples/script/lead_scoring/sample_data/lead.csv new file mode 100644 index 00000000..70ec8af4 --- /dev/null +++ b/docs/examples/script/lead_scoring/sample_data/lead.csv @@ -0,0 +1,21 @@ +id,first_name,last_name,industry,employee_band,region,source +L1,Ava,Nguyen,tech,201-1000,NA,referral +L2,Ben,Ortiz,tech,1001-5000,NA,partner +L3,Cara,Singh,finance,5001+,EMEA,event +L4,Dan,Weiss,healthcare,51-200,NA,marketing_campaign +L5,Elena,Park,retail,11-50,APAC,cold_outreach +L6,Frank,Yamada,agriculture,1-10,LATAM,cold_outreach +L7,Grace,Osei,tech,51-200,EMEA,webform +L8,Hugo,Lin,telecom,1001-5000,ANZ,partner +L9,Isha,Mehta,education,1-10,APAC,marketing_campaign +L10,Jack,Rowe,government,201-1000,NA,cold_outreach +L11,Kira,Sato,media,11-50,APAC,webform +L12,Leo,Duval,real_estate,51-200,EMEA,referral +L13,Mia,Costa,hospitality,1-10,LATAM,webform +L14,Nate,Weber,energy,5001+,NA,partner +L15,Omar,Diallo,transportation,201-1000,EMEA,event +L16,Priya,Rao,manufacturing,1001-5000,APAC,referral +L17,Quinn,Bauer,other,11-50,ANZ,cold_outreach +L18,Rita,Kang,finance,51-200,APAC,referral +L19,Sam,Alavi,tech,1-10,NA,event +L20,Tara,Ilic,healthcare,5001+,EMEA,partner diff --git a/docs/examples/script/lead_scoring/train_model.py b/docs/examples/script/lead_scoring/train_model.py new file mode 100644 index 00000000..f942173e --- /dev/null +++ b/docs/examples/script/lead_scoring/train_model.py @@ -0,0 +1,150 @@ +# Train a small lead-scoring classifier and bundle it with the payload. +from __future__ import annotations + +import itertools +import pathlib +import random +import zipfile + +import joblib +import numpy as np +import pandas as pd +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import roc_auc_score +from sklearn.model_selection import train_test_split +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import OneHotEncoder + +INDUSTRIES = [ + "retail", + "healthcare", + "finance", + "tech", + "manufacturing", + "education", + "government", + "media", + "hospitality", + "transportation", + "energy", + "real_estate", + "telecom", + "agriculture", + "other", +] +EMPLOYEE_BANDS = ["1-10", "11-50", "51-200", "201-1000", "1001-5000", "5001+"] +REGIONS = ["NA", "EMEA", "APAC", "LATAM", "ANZ"] +SOURCES = [ + "webform", + "event", + "referral", + "partner", + "cold_outreach", + "marketing_campaign", +] + +FEATURE_COLS = ["industry__c", "employee_band__c", "region__c", "source__c"] + +BAND_SIGNAL = {b: i for i, b in enumerate(EMPLOYEE_BANDS)} +SOURCE_SIGNAL = { + "referral": 2.0, + "partner": 1.2, + "event": 0.8, + "marketing_campaign": 0.3, + "webform": 0.0, + "cold_outreach": -1.0, +} +INDUSTRY_SIGNAL = { + "tech": 1.2, + "finance": 1.0, + "healthcare": 0.7, + "telecom": 0.5, + "energy": 0.4, + "manufacturing": 0.2, + "retail": 0.0, + "media": 0.0, + "real_estate": -0.2, + "education": -0.3, + "government": -0.4, + "hospitality": -0.5, + "transportation": -0.5, + "agriculture": -0.7, + "other": -0.5, +} +REGION_SIGNAL = {"NA": 0.6, "EMEA": 0.4, "APAC": 0.3, "ANZ": 0.2, "LATAM": 0.0} + + +def synth_rows(n: int, seed: int = 42) -> pd.DataFrame: + rng = random.Random(seed) + rows = [] + for _ in range(n): + row = { + "industry__c": rng.choice(INDUSTRIES), + "employee_band__c": rng.choice(EMPLOYEE_BANDS), + "region__c": rng.choice(REGIONS), + "source__c": rng.choice(SOURCES), + } + logit = ( + INDUSTRY_SIGNAL[row["industry__c"]] + + 0.4 * BAND_SIGNAL[row["employee_band__c"]] + + REGION_SIGNAL[row["region__c"]] + + SOURCE_SIGNAL[row["source__c"]] + - 1.5 + ) + p = 1.0 / (1.0 + np.exp(-logit)) + row["converted"] = int(rng.random() < p) + rows.append(row) + return pd.DataFrame(rows) + + +def main() -> None: + df = synth_rows(8000) + X, y = df[FEATURE_COLS], df["converted"] + + X_tr, X_te, y_tr, y_te = train_test_split( + X, y, test_size=0.25, random_state=0, stratify=y + ) + pipe = Pipeline( + [ + ("ohe", OneHotEncoder(handle_unknown="ignore", sparse_output=False)), + ("clf", LogisticRegression(max_iter=1000, random_state=0)), + ] + ) + pipe.fit(X_tr, y_tr) + + auc = roc_auc_score(y_te, pipe.predict_proba(X_te)[:, 1]) + prevalence = float(y.mean()) + + grid_rows = list(itertools.product(INDUSTRIES, EMPLOYEE_BANDS, REGIONS, SOURCES)) + print( + f"train AUC: {auc:.3f} | prevalence: {prevalence:.3f} | grid: {len(grid_rows)}" + ) + + payload = { + "pipeline": pipe, + "feature_cols": FEATURE_COLS, + "feature_domain": { + "industry__c": INDUSTRIES, + "employee_band__c": EMPLOYEE_BANDS, + "region__c": REGIONS, + "source__c": SOURCES, + }, + } + + out_joblib = ( + pathlib.Path(__file__).parent / "payload" / "files" / "lead_scorer.joblib" + ) + out_joblib.parent.mkdir(parents=True, exist_ok=True) + joblib.dump(payload, out_joblib, compress=3) + print(f"wrote {out_joblib} ({out_joblib.stat().st_size} bytes)") + + out_zip = out_joblib.with_suffix(".zip") + with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf: + zf.write(out_joblib, arcname=out_joblib.name) + print(f"wrote {out_zip} ({out_zip.stat().st_size} bytes)") + + out_joblib.unlink() + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index 2d6938b5..c0e868bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,10 +87,10 @@ warn_unused_configs = true [tool.poetry] include = [ - {path = "src/datacustomcode/templates/**/*"}, - {path = "src/datacustomcode/config.yaml"} + { path = "src/datacustomcode/templates/**/*" }, + { path = "src/datacustomcode/config.yaml" } ] -packages = [{include = "datacustomcode", from = "src"}] +packages = [{ include = "datacustomcode", from = "src" }] version = "0.0.0" [tool.poetry.build] @@ -115,7 +115,7 @@ coverage = ">=7.0.0,<8.0.0" ipykernel = "^6.29.5" mypy = "*" pipreqs = "*" -poetry-dynamic-versioning = {extras = ["plugin"], version = "^1.8.2"} +poetry-dynamic-versioning = { extras = ["plugin"], version = "^1.8.2" } pre-commit = "*" pytest = "*" pytest-cov = "*" @@ -127,7 +127,7 @@ types-requests = "*" [tool.poetry.plugins."poetry.plugin"] [tool.poetry.requires-plugins] -poetry-dynamic-versioning = {version = ">=1.0.0,<2.0.0", extras = ["plugin"]} +poetry-dynamic-versioning = { version = ">=1.0.0,<2.0.0", extras = ["plugin"] } [tool.poetry.scripts] datacustomcode = "datacustomcode.cli:cli" @@ -152,7 +152,6 @@ testpaths = ["tests"] [tool.ruff] fix = true line-length = 88 -target-version = 'py310' lint.ignore = [ # do not assign a lambda expression, use a def 'E731', @@ -211,6 +210,7 @@ lint.select = [ 'RUF', 'S102' ] +target-version = 'py310' [tool.setuptools.package_data] datacustomcode = ["templates/**/*", "config.yaml"] diff --git a/src/datacustomcode/__init__.py b/src/datacustomcode/__init__.py index 4cd56f57..4fd264bd 100644 --- a/src/datacustomcode/__init__.py +++ b/src/datacustomcode/__init__.py @@ -13,12 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datacustomcode.spark.column_hints import install_column_casing_hints + +# Friendlier errors for wrong-case column references. Idempotent. +install_column_casing_hints() + __all__ = [ "AuthType", "Client", "Credentials", "DefaultSparkEinsteinPredictions", "DefaultSparkLLMGateway", + "LocalDeltasReader", + "LocalDeltasWriter", "PrintDataCloudWriter", "QueryAPIDataCloudReader", "SparkEinsteinPredictions", @@ -55,6 +62,14 @@ def __getattr__(name: str): from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader return QueryAPIDataCloudReader + elif name == "LocalDeltasReader": + from datacustomcode.io.reader.local_deltas import LocalDeltasReader + + return LocalDeltasReader + elif name == "LocalDeltasWriter": + from datacustomcode.io.writer.local_deltas import LocalDeltasWriter + + return LocalDeltasWriter elif name == "SparkLLMGateway": from datacustomcode.llm_gateway import SparkLLMGateway diff --git a/src/datacustomcode/auth.py b/src/datacustomcode/auth.py index 6636379f..ca38001f 100644 --- a/src/datacustomcode/auth.py +++ b/src/datacustomcode/auth.py @@ -12,13 +12,21 @@ # 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. +import base64 +import hashlib +import hmac import http.server import queue +import secrets import socketserver import threading import time from typing import Any -from urllib.parse import parse_qs, urlparse +from urllib.parse import ( + parse_qs, + urlencode, + urlparse, +) import webbrowser import click @@ -28,16 +36,35 @@ class OAuthCallbackHandler(http.server.SimpleHTTPRequestHandler): """HTTP request handler to capture OAuth callback.""" - def __init__(self, *args, auth_code_queue=None, **kwargs): + def __init__(self, *args, auth_code_queue=None, expected_state=None, **kwargs): self.auth_code_queue = auth_code_queue + self.expected_state = expected_state super().__init__(*args, **kwargs) + def _state_matches(self, query_params: dict) -> bool: + """Check the callback's state parameter against the expected value.""" + received = query_params.get("state", [""])[0] + if not self.expected_state or not received: + return False + return hmac.compare_digest(received, self.expected_state) + def do_GET(self): - """Handle GET request from OAuth callback.""" + """Handle GET request from OAuth callback. + + Callbacks whose ``state`` does not match are rejected without touching + the queue, so a forged request can neither inject an authorization code + nor abort the legitimate login. + """ parsed_path = urlparse(self.path) query_params = parse_qs(parsed_path.query) - if "code" in query_params: + is_callback = "code" in query_params or "error" in query_params + if is_callback and not self._state_matches(query_params): + self.send_response(400) + self.send_header("Content-type", "text/html") + self.end_headers() + self.wfile.write(b"

Invalid callback

") + elif "code" in query_params: auth_code = query_params["code"][0] self.auth_code_queue.put(auth_code) self.send_response(200) @@ -70,14 +97,27 @@ def log_message(self, format, *args): """Suppress default logging.""" +def _generate_pkce_pair() -> tuple[str, str]: + """Generate a PKCE (RFC 7636) code verifier and its S256 code challenge. + + Returns: + Tuple of (code_verifier, code_challenge) + """ + code_verifier = secrets.token_urlsafe(64) + digest = hashlib.sha256(code_verifier.encode("ascii")).digest() + code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + return code_verifier, code_challenge + + def _run_oauth_callback_server( - redirect_uri: str, auth_code_queue: "queue.Queue[str]" + redirect_uri: str, auth_code_queue: "queue.Queue[str]", expected_state: str ) -> tuple[socketserver.TCPServer, int]: """Start a local HTTP server to catch OAuth callback. Args: redirect_uri: The redirect URI configured in the OAuth app auth_code_queue: Queue to put the authorization code in + expected_state: OAuth state value the callback must echo back Returns: Tuple of (server instance, actual port number) @@ -90,7 +130,12 @@ def _run_oauth_callback_server( # Create a custom handler factory def handler_factory(*args, **kwargs): - return OAuthCallbackHandler(*args, auth_code_queue=auth_code_queue, **kwargs) + return OAuthCallbackHandler( + *args, + auth_code_queue=auth_code_queue, + expected_state=expected_state, + **kwargs, + ) server = socketserver.TCPServer((host, port), handler_factory) server.allow_reuse_address = True @@ -113,6 +158,7 @@ def _exchange_code_for_tokens( client_secret: str, redirect_uri: str, auth_code: str, + code_verifier: str, ) -> Any: """Exchange authorization code for access and refresh tokens. @@ -122,6 +168,7 @@ def _exchange_code_for_tokens( client_secret: OAuth client secret redirect_uri: Redirect URI used in authorization auth_code: Authorization code from callback + code_verifier: PKCE code verifier matching the authorize request Returns: Dictionary containing access_token and refresh_token @@ -136,6 +183,7 @@ def _exchange_code_for_tokens( "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, + "code_verifier": code_verifier, } try: @@ -168,17 +216,28 @@ def do_oauth_browser_flow( # Create queue for communication between server and main thread auth_code_queue: queue.Queue[str] = queue.Queue() + # CSRF protection (RFC 6749 10.12) and PKCE (RFC 7636 / RFC 8252) + state = secrets.token_urlsafe(32) + code_verifier, code_challenge = _generate_pkce_pair() + # Start callback server click.echo(f"\nStarting local callback server on {redirect_uri}...") - server, _actual_port = _run_oauth_callback_server(redirect_uri, auth_code_queue) + server, _actual_port = _run_oauth_callback_server( + redirect_uri, auth_code_queue, state + ) # Build authorization URL with final redirect_uri - auth_url = ( - f"{login_url.rstrip('/')}/services/oauth2/authorize" - f"?response_type=code" - f"&client_id={client_id}" - f"&redirect_uri={redirect_uri}" + query = urlencode( + { + "response_type": "code", + "client_id": client_id, + "redirect_uri": redirect_uri, + "state": state, + "code_challenge": code_challenge, + "code_challenge_method": "S256", + } ) + auth_url = f"{login_url.rstrip('/')}/services/oauth2/authorize?{query}" # Open browser click.echo("Opening browser for authentication...") @@ -208,7 +267,7 @@ def do_oauth_browser_flow( # Exchange code for tokens click.echo("Exchanging authorization code for tokens...") token_response = _exchange_code_for_tokens( - login_url, client_id, client_secret, redirect_uri, auth_code + login_url, client_id, client_secret, redirect_uri, auth_code, code_verifier ) refresh_token = token_response.get("refresh_token") diff --git a/src/datacustomcode/cli.py b/src/datacustomcode/cli.py index 3a03e6d9..e2690a6f 100644 --- a/src/datacustomcode/cli.py +++ b/src/datacustomcode/cli.py @@ -215,6 +215,7 @@ def deploy( COMPUTE_TYPES, CodeExtensionMetadata, deploy_full, + describe_supported_signatures, infer_use_in_feature, ) from datacustomcode.token_provider import ( @@ -252,8 +253,9 @@ def deploy( else: click.secho( "Error: Function signature does not match a supported type. " - "Use SearchIndexChunkingV1Request and " - "SearchIndexChunkingV1Response in function signature.", + "Use a supported Request/Response pair in the function " + "signature. For example, " + f"{describe_supported_signatures(entrypoint_path)}.", fg="red", ) raise click.Abort() diff --git a/src/datacustomcode/client.py b/src/datacustomcode/client.py index b43e4236..69f7ea1f 100644 --- a/src/datacustomcode/client.py +++ b/src/datacustomcode/client.py @@ -231,11 +231,12 @@ def einstein_predict_col( def named_credential_request_col( request: "HTTPRequest", body: Optional["Column"] = None, + path: Optional["Column"] = None, ) -> "Column": """Build a Spark Column that makes one Named Credential callout per row. - The endpoint, method, and headers are fixed for the call (taken from - ``request``); only ``body`` varies per row. Use this instead of + The method and headers are fixed for the call (taken from ``request``); + ``body`` and, optionally, ``path`` vary per row. Use this instead of :meth:`Client.named_credential_request` when the callout runs across a DataFrame so each row is dispatched independently rather than one-shot on the driver. @@ -253,13 +254,20 @@ def named_credential_request_col( headers are applied to every row. body: Optional per-row ``Column`` holding the request body as a string (or null for no body). + path: Optional per-row ``Column`` appended to ``request.url``, e.g. + ``concat(lit("?address="), col("address"))`` or ``lit("/v1/models")``. + The callout always stays on ``request.url``'s Named Credential: a + path not starting with ``/`` or ``?`` is joined with ``/``. A null + or empty row value uses ``request.url`` as is. Returns: A Spark ``Column`` of ``StructType`` with fields ``status``, ``response``, ``error_code``, and ``error_message``. """ named_credential = Client()._get_spark_named_credential() - return named_credential.request_col(request, body=body) + if path is None: + return named_credential.request_col(request, body=body) + return named_credential.request_col(request, body=body, path=path) class DataCloudObjectType(Enum): @@ -368,7 +376,13 @@ def __new__( instance._spark_named_credential = spark_named_credential # Initialize Readers and Writers from config # and/or provided reader and writer - if reader is None or writer is None: + reader_forced = ( + config.reader_config is not None and config.reader_config.force + ) + writer_forced = ( + config.writer_config is not None and config.writer_config.force + ) + if reader is None or writer is None or reader_forced or writer_forced: # We need a spark because we will initialize readers and writers. # Reuse the process-wide session if one client already built it, # so a Client and a StreamingClient share a single connection. @@ -396,9 +410,7 @@ def __new__( raise ValueError( "Reader config is required when reader is not provided" ) - elif reader is None or ( - config.reader_config is not None and config.reader_config.force - ): + elif reader is None or reader_forced: reader_init = config.reader_config.to_object(spark) # type: ignore else: reader_init = reader @@ -406,9 +418,7 @@ def __new__( raise ValueError( "Writer config is required when writer is not provided" ) - elif writer is None or ( - config.writer_config is not None and config.writer_config.force - ): + elif writer is None or writer_forced: writer_init = config.writer_config.to_object(spark) # type: ignore else: writer_init = writer @@ -716,6 +726,25 @@ def write_dlo_deltas( self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DMO) return self._writer.write_dlo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return] + def write_dmo_deltas( + self, name: str, dataframe: PySparkDataFrame, **kwargs + ) -> StreamingQuery: + """Write a streaming DataFrame of deltas to a DMO in Data Cloud. + + Starts a streaming query that writes each micro-batch to the + target DMO and returns the ``StreamingQuery`` handle; the caller + typically calls ``query.awaitTermination()``. + + Args: + name: The name of the DMO to write to. + dataframe: The streaming PySpark DataFrame to write. + + Returns: + The started ``StreamingQuery``. + """ + self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DLO) + return self._writer.write_dmo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return] + def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None: """Write a PySpark DataFrame to a DLO in Data Cloud automatically picking the WriteMode. diff --git a/src/datacustomcode/config.yaml b/src/datacustomcode/config.yaml index e9a8a617..e9da8528 100644 --- a/src/datacustomcode/config.yaml +++ b/src/datacustomcode/config.yaml @@ -18,6 +18,8 @@ spark_config: spark.submit.deployMode: client spark.sql.execution.arrow.pyspark.enabled: 'true' spark.driver.extraJavaOptions: -Djava.security.manager=allow + # Resolve columns case-sensitively so wrong-case refs fail locally too. + spark.sql.caseSensitive: 'true' einstein_predictions_config: type_config_name: DefaultEinsteinPredictions diff --git a/src/datacustomcode/constants.py b/src/datacustomcode/constants.py index fe29a5cf..23b139d3 100644 --- a/src/datacustomcode/constants.py +++ b/src/datacustomcode/constants.py @@ -46,8 +46,9 @@ SCRIPT_USE_IN_FEATURE_STREAMING, ] -# Pydantic request/response type names to feature names +# (request type name, response type name) pair to feature name REQUEST_TYPE_TO_FEATURE = { - "SearchIndexChunkingV1Request": "SearchIndexChunking", - "SearchIndexChunkingV1Response": "SearchIndexChunking", + ("SearchIndexChunkingV1Request", "SearchIndexChunkingV1Response"): ( + "SearchIndexChunking" + ), } diff --git a/src/datacustomcode/deploy.py b/src/datacustomcode/deploy.py index 18a4f863..c0646ce1 100644 --- a/src/datacustomcode/deploy.py +++ b/src/datacustomcode/deploy.py @@ -95,15 +95,35 @@ def infer_use_in_feature(entrypoint_path: str) -> Union[str, None]: if not request_type_name or not response_type_name: return None - # Look up features for both types - request_feature = REQUEST_TYPE_TO_FEATURE.get(request_type_name) - response_feature = REQUEST_TYPE_TO_FEATURE.get(response_type_name) + return REQUEST_TYPE_TO_FEATURE.get((request_type_name, response_type_name)) - # Both must be present and must match - if request_feature and response_feature and request_feature == response_feature: - return request_feature - return None +def describe_supported_signatures(entrypoint_path: str) -> str: + """Build a contract-mismatch hint based on the function's feature type. + + If the request or response type belongs to a known feature, only that + feature's expected pair is listed; otherwise all supported pairs are. + Each pair is followed by the use_in_feature it maps to, e.g. + ``Req/Resp for use_in_feature: SearchIndexChunking``. + """ + from datacustomcode.function_utils import inspect_function_types_static + + request_type_name, response_type_name = inspect_function_types_static( + entrypoint_path + ) + supported = list(REQUEST_TYPE_TO_FEATURE.items()) + sharing_a_type = [ + ((expected_request, expected_response), feature) + for (expected_request, expected_response), feature in supported + if request_type_name == expected_request + or response_type_name == expected_response + ] + # Narrow the hint only when the detected types point at a single feature + to_show = sharing_a_type if len(sharing_a_type) == 1 else supported + return " or ".join( + f"{expected_request}/{expected_response} for use_in_feature: {feature}" + for (expected_request, expected_response), feature in to_show + ) class CodeExtensionMetadata(BaseModel): @@ -415,13 +435,7 @@ def is_streaming(self) -> bool: def _validate_layers(self) -> "DataTransformConfig": read_is_dlo = isinstance(self.permissions.read, DloPermission) write_is_dlo = isinstance(self.permissions.write, DloPermission) - if self.is_streaming: - if not write_is_dlo: - raise ValueError( - "A streaming transform must write to a DLO " - "(permissions.write must be a 'dlo' entry)." - ) - elif read_is_dlo != write_is_dlo: + if read_is_dlo != write_is_dlo: raise ValueError( "permissions.read and permissions.write must both reference " "DLOs or both reference DMOs (got " @@ -551,15 +565,13 @@ def create_data_transform( "version": "56.0", } - # outputDataObjects is only set for DMO-backed transforms. The server requires - # the schema of any DMO created/updated by the transform; DLO transforms use - # an existing materialized table and must not include this field. - if isinstance(data_transform_config.permissions.write, DmoPermission): - if not data_transform_config.dataObjects: + if not data_transform_config.dataObjects: + if isinstance(data_transform_config.permissions.write, DmoPermission): raise ValueError( "DMO transforms require 'dataObjects' in config.json describing " "the schema of each output DMO." ) + else: definition["outputDataObjects"] = [ _data_object_to_output(obj) for obj in data_transform_config.dataObjects ] @@ -632,12 +644,15 @@ def zip( logger.debug(f"Zipping directory... {directory}") with zipfile.ZipFile(ZIP_FILE_NAME, "w", zipfile.ZIP_DEFLATED) as zipf: - for root, dirs, files in os.walk(directory): - # Skip .DS_Store and local credentials. + for root, dirs, files in os.walk(directory, followlinks=False): + # Skip symlinks, .DS_Store and local credentials. for file in files: + abs_path = os.path.join(root, file) + arcname = os.path.relpath(abs_path, directory) + if os.path.islink(abs_path): + logger.warning(f"Skipping symlink file {arcname}") + continue if file not in EXCLUDED_FILES: - abs_path = os.path.join(root, file) - arcname = os.path.relpath(abs_path, directory) zipf.write(abs_path, arcname) logger.debug(f"Created zip file: {ZIP_FILE_NAME}") diff --git a/src/datacustomcode/io/cdf.py b/src/datacustomcode/io/cdf.py new file mode 100644 index 00000000..cd049be2 --- /dev/null +++ b/src/datacustomcode/io/cdf.py @@ -0,0 +1,34 @@ +# 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. + +from __future__ import annotations + +from typing import Final + +from datacustomcode.io.writer.base import MERGE_RECORD_TYPE_COLUMN, MergeRecordType + +COMMIT_VERSION: Final = "_commit_version" +COMMIT_TIMESTAMP: Final = "_commit_timestamp" +MERGE_RECORD_TYPE: Final = MERGE_RECORD_TYPE_COLUMN + +CDF_METADATA_COLUMNS: Final = (COMMIT_VERSION, COMMIT_TIMESTAMP, MERGE_RECORD_TYPE) + +__all__ = [ + "COMMIT_VERSION", + "COMMIT_TIMESTAMP", + "MERGE_RECORD_TYPE", + "CDF_METADATA_COLUMNS", + "MergeRecordType", +] diff --git a/src/datacustomcode/io/reader/local_deltas.py b/src/datacustomcode/io/reader/local_deltas.py new file mode 100644 index 00000000..18460dd1 --- /dev/null +++ b/src/datacustomcode/io/reader/local_deltas.py @@ -0,0 +1,164 @@ +# 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. + +from __future__ import annotations + +import json +import logging +from pathlib import Path +import sys +from typing import ( + TYPE_CHECKING, + Optional, + Union, +) + +from datacustomcode.config import config +from datacustomcode.io import cdf +from datacustomcode.io.reader.base import BaseDataCloudReader +from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader + +if TYPE_CHECKING: + from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession + from pyspark.sql.types import AtomicType, StructType + +logger = logging.getLogger(__name__) + + +class LocalDeltasReader(BaseDataCloudReader): + """Local reader for streaming transforms""" + + CONFIG_NAME = "LocalDeltasReader" + + def __init__( + self, + spark: SparkSession, + credentials_profile: str = "default", + dataspace: Optional[str] = None, + sf_cli_org: Optional[str] = None, + default_row_limit: Optional[int] = None, + fixtures_root: str = "payload/streaming_fixtures", + ) -> None: + super().__init__(spark) + self._fixtures_root = Path(fixtures_root) + self._credentials_profile = credentials_profile + self._dataspace = dataspace + self._sf_cli_org = sf_cli_org + # Reuse the batch reader for INITIAL_SYNC / REBUILD reads. + self._batch = QueryAPIDataCloudReader( + spark=spark, + credentials_profile=credentials_profile, + dataspace=dataspace, + sf_cli_org=sf_cli_org, + default_row_limit=default_row_limit, + ) + self._current_layer = "dlo" + + def read_dlo( + self, + name: str, + schema: Union[AtomicType, StructType, str, None] = None, + ) -> PySparkDataFrame: + return self._batch.read_dlo(name, schema) + + def read_dmo( + self, + name: str, + schema: Union[AtomicType, StructType, str, None] = None, + ) -> PySparkDataFrame: + return self._batch.read_dmo(name, schema) + + def read_dlo_deltas(self) -> PySparkDataFrame: + self._current_layer = "dlo" + return self._open_stream(self._streaming_source()) + + def read_dmo_deltas(self) -> PySparkDataFrame: + self._current_layer = "dmo" + return self._open_stream(self._streaming_source()) + + def _streaming_source(self) -> str: + source = config.streaming_source + if not source: + raise RuntimeError( + "No streaming source configured. Set streamingSource.name in " + "config.json." + ) + return source + + def _open_stream(self, name: str) -> PySparkDataFrame: + drop_dir = self._fixtures_root / name + + if not (drop_dir / "_schema.json").exists(): + seeded = self._try_seed(name) + if not seeded: + print( + f"\nStreaming source {self._current_layer}='{name}' is " + f"empty.\n" + f" Populate the stream source with at least one row in " + f"Data Cloud, then re-run `datacustomcode run`.\n" + ) + sys.exit(0) + + print( + f"\nWrote sample streaming fixture in: {drop_dir} " + f"based on the contents of the streaming source {name}.\n" + f" You may add more JSON files alongside it to simulate " + f"additional changes.\n" + ) + + schema = self._build_stream_schema(name) + return ( + self.spark.readStream.format("json") + .schema(schema) + .option("maxFilesPerTrigger", 1) # one file = one batch + .option("latestFirst", "false") # oldest mtime first + .load(str(drop_dir)) + ) + + def _build_stream_schema(self, name: str) -> "StructType": + """Compose (source schema + CDF metadata columns) for readStream.""" + from pyspark.sql.types import ( + LongType, + StringType, + StructField, + StructType, + TimestampType, + ) + + source_schema = self._resolve_source_schema(name) + cdf_fields = [ + StructField(cdf.COMMIT_VERSION, LongType(), True), + StructField(cdf.COMMIT_TIMESTAMP, TimestampType(), True), + StructField(cdf.MERGE_RECORD_TYPE, StringType(), True), + ] + return StructType(list(source_schema.fields) + cdf_fields) + + def _resolve_source_schema(self, name: str) -> "StructType": + from pyspark.sql.types import StructType + + schema_file = self._fixtures_root / name / "_schema.json" + return StructType.fromJson(json.loads(schema_file.read_text())) + + def _try_seed(self, name: str) -> bool: + """Creates source schema and sample change file.""" + from datacustomcode.io.reader.streaming_seeder import StreamingSourceSeeder + + seeder = StreamingSourceSeeder( + spark=self.spark, + credentials_profile=self._credentials_profile, + dataspace=self._dataspace, + sf_cli_org=self._sf_cli_org, + ) + return seeder.seed_source(name, self._current_layer, str(self._fixtures_root)) diff --git a/src/datacustomcode/io/reader/streaming_seeder.py b/src/datacustomcode/io/reader/streaming_seeder.py new file mode 100644 index 00000000..9ca19f41 --- /dev/null +++ b/src/datacustomcode/io/reader/streaming_seeder.py @@ -0,0 +1,114 @@ +# 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. + +from __future__ import annotations + +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Optional, +) + +from datacustomcode.io import cdf +from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader + +if TYPE_CHECKING: + import pandas as pd + from pyspark.sql import SparkSession + +SEED_LIMIT = 10 + + +def _clean_for_json(value: Any) -> Any: + if isinstance(value, float): + if math.isnan(value): + return None + if value.is_integer(): + return int(value) + return value + + +class StreamingSourceSeeder: + def __init__( + self, + spark: SparkSession, + credentials_profile: str = "default", + dataspace: Optional[str] = None, + sf_cli_org: Optional[str] = None, + ) -> None: + self.spark = spark + self.reader = QueryAPIDataCloudReader( + spark=spark, + credentials_profile=credentials_profile, + dataspace=dataspace, + sf_cli_org=sf_cli_org, + ) + + def seed_source(self, name: str, layer: str, fixtures_root: str) -> bool: + """Seed streaming fixtures and source schema. + + Returns: + ``True`` when schema + fixtures are written + ``False`` when the source is empty. + Query API errors (missing creds, missing + source) propagate as ``RuntimeError``. + """ + read_fn = self.reader.read_dlo if layer == "dlo" else self.reader.read_dmo + + try: + head_df = read_fn(name).limit(1) + except Exception as exc: + raise RuntimeError(f"Failed to read {layer}='{name}': {exc}.") from exc + + head_pandas = head_df.toPandas() + if len(head_pandas) == 0: + return False + + schema = head_df.schema + out_dir = Path(fixtures_root) / name + out_dir.mkdir(parents=True, exist_ok=True) + schema_file_path = out_dir / "_schema.json" + schema_file_path.write_text(json.dumps(schema.jsonValue())) + print( + f"\nStreaming source schema written to {schema_file_path} " + f"({len(schema.fields)} fields)" + ) + + # Mix UPSERT and DELETE in the seed so the customer sees both + # operation types in the starter fixture. Annotated because + # pyspark's ``.toPandas()`` return type is ``PandasDataFrameLike``, + # which mypy doesn't recognize as having ``to_dict``. + snapshot: pd.DataFrame = read_fn(name).limit(SEED_LIMIT).toPandas() + seed_rows = [] + for i, record in enumerate(snapshot.to_dict("records")): + op = cdf.MergeRecordType.DELETE if i % 2 else cdf.MergeRecordType.UPSERT + + cleaned = {k: _clean_for_json(v) for k, v in record.items()} + seed_rows.append( + { + **cleaned, + cdf.COMMIT_VERSION: i + 1, + cdf.COMMIT_TIMESTAMP: datetime.now(timezone.utc).isoformat(), + cdf.MERGE_RECORD_TYPE: op.value, + } + ) + (out_dir / "000_seed.json").write_text( + "\n".join(json.dumps(r, default=str) for r in seed_rows) + ) + return True diff --git a/src/datacustomcode/io/writer/base.py b/src/datacustomcode/io/writer/base.py index d24a33b9..56b89f9f 100644 --- a/src/datacustomcode/io/writer/base.py +++ b/src/datacustomcode/io/writer/base.py @@ -87,7 +87,7 @@ def write_dlo_deltas( Args: name: Target Data Lake Object name. dataframe: Streaming PySpark DataFrame produced from a - ``read_dlo_deltas`` / ``read_dmo_deltas`` source. + ``read_dlo_deltas`` source. Returns: The started ``StreamingQuery``; the caller drives its lifecycle @@ -102,3 +102,35 @@ def write_dlo_deltas( "streaming runtime; the local writer does not support streaming " "deltas." ) + + def write_dmo_deltas( + self, name: str, dataframe: PySparkDataFrame + ) -> StreamingQuery: + """Write a streaming DataFrame of deltas to a Data Model Object. + + Streaming counterpart to :meth:`write_to_dmo`. Starts a streaming query + that writes each micro-batch to the target DMO via the Data Cloud + streaming sink and returns the resulting ``StreamingQuery`` handle. The + runtime owns the trigger and checkpoint location; callers pass only the + table name. Concrete streaming behavior is provided by the deployed + Data Cloud runtime; the base implementation raises + :class:`NotImplementedError`. + + Args: + name: Target Data Model Object name. + dataframe: Streaming PySpark DataFrame produced from a + ``read_dmo_deltas`` source. + + Returns: + The started ``StreamingQuery``; the caller drives its lifecycle + (typically ``query.awaitTermination()``). + + Raises: + NotImplementedError: If the active writer does not support streaming + deltas (e.g. the local development writers). + """ + raise NotImplementedError( + "write_dmo_deltas is only supported when running in the Data Cloud " + "streaming runtime; the local writer does not support streaming " + "deltas." + ) diff --git a/src/datacustomcode/io/writer/local_deltas.py b/src/datacustomcode/io/writer/local_deltas.py new file mode 100644 index 00000000..49230c25 --- /dev/null +++ b/src/datacustomcode/io/writer/local_deltas.py @@ -0,0 +1,133 @@ +# 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. + +from __future__ import annotations + +import os +import tempfile +from typing import TYPE_CHECKING, Optional +from urllib.parse import urlparse + +from datacustomcode.io import cdf +from datacustomcode.io.writer.base import BaseDataCloudWriter, WriteMode + +if TYPE_CHECKING: + from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession + from pyspark.sql.streaming import StreamingQuery + +_HEADER_WARNING = ( + " NOTE: The output below is based on example streaming changes " + "auto-generated by this CLI or generated by the user.\n" + " Once this code extension is deployed, Data Cloud will persist " + "only the final state per primary key.\n" + " This local preview shows every emitted row uncollapsed." +) + + +class LocalDeltasWriter(BaseDataCloudWriter): + """Local writer for streaming transforms.""" + + CONFIG_NAME = "LocalDeltasWriter" + + def __init__( + self, + spark: SparkSession, + credentials_profile: str = "default", + dataspace: Optional[str] = None, + sf_cli_org: Optional[str] = None, + ) -> None: + super().__init__(spark) + + from datacustomcode.io.writer.print import PrintDataCloudWriter + + self._batch_writer = PrintDataCloudWriter( + spark=spark, + credentials_profile=credentials_profile, + dataspace=dataspace, + sf_cli_org=sf_cli_org, + ) + + def write_to_dlo( + self, name: str, dataframe: PySparkDataFrame, write_mode: WriteMode + ) -> None: + return self._batch_writer.write_to_dlo(name, dataframe, write_mode) + + def write_to_dmo( + self, name: str, dataframe: PySparkDataFrame, write_mode: WriteMode + ) -> None: + return self._batch_writer.write_to_dmo(name, dataframe, write_mode) + + def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None: + return self._batch_writer.auto_write_to_dlo(name, dataframe) + + def auto_write_to_dmo(self, name: str, dataframe: PySparkDataFrame) -> None: + return self._batch_writer.auto_write_to_dmo(name, dataframe) + + @staticmethod + def _batch_source_file(batch_df: "PySparkDataFrame") -> str: + """Return the fixture file backing this micro-batch, relative to CWD""" + from pyspark.sql import functions as F + + file_row = batch_df.select(F.input_file_name().alias("_src")).limit(1).collect() + if not file_row: + return "?" + abs_path = str(urlparse(str(file_row[0]["_src"])).path) + try: + return os.path.relpath(abs_path) + except Exception: + return abs_path + + def write_dlo_deltas( + self, name: str, dataframe: PySparkDataFrame, **kwargs + ) -> StreamingQuery: + if not name: + raise ValueError("DLO name must be provided.") + + def _preview(batch_df, batch_id): + from pyspark.sql import functions as F + + source_file = self._batch_source_file(batch_df) + + output_batch = batch_df.withColumn( + "_operation", + F.when( + F.col(cdf.MERGE_RECORD_TYPE) == cdf.MergeRecordType.DELETE.value, + F.lit("DELETE"), + ).otherwise(F.lit("UPSERT")), + ).drop( + cdf.COMMIT_VERSION, + cdf.COMMIT_TIMESTAMP, + cdf.MERGE_RECORD_TYPE, + ) + + row_count = output_batch.count() + print( + f"\nTarget={name} batch_id={batch_id} " + f"file={source_file} rows={row_count}" + ) + print(_HEADER_WARNING) + output_batch.show(truncate=False) + + checkpoint_dir = tempfile.mkdtemp(prefix=f"local-deltas-ckpt-{name}-") + return ( + dataframe.writeStream.foreachBatch(_preview) + .option("checkpointLocation", checkpoint_dir) + # AvailableNow: drain every fixture file then + # terminate. The user's `query.awaitTermination()` + # returns without needing a timeout, so + # `datacustomcode run` exits deterministically. + .trigger(availableNow=True) + .start() + ) diff --git a/src/datacustomcode/lineage/__init__.py b/src/datacustomcode/lineage/__init__.py new file mode 100644 index 00000000..cf96819e --- /dev/null +++ b/src/datacustomcode/lineage/__init__.py @@ -0,0 +1,137 @@ +# 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. +"""Generate config.json ``dataLineage`` by tracing a script's Spark plans.""" + +from __future__ import annotations + +import builtins +import json +import os +import subprocess +import sys +import tempfile +from typing import ( + Any, + Dict, + NoReturn, + Optional, + Sequence, +) + +from datacustomcode.lineage.capture import ( + LineageCaptureReader, + LineageCaptureWriter, + LineageCollector, + LineageResult, + install_capture, +) +from datacustomcode.lineage.tracer import LineageTraceError + +__all__ = [ + "LineageCaptureReader", + "LineageCaptureWriter", + "LineageCollector", + "LineageResult", + "LineageTraceError", + "generate_lineage", + "install_capture", +] + + +def generate_lineage( + entrypoint: str, + config_file: Optional[str] = None, + dependencies: Sequence[str] = (), + profile: str = "default", + sf_cli_org: Optional[str] = None, +) -> LineageResult: + """Run a script entrypoint and return the field-level lineage it produces. + + The entrypoint runs exactly as with ``run`` (same config resolution, reader + and credentials), except that writes are traced instead of performed. It runs + in a fresh Python process, so no client or config from the caller's process + leaks into the capture. The process inherits this one's working directory, + environment, ``sys.path`` and stdout/stderr. + + Args: + entrypoint: The script entrypoint to run. + config_file: Optional SDK config file, as for ``run``. + dependencies: Modules to import before running, as for ``run``. + profile: The credentials profile to use. + sf_cli_org: Optional SF CLI org alias or username. + + Returns: + The captured :class:`LineageResult`. + + Raises: + ValueError: If the package is not a batch script. + Exception: Whatever the run raised, re-raised as the same built-in + exception type or :class:`LineageTraceError`, else ``RuntimeError``. + """ + with tempfile.TemporaryDirectory(prefix="datacustomcode-lineage-") as tmp: + request_file = os.path.join(tmp, "request.json") + response_file = os.path.join(tmp, "response.json") + with open(request_file, "w", encoding="utf-8") as f: + json.dump( + { + "args": { + "entrypoint": entrypoint, + "config_file": config_file, + "dependencies": list(dependencies), + "profile": profile, + "sf_cli_org": sf_cli_org, + }, + "response_file": response_file, + }, + f, + ) + # The worker sees the same modules this process does + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path) + completed = subprocess.run( + [sys.executable, "-m", "datacustomcode.lineage._worker", request_file], + env=env, + check=False, + ) + if not os.path.exists(response_file): + raise RuntimeError( + f"Lineage generation exited with code {completed.returncode} " + "without a result" + ) + with open(response_file, encoding="utf-8") as f: + response = json.load(f) + if "error" in response: + _raise(response["error"]) + return LineageResult.from_dict(response["result"]) + + +def _raise(error: Dict[str, Any]) -> NoReturn: + """Re-raise an error reported by the worker as the closest local type.""" + message = error["message"] + if error["type"] == LineageTraceError.__name__: + raise LineageTraceError(message) + exc_type = getattr(builtins, error["type"], None) + if ( + error["module"] == "builtins" + and isinstance(exc_type, type) + and issubclass(exc_type, Exception) + ): + try: + exc = exc_type(message) + except TypeError: # e.g. UnicodeDecodeError takes more arguments + pass + else: + raise exc + raise RuntimeError(f"{error['module']}.{error['type']}: {message}") diff --git a/src/datacustomcode/lineage/_worker.py b/src/datacustomcode/lineage/_worker.py new file mode 100644 index 00000000..62d15f76 --- /dev/null +++ b/src/datacustomcode/lineage/_worker.py @@ -0,0 +1,97 @@ +# 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. +"""Runs one lineage capture in a fresh process, for ``generate_lineage``. + +Usage: ``python -m datacustomcode.lineage._worker ``. The request +holds the ``run_capture`` arguments and the path of a response file, which gets +either ``{"result": LineageResult.to_dict()}`` or +``{"error": {"module", "type", "message"}}``. The response goes to a file rather +than stdout because the entrypoint prints freely to stdout. +""" + +from __future__ import annotations + +import json +import sys +import traceback +from typing import ( + List, + Optional, + Sequence, +) + +from datacustomcode.lineage.capture import ( + LineageCollector, + LineageResult, + install_capture, +) + + +def run_capture( + entrypoint: str, + config_file: Optional[str], + dependencies: Sequence[str], + profile: str, + sf_cli_org: Optional[str], +) -> LineageResult: + """Run the entrypoint with capture installed. Call only in a fresh process.""" + from datacustomcode.run import ( + execute_entrypoint, + import_dependencies, + prepare_run, + ) + + # Dependencies are imported after capture is installed, so a Client they + # create at import time is captured too + context = prepare_run(entrypoint, config_file, [], profile, sf_cli_org) + if context.package_type != "script": + raise ValueError( + f"Lineage can only be generated for script packages, not " + f"{context.package_type} packages" + ) + if context.config_json.get("streamingSource"): + raise ValueError("Lineage generation does not support streaming scripts") + + collector = LineageCollector() + install_capture(collector) + import_dependencies(list(dependencies)) + execute_entrypoint(entrypoint, context) + return collector.result() + + +def main(argv: List[str]) -> int: + with open(argv[0], encoding="utf-8") as f: + request = json.load(f) + try: + result = run_capture(**request["args"]) + response: dict = {"result": result.to_dict()} + except Exception as exc: + # The caller re-raises from the response; the traceback is for the + # customer, pointing into their entrypoint + traceback.print_exc() + response = { + "error": { + "module": type(exc).__module__, + "type": type(exc).__name__, + "message": str(exc), + } + } + with open(request["response_file"], "w", encoding="utf-8") as f: + json.dump(response, f) + return 1 if "error" in response else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/datacustomcode/lineage/capture.py b/src/datacustomcode/lineage/capture.py new file mode 100644 index 00000000..404205f3 --- /dev/null +++ b/src/datacustomcode/lineage/capture.py @@ -0,0 +1,289 @@ +# 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. +"""Readers and writers that record lineage instead of writing data. + +:func:`install_capture` replaces the configured reader and writer with forced +configs for :class:`LineageCaptureReader` and :class:`LineageCaptureWriter`, so +every client built afterwards uses them, even one passed its own +``Client(reader=..., writer=...)``. The wrappers delegate to the reader/writer +the config resolved, so the customer's reader choice and credentials still +apply: reads go through the delegate and are registered as lineage sources, +writes are validated through the delegate (when it supports it), traced, and +never written. + +Forcing config only reaches clients built after it, so capture runs in a fresh +process (see :mod:`datacustomcode.lineage._worker`), where no client exists yet. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Union, +) + +from datacustomcode.io.reader.base import BaseDataCloudReader +from datacustomcode.io.writer.base import ( + MERGE_RECORD_TYPE_COLUMN, + BaseDataCloudWriter, + WriteMode, +) +from datacustomcode.lineage.tracer import SourceRegistry, TraceResult + +if TYPE_CHECKING: + from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession + from pyspark.sql.types import AtomicType, StructType + + from datacustomcode.config import AccessLayerObjectConfig + + +@dataclass +class LineageResult: + """Field-level lineage captured from one run of an entrypoint. + + Attributes: + data_lineage: Target field to its sorted source fields. + unresolved: Target field to the reason its lineage could not be traced. + no_sources: Target fields computed from no source field (e.g. literals). + udf_fields: Target fields in ``data_lineage`` or ``no_sources`` computed + by a user-defined function, whose sources may be incomplete. + targets: Objects written. + sources: Objects read. + """ + + data_lineage: Dict[str, List[str]] = field(default_factory=dict) + unresolved: Dict[str, str] = field(default_factory=dict) + no_sources: List[str] = field(default_factory=list) + udf_fields: List[str] = field(default_factory=list) + targets: List[str] = field(default_factory=list) + sources: List[str] = field(default_factory=list) + + @property + def pair_count(self) -> int: + """Number of (target, source) field pairs in ``data_lineage``.""" + return sum(len(sources) for sources in self.data_lineage.values()) + + def to_dict(self) -> Dict[str, Any]: + """Deterministic JSON-ready form; ``dataLineage`` matches config.json.""" + return { + "dataLineage": [ + {"targetField": target, "sourceFields": self.data_lineage[target]} + for target in sorted(self.data_lineage) + ], + "unresolved": [ + {"targetField": target, "reason": self.unresolved[target]} + for target in sorted(self.unresolved) + ], + "noSources": sorted(self.no_sources), + "udfFields": sorted(self.udf_fields), + "targets": sorted(self.targets), + "sources": sorted(self.sources), + "pairCount": self.pair_count, + } + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> LineageResult: + """Inverse of :meth:`to_dict`.""" + return cls( + data_lineage={ + entry["targetField"]: list(entry["sourceFields"]) + for entry in data["dataLineage"] + }, + unresolved={ + entry["targetField"]: entry["reason"] for entry in data["unresolved"] + }, + no_sources=list(data["noSources"]), + udf_fields=list(data["udfFields"]), + targets=list(data["targets"]), + sources=list(data["sources"]), + ) + + +class LineageCollector: + """Accumulates sources read and target fields written during a run.""" + + def __init__(self) -> None: + self.registry = SourceRegistry() + self._targets: Dict[str, Dict[str, TraceResult]] = {} + + def record_read(self, object_name: str, dataframe: PySparkDataFrame) -> None: + self.registry.register(dataframe, object_name) + + def record_write(self, object_name: str, dataframe: PySparkDataFrame) -> None: + fields = self._targets.setdefault(object_name, {}) + for column, traced in self.registry.trace(dataframe).items(): + if column == MERGE_RECORD_TYPE_COLUMN: + continue + # Repeat writes to the same target: a field reads from the union of + # every write, stays unresolved if any write was unresolved, and is + # UDF-computed if any write computed it with a UDF + previous = fields.get(column) + if previous is None or (traced.unresolved and not previous.unresolved): + fields[column] = traced + elif not previous.unresolved: + fields[column] = TraceResult( + sources=previous.sources | traced.sources, + udf=previous.udf or traced.udf, + ) + + def result(self) -> LineageResult: + result = LineageResult( + targets=list(self._targets), sources=list(self.registry.objects) + ) + for object_name, fields in self._targets.items(): + for column, traced in fields.items(): + target = f"{object_name}.{column}" + if traced.reason is not None: + result.unresolved[target] = traced.reason + continue + if traced.sources: + result.data_lineage[target] = sorted(traced.sources) + else: + result.no_sources.append(target) + if traced.udf: + result.udf_fields.append(target) + return result + + +class _Delegating: + """Falls back to the delegate for attributes the capture class lacks.""" + + _delegate: Any + + def __getattr__(self, item: str) -> Any: + if item == "_delegate": + raise AttributeError(item) + return getattr(self._delegate, item) + + +class LineageCaptureReader(_Delegating, BaseDataCloudReader): + """Reads through the configured reader and registers lineage sources.""" + + CONFIG_NAME = "LineageCaptureReader" + + def __init__( + self, + spark: SparkSession, + delegate_config: AccessLayerObjectConfig[BaseDataCloudReader], + collector: LineageCollector, + ) -> None: + super().__init__(spark) + self._delegate = delegate_config.to_object(spark) + self._collector = collector + + def read_dlo( + self, + name: str, + schema: Union[AtomicType, StructType, str, None] = None, + ) -> PySparkDataFrame: + dataframe: PySparkDataFrame = ( + self._delegate.read_dlo(name) + if schema is None + else self._delegate.read_dlo(name, schema) + ) + self._collector.record_read(name, dataframe) + return dataframe + + def read_dmo( + self, + name: str, + schema: Union[AtomicType, StructType, str, None] = None, + ) -> PySparkDataFrame: + dataframe: PySparkDataFrame = ( + self._delegate.read_dmo(name) + if schema is None + else self._delegate.read_dmo(name, schema) + ) + self._collector.record_read(name, dataframe) + return dataframe + + +class LineageCaptureWriter(_Delegating, BaseDataCloudWriter): + """Traces DataFrames handed to the writer; never writes or shows them.""" + + CONFIG_NAME = "LineageCaptureWriter" + + def __init__( + self, + spark: SparkSession, + delegate_config: AccessLayerObjectConfig[BaseDataCloudWriter], + collector: LineageCollector, + ) -> None: + super().__init__(spark) + self._delegate = delegate_config.to_object(spark) + self._collector = collector + + def _validate_dlo(self, name: str, dataframe: PySparkDataFrame) -> None: + # Same column check `run` does, so lineage never names a missing field + validate = getattr( + self._delegate, "validate_dataframe_columns_against_dlo", None + ) + if validate is not None: + validate(dataframe, name) + + def write_to_dlo( + self, + name: str, + dataframe: PySparkDataFrame, + write_mode: WriteMode, + **kwargs: Any, + ) -> None: + self.auto_write_to_dlo(name, dataframe) + + def write_to_dmo( + self, + name: str, + dataframe: PySparkDataFrame, + write_mode: WriteMode, + **kwargs: Any, + ) -> None: + self.auto_write_to_dmo(name, dataframe) + + def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None: + self._validate_dlo(name, dataframe) + self._collector.record_write(name, dataframe) + + def auto_write_to_dmo(self, name: str, dataframe: PySparkDataFrame) -> None: + self._collector.record_write(name, dataframe) + + +def install_capture(collector: LineageCollector) -> None: + """Force every client built from now on to capture lineage into ``collector``. + + Wraps the current ``config.reader_config`` and ``config.writer_config`` (as + resolved by ``prepare_run``) in forced capture configs. Clients that already + exist are not affected, which is why capture runs in a fresh process. + + Raises: + ValueError: If no reader or writer is configured. + """ + from datacustomcode.config import AccessLayerObjectConfig, config + + if config.reader_config is None or config.writer_config is None: + raise ValueError("Lineage generation needs a reader_config and writer_config") + config.reader_config = AccessLayerObjectConfig( + type_config_name=LineageCaptureReader.CONFIG_NAME, + options={"delegate_config": config.reader_config, "collector": collector}, + force=True, + ) + config.writer_config = AccessLayerObjectConfig( + type_config_name=LineageCaptureWriter.CONFIG_NAME, + options={"delegate_config": config.writer_config, "collector": collector}, + force=True, + ) diff --git a/src/datacustomcode/lineage/tracer.py b/src/datacustomcode/lineage/tracer.py new file mode 100644 index 00000000..3d147c8c --- /dev/null +++ b/src/datacustomcode/lineage/tracer.py @@ -0,0 +1,566 @@ +# 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. +"""Column-level lineage tracing over a DataFrame's analyzed logical plan. + +Every column in a Spark plan is an attribute with a unique ``exprId``. Walking the +analyzed plan bottom-up, each attribute is resolved to the set of *leaf columns* +it is computed from, where a leaf column is ``(leaf relation identity, position)``. + +Leaf identity (rather than ``exprId``) is what makes self-joins traceable: Spark +re-aliases one side of a self-join to fresh ``exprId`` values, but both sides +still sit on the same underlying RDD / local data. + +Only the columns that feed a column's *value* are sources. Columns that only +decide which rows, groups or branch are used are deliberately ignored, wherever +they appear: filter predicates, join conditions, grouping and sort keys, window +partition/order keys, ``CASE WHEN``/``IF`` conditions and aggregate ``FILTER`` +clauses. A value computed from none of its inputs' values (``row_number()``, +``rank()``, ``count(*)``) therefore has no sources. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import json +from typing import ( + TYPE_CHECKING, + Any, + Dict, + FrozenSet, + Hashable, + Iterator, + List, + Optional, + Set, + Tuple, +) + +if TYPE_CHECKING: + from pyspark.sql import DataFrame as PySparkDataFrame + +LeafColumn = Tuple[Hashable, int] +"""``(leaf relation identity, column position)``.""" + +UNTRACEABLE_SOURCE = "untraceable source" +AMBIGUOUS_SOURCE = "ambiguous source" + +_OUTPUT_SEPARATOR = "\u0001" + +# Expressions that hide the columns they read in a nested plan the JSON does not +# carry, so their inputs cannot be traced +_OPAQUE_EXPRESSIONS = frozenset( + {"ScalarSubquery", "Exists", "ListQuery", "InSubquery", "LateralSubquery"} +) + +# User-defined functions: their arguments are traced, but the body can read data +# the plan does not show (a captured lookup, a broadcast, a file) +_UDF_EXPRESSIONS = frozenset( + { + "PythonUDF", + "PythonUDAF", + "PythonUDTF", + "ScalaUDF", + "ScalaUDAF", + "ScalaAggregator", + } +) + + +# Expressions with children that only decide which rows, groups or branch are used +_ROW_GATING_EXPRESSIONS = frozenset( + {"WindowExpression", "AggregateExpression", "CaseWhen", "If"} +) + + +def _keep_value_children(expr_class: str, position: int, count: int) -> bool: + """Whether child ``position`` of a row-gating expression feeds its value.""" + if expr_class in ("WindowExpression", "AggregateExpression"): + # (function, window spec) / (function, optional FILTER predicate) + return position == 0 + if expr_class == "CaseWhen": + # (cond, value)* then an optional else value + return position % 2 == 1 or (count % 2 == 1 and position == count - 1) + # If: (predicate, true value, false value) + return position != 0 + + +class LineageTraceError(Exception): + """Raised when a DataFrame's plan cannot be traced at all.""" + + +@dataclass(frozen=True) +class ColumnTrace: + """Lineage of one output column. + + Attributes: + name: Output column name. + leaves: Leaf columns the value is computed from. Empty for literals. + opaque_reason: Set when the plan hides this column's inputs (e.g. a + ``mapInPandas`` or subquery); ``leaves`` is then incomplete. + direct: The column is its single leaf column passed through unchanged + (possibly renamed), not computed from it. + udf: The value is computed by a user-defined function, which may read + more than ``leaves``. + """ + + name: str + leaves: FrozenSet[LeafColumn] = field(default_factory=frozenset) + opaque_reason: Optional[str] = None + direct: bool = False + udf: bool = False + + +@dataclass(frozen=True) +class _AttrTrace: + leaves: FrozenSet[LeafColumn] + opaque_reason: Optional[str] = None + direct: bool = False + udf: bool = False + + def merge(self, other: _AttrTrace) -> _AttrTrace: + # A merge combines inputs, so the result is never a direct pass-through + return _AttrTrace( + self.leaves | other.leaves, + self.opaque_reason or other.opaque_reason, + udf=self.udf or other.udf, + ) + + +_EMPTY = _AttrTrace(frozenset()) + + +@dataclass(frozen=True) +class TraceResult: + """Lineage of one output column in terms of registered source fields. + + Attributes: + sources: ``"Object.field"`` names the value is computed from. + reason: Set when the column cannot be fully traced; ``sources`` must + then not be used. + udf: The value is computed by a user-defined function, so ``sources`` + may be incomplete and needs review. + """ + + sources: FrozenSet[str] = field(default_factory=frozenset) + reason: Optional[str] = None + udf: bool = False + + @property + def unresolved(self) -> bool: + return self.reason is not None + + +class SourceRegistry: + """Maps leaf columns of DataFrames read from Data Cloud to their fields. + + Only direct columns name a field: a column a reader computes (e.g. + ``upper(name).alias("normalized")``) does not claim the leaf it reads. A leaf + claimed by two different fields (two direct columns over it, or two objects + read from the same relation) is ambiguous, and so is anything traced to it. + """ + + def __init__(self) -> None: + self._fields: Dict[LeafColumn, str] = {} + self._ambiguous: Set[LeafColumn] = set() + self.objects: List[str] = [] + + def register(self, df: PySparkDataFrame, object_name: str) -> None: + """Record that the direct columns of ``df`` are fields of ``object_name``.""" + for column in trace_columns(df): + if not column.direct: + continue + (leaf,) = column.leaves + field_name = f"{object_name}.{column.name}" + if self._fields.setdefault(leaf, field_name) != field_name: + self._ambiguous.add(leaf) + if object_name not in self.objects: + self.objects.append(object_name) + + def trace(self, df: PySparkDataFrame) -> Dict[str, TraceResult]: + """Resolve each column of ``df`` to the registered fields it reads.""" + results = {} + for column in trace_columns(df): + if column.opaque_reason is not None: + results[column.name] = TraceResult(reason=column.opaque_reason) + elif any(leaf in self._ambiguous for leaf in column.leaves): + results[column.name] = TraceResult(reason=AMBIGUOUS_SOURCE) + elif any(leaf not in self._fields for leaf in column.leaves): + results[column.name] = TraceResult(reason=UNTRACEABLE_SOURCE) + else: + results[column.name] = TraceResult( + sources=frozenset(self._fields[leaf] for leaf in column.leaves), + udf=column.udf, + ) + return results + + +def trace_columns(df: PySparkDataFrame) -> List[ColumnTrace]: + """Trace every output column of ``df`` back to its leaf columns. + + Args: + df: A classic (non Spark Connect) PySpark DataFrame. + + Returns: + One :class:`ColumnTrace` per column of ``df``, in column order. + + Raises: + LineageTraceError: If the plan is not accessible or is malformed. + """ + jdf = getattr(df, "_jdf", None) + if jdf is None: + raise LineageTraceError( + "Lineage tracing requires a classic PySpark DataFrame; Spark Connect " + "DataFrames are not supported." + ) + jvm = df.sparkSession._jvm + jplan = jdf.queryExecution().analyzed() + nodes = json.loads(jplan.toJSON()) + jnodes = _jvm_preorder(jplan) + if len(nodes) != len(jnodes): + raise LineageTraceError( + f"Plan JSON has {len(nodes)} nodes but the plan tree has {len(jnodes)}" + ) + + children = _children_from_preorder(nodes) + outputs = [_parse_output(jnode) for jnode in jnodes] + traces: Dict[int, _AttrTrace] = {} + + # In pre-order every child comes after its parent, so walking backwards + # resolves all children before the node that consumes them + for index in range(len(nodes) - 1, -1, -1): + _trace_node( + nodes[index], + jnodes[index], + outputs[index], + [outputs[c] for c in children[index]], + traces, + jvm, + ) + + root_ids = outputs[0] + if len(root_ids) != len(df.columns): + raise LineageTraceError( + f"Plan output has {len(root_ids)} columns but the DataFrame has " + f"{len(df.columns)}" + ) + columns = [] + for name, expr_id in zip(df.columns, root_ids, strict=False): + trace = traces.get(expr_id, _EMPTY) + columns.append( + ColumnTrace( + name, trace.leaves, trace.opaque_reason, trace.direct, trace.udf + ) + ) + return columns + + +def _trace_node( + node: dict, + jnode: Any, + output: List[int], + child_outputs: List[List[int]], + traces: Dict[int, _AttrTrace], + jvm: Any, +) -> None: + node_class = node["class"].rsplit(".", 1)[-1] + + if not child_outputs: + key = _leaf_key(jnode, node_class, jvm) + for position, expr_id in enumerate(output): + traces[expr_id] = _AttrTrace(frozenset({(key, position)}), direct=True) + return + + if node_class == "Union": + # Union reuses child 0's exprIds; merge every child positionally into them + for position, expr_id in enumerate(output): + merged = _EMPTY + for child in child_outputs: + if position < len(child): + merged = merged.merge(traces.get(child[position], _EMPTY)) + traces[expr_id] = merged + elif node_class == "Expand": + for position, expr_id in enumerate(output): + merged = _EMPTY + for projection in node.get("projections", []): + if position < len(projection): + merged = merged.merge( + _trace_expression(projection[position], traces) + ) + traces[expr_id] = merged + elif node_class == "Generate": + generated = [ + _expr_id(attr) + for attr_list in node.get("generatorOutput", []) + for attr in attr_list + ] + per_output = _trace_generator(node.get("generator", []), len(generated), traces) + for expr_id, trace in zip(generated, per_output, strict=True): + traces[expr_id] = trace + else: + for expression in _expression_trees(node): + _trace_aliases(expression, traces) + + for expr_id in output: + if expr_id not in traces: + traces[expr_id] = _AttrTrace( + frozenset(), f"columns produced by {node_class} cannot be traced" + ) + + +def _trace_aliases(expression: List[dict], traces: Dict[int, _AttrTrace]) -> None: + """Record every Alias in a flattened expression tree as a new attribute.""" + for index, expr_node in enumerate(expression): + if expr_node["class"].endswith(".Alias"): + child = expression[index + 1 : _subtree_end(expression, index)] + if ( + len(child) == 1 + and child[0]["class"].endswith(".AttributeReference") + and _expr_id(child[0]) in traces + ): + # A rename keeps the column a direct pass-through + traces[_expr_id(expr_node)] = traces[_expr_id(child[0])] + else: + traces[_expr_id(expr_node)] = _trace_expression(child, traces) + + +def _trace_generator( + generator: List[dict], output_count: int, traces: Dict[int, _AttrTrace] +) -> List[_AttrTrace]: + """Trace each output of a Generate node's generator expression. + + Outputs are traced individually where the generator's shape says which + input feeds which output. Otherwise they share the input's trace only when + that input is a source column passed through unchanged: a computed input + (e.g. ``map('key', name)``) can mix literals and columns, and the shared + trace would attribute the literal outputs to the columns. + """ + whole = _trace_expression(generator, traces) + if output_count <= 1 or whole.opaque_reason is not None or not whole.leaves: + return [whole] * output_count + generator_class = _class_name(generator[0]) + children = _child_subtrees(generator) + per_output: Optional[List[_AttrTrace]] = None + if generator_class == "Stack": + # stack(n, e0, e1, ...) puts e_j in output j % output_count + per_output = [_EMPTY] * output_count + for position, arg in enumerate(children[1:]): + slot = position % output_count + per_output[slot] = per_output[slot].merge(_trace_expression(arg, traces)) + elif generator_class == "JsonTuple": + # Every output is a value extracted from the one JSON input + per_output = [whole] * output_count + elif generator_class in ("Explode", "PosExplode", "Inline"): + with_position = generator_class == "PosExplode" + fields = _trace_collection( + children[0], + output_count - with_position, + generator_class == "Inline", + traces, + ) + if fields is not None: + per_output = [whole] * with_position + fields + if per_output is None: + reason = f"columns produced by {generator_class} cannot be traced" + return [_AttrTrace(frozenset(), reason)] * output_count + return per_output + + +def _trace_collection( + collection: List[dict], + field_count: int, + of_structs: bool, + traces: Dict[int, _AttrTrace], +) -> Optional[List[_AttrTrace]]: + """Trace the fields a generator unpacks from each element of a collection. + + The fields are a map's key and value, or a struct's fields (``of_structs``). + Returns ``None`` when it is not known which input feeds which field. + """ + if _is_direct(collection, traces): + return [_trace_expression(collection, traces)] * field_count + root = _class_name(collection[0]) + if root == "CreateMap" and not of_structs and field_count == 2: + # map(k0, v0, k1, v1, ...) + fields = [_EMPTY, _EMPTY] + for position, entry in enumerate(_child_subtrees(collection)): + fields[position % 2] = fields[position % 2].merge( + _trace_expression(entry, traces) + ) + return fields + if root == "CreateArray" and of_structs: + fields = [_EMPTY] * field_count + for element in _child_subtrees(collection): + if _is_direct(element, traces): + element_fields = [_trace_expression(element, traces)] * field_count + elif _class_name(element[0]) == "CreateNamedStruct": + # named_struct(name0, value0, name1, value1, ...) + element_fields = [ + _trace_expression(value, traces) + for value in _child_subtrees(element)[1::2] + ] + else: + return None + fields = [f.merge(e) for f, e in zip(fields, element_fields, strict=True)] + return fields + return None + + +def _is_direct(expression: List[dict], traces: Dict[int, _AttrTrace]) -> bool: + """Whether a flattened expression is a source column passed through as-is.""" + return ( + len(expression) == 1 + and _class_name(expression[0]) == "AttributeReference" + and traces.get(_expr_id(expression[0]), _EMPTY).direct + ) + + +def _class_name(expr_node: dict) -> str: + return str(expr_node["class"]).rsplit(".", 1)[-1] + + +def _child_subtrees(expression: List[dict]) -> List[List[dict]]: + """The flattened subtrees of the root's children, in order.""" + children = [] + index = 1 + for _ in range(expression[0]["num-children"]): + end = _subtree_end(expression, index) + children.append(expression[index:end]) + index = end + return children + + +def _trace_expression( + expression: List[dict], traces: Dict[int, _AttrTrace] +) -> _AttrTrace: + """Union the traces of every attribute an expression (sub)tree's value reads.""" + result = _EMPTY + index = 0 + while index < len(expression): + expr_node = expression[index] + expr_class = _class_name(expr_node) + if expr_class in _ROW_GATING_EXPRESSIONS: + children = _child_subtrees(expression[index:]) + for position, child in enumerate(children): + if _keep_value_children(expr_class, position, len(children)): + result = result.merge(_trace_expression(child, traces)) + index = _subtree_end(expression, index) + continue + index += 1 + if expr_class in _OPAQUE_EXPRESSIONS: + result = result.merge( + _AttrTrace(frozenset(), f"{expr_class} inputs cannot be traced") + ) + elif expr_class in _UDF_EXPRESSIONS: + result = result.merge(_AttrTrace(frozenset(), udf=True)) + elif expr_class == "AttributeReference": + expr_id = _expr_id(expr_node) + if expr_id in traces: + result = result.merge(traces[expr_id]) + else: + result = result.merge( + _AttrTrace(frozenset(), f"unresolved attribute {expr_id}") + ) + return result + + +def _expression_trees(value: Any) -> Iterator[List[dict]]: + """Yield every flattened expression tree held in a plan node's fields.""" + if isinstance(value, dict): + for key, field_value in value.items(): + if key not in ("class", "num-children"): + yield from _expression_trees(field_value) + elif isinstance(value, list) and value: + if all(isinstance(item, dict) and "num-children" in item for item in value): + yield value + else: + for item in value: + if isinstance(item, list): + yield from _expression_trees(item) + + +def _subtree_end(nodes: List[dict], start: int) -> int: + """Index one past the pre-order subtree rooted at ``start``.""" + pending = 1 + index = start + while pending: + pending += nodes[index]["num-children"] - 1 + index += 1 + return index + + +def _children_from_preorder(nodes: List[dict]) -> List[List[int]]: + children: List[List[int]] = [[] for _ in nodes] + open_parents: List[List[int]] = [] # [parent index, children still expected] + for index, node in enumerate(nodes): + if open_parents: + parent = open_parents[-1] + children[parent[0]].append(index) + parent[1] -= 1 + if parent[1] == 0: + open_parents.pop() + if node["num-children"] > 0: + open_parents.append([index, node["num-children"]]) + return children + + +def _jvm_preorder(jplan: Any) -> List[Any]: + result = [] + stack = [jplan] + while stack: + jnode = stack.pop() + result.append(jnode) + jchildren = jnode.children() + stack.extend(jchildren.apply(i) for i in reversed(range(jchildren.size()))) + return result + + +def _parse_output(jnode: Any) -> List[int]: + """ExprIds of a plan node's output attributes, in order. + + One JVM round trip per node: attributes render as ``name#``. + """ + count = jnode.output().size() + if count == 0: + return [] + rendered = jnode.output().mkString(_OUTPUT_SEPARATOR).split(_OUTPUT_SEPARATOR) + if len(rendered) != count: + raise LineageTraceError("Could not parse plan output attributes") + expr_ids = [] + for attr in rendered: + digits = attr.rsplit("#", 1)[-1] + end = 0 + while end < len(digits) and digits[end].isdigit(): + end += 1 + if end == 0: + raise LineageTraceError(f"Could not parse plan attribute {attr!r}") + expr_ids.append(int(digits[:end])) + return expr_ids + + +def _expr_id(expr_node: dict) -> int: + return int(expr_node["exprId"]["id"]) + + +def _leaf_key(jnode: Any, node_class: str, jvm: Any) -> Hashable: + identity = jvm.java.lang.System.identityHashCode + if node_class == "LogicalRDD": + return ("rdd", jnode.rdd().id()) + if node_class == "LocalRelation": + return ("local", identity(jnode.data())) + if node_class == "LogicalRelation": + return ("relation", identity(jnode.relation())) + if node_class == "DataSourceV2Relation": + return ("v2", identity(jnode.table())) + return ("node", identity(jnode)) diff --git a/src/datacustomcode/named_credential/spark_base.py b/src/datacustomcode/named_credential/spark_base.py index 2c477437..8e464575 100644 --- a/src/datacustomcode/named_credential/spark_base.py +++ b/src/datacustomcode/named_credential/spark_base.py @@ -66,11 +66,12 @@ def request_col( self, request: HTTPRequest, body: Optional["Column"] = None, + path: Optional["Column"] = None, ) -> "Column": """Build a Spark ``Column`` that makes one external callout per row. - The endpoint, method, and headers are fixed for the call (taken from - ``request``); only ``body`` varies per row. Use this instead of + The method and headers are fixed for the call (taken from ``request``); + ``body`` and, optionally, ``path`` vary per row. Use this instead of :meth:`request` when the callout runs across a DataFrame so each row is dispatched independently rather than one-shot on the driver. @@ -78,6 +79,11 @@ def request_col( request: The callout template body: Optional per-row ``Column`` holding the request body as a string, sent verbatim (or null for no body). + path: Optional per-row ``Column`` appended to ``request.url`` + (e.g. ``/v1/models`` or ``?id=42``) so each row can target a + different endpoint of the same Named Credential. A path not + starting with ``/`` or ``?`` is joined with ``/``; a null or + empty row value uses ``request.url`` as is. Returns: A ``Column`` yielding a struct diff --git a/src/datacustomcode/named_credential/spark_default.py b/src/datacustomcode/named_credential/spark_default.py index 8f3ea236..3e13fccf 100644 --- a/src/datacustomcode/named_credential/spark_default.py +++ b/src/datacustomcode/named_credential/spark_default.py @@ -79,6 +79,7 @@ def request_col( self, request: "HTTPRequest", body: Optional["Column"] = None, + path: Optional["Column"] = None, ) -> "Column": """Per-row callout via a client-side Spark UDF. @@ -114,11 +115,46 @@ def request_col( ] ) - def _callout(body_str: Optional[str]) -> Dict[str, Any]: - return _invoke_callout_as_struct(self._named_credential, request, body_str) - body_col = body if body is not None else lit(None).cast(StringType()) - return udf(_callout, result_schema)(body_col) + + if path is None: + + def _callout(body_str: Optional[str]) -> Dict[str, Any]: + return _invoke_callout_as_struct( + self._named_credential, request, body_str + ) + + return udf(_callout, result_schema)(body_col) + + def _callout_with_path( + body_str: Optional[str], path_str: Optional[str] + ) -> Dict[str, Any]: + row_request = ( + request.model_copy( + update={"url": join_callout_path(request.url, path_str)} + ) + if path_str + else request + ) + return _invoke_callout_as_struct( + self._named_credential, row_request, body_str + ) + + return udf(_callout_with_path, result_schema)(body_col, path) + + +def join_callout_path(base_url: str, path: Optional[str]) -> str: + """Append a per-row ``path`` to the template ``base_url``. + + A path not starting with ``/`` or ``?`` is joined with ``/`` so the row can + never extend the Named Credential name (``callout:NC`` + ``2/x`` must not + become ``callout:NC2/x``). A null or empty path returns ``base_url``. + """ + if not path: + return base_url + if path.startswith(("/", "?")): + return base_url + path + return f"{base_url}/{path}" def _invoke_callout_as_struct( diff --git a/src/datacustomcode/run.py b/src/datacustomcode/run.py index f615af52..0552adfc 100644 --- a/src/datacustomcode/run.py +++ b/src/datacustomcode/run.py @@ -12,6 +12,7 @@ # 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. +from dataclasses import dataclass, field import importlib import json import os @@ -52,6 +53,27 @@ def _read_streaming_source(config_json: dict) -> Optional[str]: return str(name) if name else None +def _project_config_yaml(entrypoint: str) -> Optional[str]: + """Locate a project-local ``config.yaml`` next to ``payload/``. + + A streaming project scaffolded by + ``datacustomcode init --use-in-feature StreamingTransform`` has + ``config.yaml`` at the project root. + + Layout:: + + / + config.yaml <-- this file (streaming profile) + payload/ + entrypoint.py <-- passed as `entrypoint` + config.json + """ + entrypoint_dir = os.path.dirname(os.path.abspath(entrypoint)) + project_root = os.path.dirname(entrypoint_dir) + candidate = os.path.join(project_root, "config.yaml") + return candidate if os.path.exists(candidate) else None + + def _update_config_options(profile: Optional[str], sf_cli_org: Optional[str]): if sf_cli_org: config_key = "sf_cli_org" @@ -81,6 +103,15 @@ def _update_config_options(profile: Optional[str], sf_cli_org: Optional[str]): ) +@dataclass(frozen=True) +class RunContext: + """State resolved by :func:`prepare_run` and consumed by + :func:`execute_entrypoint`.""" + + package_type: str + config_json: dict = field(default_factory=dict) + + def run_entrypoint( entrypoint: str, config_file: Union[str, None], @@ -100,6 +131,34 @@ def run_entrypoint( sf_cli_org: Optional SF CLI org alias or username. If provided, credentials are fetched via `sf org display` instead of from credentials.ini. """ + context = prepare_run(entrypoint, config_file, dependencies, profile, sf_cli_org) + execute_entrypoint(entrypoint, context, test_file) + + +def prepare_run( + entrypoint: str, + config_file: Union[str, None], + dependencies: List[str], + profile: str, + sf_cli_org: Optional[str] = None, +) -> RunContext: + """Resolve config and import dependencies for an entrypoint, without running it. + + This is the setup half of :func:`run_entrypoint`. Callers that need to act + between setup and running (e.g. lineage generation starting its capture) call + this, then :func:`execute_entrypoint`. Such callers can pass no dependencies + here and call :func:`import_dependencies` themselves at the right moment. + + Args: + entrypoint: The entrypoint script to run. + config_file: The config file to use. + dependencies: The dependencies to import. + profile: The credentials profile to use. + sf_cli_org: Optional SF CLI org alias or username. + + Returns: + The resolved :class:`RunContext`. + """ add_py_folder(entrypoint) # Read dataspace from config.json (required) @@ -136,6 +195,10 @@ def run_entrypoint( # Load config file first if config_file: config.load(config_file) + else: + project_config = _project_config_yaml(entrypoint) + if project_config: + config.load(project_config) # Add dataspace to reader and writer config options _set_config_option(config.reader_config, "dataspace", dataspace) @@ -144,7 +207,17 @@ def run_entrypoint( config.streaming_source = _read_streaming_source(config_json) _update_config_options(profile, sf_cli_org) + import_dependencies(dependencies) + + return RunContext(package_type=package_type, config_json=config_json) + +def import_dependencies(dependencies: List[str]) -> None: + """Import each dependency module (or ``module.attribute``), as ``run`` does. + + Args: + dependencies: The dependencies to import. + """ for dependency in dependencies: try: importlib.import_module(dependency) @@ -159,8 +232,19 @@ def run_entrypoint( except (ModuleNotFoundError, AttributeError) as inner_exc: raise inner_exc from exc + +def execute_entrypoint( + entrypoint: str, context: RunContext, test_file: Optional[str] = None +) -> None: + """Run an entrypoint previously set up with :func:`prepare_run`. + + Args: + entrypoint: The entrypoint script to run. + context: The context returned by :func:`prepare_run`. + test_file: Optional test JSON file for function testing. + """ # Handle test file for functions - if test_file and package_type == "function": + if test_file and context.package_type == "function": run_function_with_test(entrypoint, test_file) else: runpy.run_path(entrypoint, init_globals=globals(), run_name="__main__") diff --git a/src/datacustomcode/scan.py b/src/datacustomcode/scan.py index 059925af..a3bf7188 100644 --- a/src/datacustomcode/scan.py +++ b/src/datacustomcode/scan.py @@ -34,7 +34,7 @@ DATA_ACCESS_METHODS = ["read_dlo", "read_dmo", "write_to_dlo", "write_to_dmo"] STREAMING_READ_METHODS = ["read_dlo_deltas", "read_dmo_deltas"] -STREAMING_WRITE_METHODS = ["write_dlo_deltas"] +STREAMING_WRITE_METHODS = ["write_dlo_deltas", "write_dmo_deltas"] DATA_TRANSFORM_CONFIG_TEMPLATE = { "sdkVersion": get_version(), @@ -181,6 +181,7 @@ class StreamingDataAccessLayerCalls(pydantic.BaseModel): read_dlo_deltas: bool read_dmo_deltas: bool write_dlo_deltas: frozenset[str] + write_dmo_deltas: frozenset[str] @pydantic.model_validator(mode="after") def validate_access_layer(self) -> StreamingDataAccessLayerCalls: @@ -193,10 +194,19 @@ def validate_access_layer(self) -> StreamingDataAccessLayerCalls: "A streaming transform must read from at least one DLO or DMO " "delta stream (read_dlo_deltas / read_dmo_deltas)." ) - if not self.write_dlo_deltas: + if not self.write_dlo_deltas and not self.write_dmo_deltas: raise ValueError( - "A streaming transform must write to at least one DLO via " - "write_dlo_deltas." + "A streaming transform must write to at least one DLO or DMO " + "via write_dlo_deltas / write_dmo_deltas." + ) + if self.write_dlo_deltas and self.write_dmo_deltas: + raise ValueError( + "Cannot write DLO and DMO deltas in the same streaming transform." + ) + if self.read_layer != self.write_layer: + raise ValueError( + "A streaming transform must read and write the same layer " + f"(got read={self.read_layer}, write={self.write_layer})." ) return self @@ -205,6 +215,11 @@ def read_layer(self) -> str: """Return the read source layer, ``"dlo"`` or ``"dmo"``.""" return "dlo" if self.read_dlo_deltas else "dmo" + @property + def write_layer(self) -> str: + """Return the write target layer, ``"dlo"`` or ``"dmo"``.""" + return "dlo" if self.write_dlo_deltas else "dmo" + class ClientMethodVisitor(ast.NodeVisitor): """AST Visitor that finds all instances of Client read/write method calls.""" @@ -217,6 +232,7 @@ def __init__(self) -> None: self._read_dlo_deltas: bool = False self._read_dmo_deltas: bool = False self._write_dlo_deltas_instances: set[str] = set() + self._write_dmo_deltas_instances: set[str] = set() self.variable_values: Dict[str, Union[str, None]] = {} def visit_Assign(self, node: ast.Assign) -> None: @@ -261,6 +277,8 @@ def visit_Call(self, node: ast.Call) -> None: name = self._resolve_name_arg(node.args[0]) if name and method_name == "write_dlo_deltas": self._write_dlo_deltas_instances.add(name) + elif name and method_name == "write_dmo_deltas": + self._write_dmo_deltas_instances.add(name) self.generic_visit(node) def _resolve_name_arg(self, arg: ast.expr) -> Union[str, None]: @@ -278,6 +296,7 @@ def is_streaming(self) -> bool: self._read_dlo_deltas or self._read_dmo_deltas or bool(self._write_dlo_deltas_instances) + or bool(self._write_dmo_deltas_instances) ) def found(self) -> DataAccessLayerCalls: @@ -293,6 +312,7 @@ def found_streaming(self) -> StreamingDataAccessLayerCalls: read_dlo_deltas=self._read_dlo_deltas, read_dmo_deltas=self._read_dmo_deltas, write_dlo_deltas=frozenset(self._write_dlo_deltas_instances), + write_dmo_deltas=frozenset(self._write_dmo_deltas_instances), ) @@ -516,10 +536,10 @@ def _update_streaming_config(existing_config: dict[str, Any], file_path: str) -> ) read_names = [source_name] if source_name else [] - write_names = list(output.write_dlo_deltas) + write_names = list(output.write_dlo_deltas or output.write_dmo_deltas) existing_config["permissions"] = { "read": {read_layer: read_names}, - "write": {"dlo": write_names}, + "write": {output.write_layer: write_names}, } diff --git a/src/datacustomcode/spark/column_hints.py b/src/datacustomcode/spark/column_hints.py new file mode 100644 index 00000000..1f49d3e3 --- /dev/null +++ b/src/datacustomcode/spark/column_hints.py @@ -0,0 +1,194 @@ +# 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. +"""Friendlier errors when a script references a column by the wrong case. + +Data Cloud column names are lowercase. A reference using another case (e.g. +``df["UnitPrice__c"]``) fails to resolve with a generic error. These hooks +detect when the lowercase form of a referenced name is a real column and +prepend an explicit hint, keeping the original message: + + Column 'UnitPrice__c' not found. Did you mean 'unitprice__c'? + Data Cloud columns must be lowercase. + +Two hooks cover all access paths: one for column-resolution errors, and one +for attribute access (``df.X``), which fails separately. Both only augment an +error that was already going to be raised, and only for a pure casing mismatch. +""" +from __future__ import annotations + +import importlib.abc +import logging +import sys +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from importlib.machinery import ModuleSpec + from types import ModuleType + +logger = logging.getLogger(__name__) + +# Marker on our wrappers so repeated installs never stack. +_WRAPPED_MARKER = "_datacustomcode_wrapped" + + +def _strip_backticks(name: str) -> str: + """Return the bare column name from a Spark identifier token.""" + name = name.strip() + if "." in name: # drop any table/alias qualifier + name = name.split(".")[-1] + return name.strip().strip("`") + + +def _casing_hint(bad: str, suggestion: str) -> str: + return ( + f"Column '{bad}' not found. Did you mean '{suggestion}'? " + "Data Cloud columns must be lowercase." + ) + + +def _lowercase_match(bad: str, available: list[str]) -> str | None: + """Return the column matching *bad* case-insensitively, else ``None``. + + Returns ``None`` when *bad* is already lowercase, so a real typo is not + reported as a casing issue. + """ + if not bad or bad == bad.lower(): + return None + lowered = bad.lower() + for col in available: + if col.lower() == lowered: + return col + return None + + +def _install_analysis_exception_hook() -> None: + """Add a casing hint to column-resolution errors.""" + from pyspark.errors.exceptions import captured + + original = captured.convert_exception + if getattr(original, _WRAPPED_MARKER, False): + return + + def convert_exception_with_hint(e): # type: ignore[no-untyped-def] + exc = original(e) + try: + error_class = exc.getErrorClass() + except Exception: # pragma: no cover - defensive + return exc + if not error_class or not error_class.startswith("UNRESOLVED_COLUMN"): + return exc + + params = exc.getMessageParameters() or {} + bad = _strip_backticks(params.get("objectName", "")) + proposal = params.get("proposal", "") + available = [ + _strip_backticks(tok) for tok in proposal.split(",") if tok.strip() + ] + + suggestion = _lowercase_match(bad, available) + if suggestion is not None: # prepend hint; keep original detail + exc.desc = f"{_casing_hint(bad, suggestion)}\n{exc.desc}" + return exc + + setattr(convert_exception_with_hint, _WRAPPED_MARKER, True) + captured.convert_exception = convert_exception_with_hint + + +def _install_getattr_hook() -> None: + """Add a casing hint to attribute access (``df.X``).""" + from pyspark.sql import DataFrame + + original = DataFrame.__getattr__ + if getattr(original, _WRAPPED_MARKER, False): + return + + def __getattr__with_hint(self, name): # type: ignore[no-untyped-def] + try: + return original(self, name) + except AttributeError as exc: + if name.startswith("_"): # leave dunder/private lookups alone + raise + suggestion = _lowercase_match(name, list(self.columns)) + if suggestion is not None: # prepend hint; keep original text + raise AttributeError( + f"{_casing_hint(name, suggestion)}\n{exc}" + ) from None + raise + + setattr(__getattr__with_hint, _WRAPPED_MARKER, True) + DataFrame.__getattr__ = __getattr__with_hint # type: ignore[assignment] + + +def install_column_casing_hints() -> None: + """Arrange for the column-casing hint hooks to be installed. + + Never imports pyspark directly. If pyspark is already loaded, the hooks + are installed immediately; otherwise, installation is deferred until + ``pyspark.sql`` is actually imported by someone. Idempotent; never raises. + """ + if "pyspark.sql" in sys.modules: + _install_hooks_now() + return + if any(isinstance(finder, _PySparkImportHook) for finder in sys.meta_path): + return + try: + sys.meta_path.insert(0, _PySparkImportHook()) + except Exception as exc: # pragma: no cover - defensive + logger.debug(f"Could not defer column-casing hint installation: {exc}") + + +def _install_hooks_now() -> None: + """Install the column-casing hint hooks. Idempotent; never raises.""" + try: + _install_analysis_exception_hook() + _install_getattr_hook() + except Exception as exc: # pragma: no cover - defensive + logger.debug(f"Could not install column-casing hint hooks: {exc}") + + +class _PySparkImportHook(importlib.abc.MetaPathFinder): + """Installs the hint hooks right after ``pyspark.sql`` finishes loading. + + ``install_column_casing_hints`` must not import pyspark itself: this + package is also used in the pyspark-free Function code path that must + not pull pyspark in as a side effect of importing ``datacustomcode``. + Wrapping the real loader lets us defer the pyspark import until whoever + actually needs it (the SDK's own lazy accessors, or user code) imports + ``pyspark.sql`` on their own. + """ + + def find_spec( + self, fullname: str, path: object, target: ModuleType | None = None + ) -> ModuleSpec | None: + if fullname != "pyspark.sql": + return None + + for finder in sys.meta_path: + if finder is self: + continue + find_spec = getattr(finder, "find_spec", None) + if find_spec is None: + continue + spec = find_spec(fullname, path, target) + if spec is not None and spec.loader is not None: + original_exec_module = spec.loader.exec_module + + def exec_module(module: ModuleType, _orig=original_exec_module) -> None: + _orig(module) + _install_hooks_now() + + spec.loader.exec_module = exec_module # type: ignore[method-assign] + return spec # type: ignore[no-any-return] + return None diff --git a/src/datacustomcode/template.py b/src/datacustomcode/template.py index a5435755..e2902f3d 100644 --- a/src/datacustomcode/template.py +++ b/src/datacustomcode/template.py @@ -27,6 +27,8 @@ script_template_dir, "examples", "streaming_deltas", "entrypoint.py" ) +_SDK_CONFIG_YAML = os.path.join(os.path.dirname(__file__), "config.yaml") + def copy_script_template(target_dir: str, streaming: bool = False) -> None: """Copy the template to the target directory.""" @@ -51,6 +53,24 @@ def copy_script_template(target_dir: str, streaming: bool = False) -> None: ) shutil.copy2(STREAMING_EXAMPLE_ENTRYPOINT, destination) + _write_streaming_config_yaml(target_dir) + + +def _write_streaming_config_yaml(target_dir: str) -> None: + """Writes the sdk config file with Streaming overrdies""" + import yaml + + with open(_SDK_CONFIG_YAML) as f: + config_data = yaml.safe_load(f) + + config_data["reader_config"]["type_config_name"] = "LocalDeltasReader" + config_data["writer_config"]["type_config_name"] = "LocalDeltasWriter" + + destination = os.path.join(target_dir, "config.yaml") + logger.debug(f"Writing streaming config.yaml to {destination}...") + with open(destination, "w") as f: + yaml.safe_dump(config_data, f, sort_keys=False) + def copy_function_template(target_dir: str, use_in_feature: Optional[str]) -> None: os.makedirs(target_dir, exist_ok=True) diff --git a/tests/io/reader/test_local_deltas.py b/tests/io/reader/test_local_deltas.py new file mode 100644 index 00000000..5f0382a2 --- /dev/null +++ b/tests/io/reader/test_local_deltas.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import json +from unittest.mock import MagicMock, patch + +from pyspark.sql.types import ( + LongType, + StringType, + StructField, + StructType, +) +import pytest + +from datacustomcode.io import cdf +from datacustomcode.io.reader.local_deltas import LocalDeltasReader + +SOURCE_SCHEMA = StructType( + [ + StructField("id__c", StringType(), True), + StructField("age__c", LongType(), True), + ] +) + + +@pytest.fixture +def reader(tmp_path): + """Reader with __init__ short-circuited (avoids Query API construction).""" + with patch.object(LocalDeltasReader, "__init__", return_value=None): + r = LocalDeltasReader(spark=None) + r.spark = MagicMock() + r._fixtures_root = tmp_path + r._credentials_profile = "default" + r._dataspace = None + r._sf_cli_org = None + r._batch = MagicMock() + r._current_layer = "dlo" + yield r + + +def _write_schema_file(fixtures_root, name): + out_dir = fixtures_root / name + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "_schema.json").write_text(json.dumps(SOURCE_SCHEMA.jsonValue())) + + +def test_stream_schema_is_source_columns_plus_three_cdf_columns(reader, tmp_path): + _write_schema_file(tmp_path, "Foo__dll") + + schema = reader._build_stream_schema("Foo__dll") + + names = [f.name for f in schema.fields] + assert names == [ + "id__c", + "age__c", + cdf.COMMIT_VERSION, + cdf.COMMIT_TIMESTAMP, + cdf.MERGE_RECORD_TYPE, + ] + + +def test_open_stream_invokes_seeder_when_schema_file_missing(reader, tmp_path): + reader.spark.readStream.format.return_value = reader.spark.readStream + reader.spark.readStream.schema.return_value = reader.spark.readStream + reader.spark.readStream.option.return_value = reader.spark.readStream + reader.spark.readStream.load.return_value = MagicMock() + + def fake_seed(name): + _write_schema_file(tmp_path, name) + return True + + with patch.object(reader, "_try_seed", side_effect=fake_seed) as try_seed: + reader._open_stream("Foo__dll") + try_seed.assert_called_once_with("Foo__dll") + + +def test_open_stream_exits_cleanly_on_empty_source(reader): + with patch.object(reader, "_try_seed", return_value=False): + with pytest.raises(SystemExit) as exc: + reader._open_stream("Foo__dll") + assert exc.value.code == 0 + reader.spark.readStream.format.assert_not_called() + + +def test_read_dlo_delegates_to_batch_reader(reader): + reader.read_dlo("Foo__dll", None) + reader._batch.read_dlo.assert_called_once_with("Foo__dll", None) diff --git a/tests/io/reader/test_streaming_seeder.py b/tests/io/reader/test_streaming_seeder.py new file mode 100644 index 00000000..11381355 --- /dev/null +++ b/tests/io/reader/test_streaming_seeder.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import json +from unittest.mock import MagicMock, patch + +import pandas as pd +from pyspark.sql.types import ( + LongType, + StringType, + StructField, + StructType, +) +import pytest + +from datacustomcode.io import cdf +from datacustomcode.io.reader.streaming_seeder import StreamingSourceSeeder + +SOURCE_SCHEMA = StructType( + [ + StructField("id__c", StringType(), True), + StructField("age__c", LongType(), True), + ] +) + + +def _stub_read_result(rows_df: pd.DataFrame): + limited = MagicMock() + limited.toPandas.return_value = rows_df + limited.schema = SOURCE_SCHEMA + + df = MagicMock() + df.limit.return_value = limited + return df + + +@pytest.fixture +def seeder(): + """Seeder with __init__ short-circuited (avoids real Query API creds).""" + with patch.object(StreamingSourceSeeder, "__init__", return_value=None): + s = StreamingSourceSeeder(spark=None) + s.spark = MagicMock() + s.reader = MagicMock() + yield s + + +def test_non_empty_source_writes_schema_and_seed(seeder, tmp_path): + seeder.reader.read_dlo.return_value = _stub_read_result( + pd.DataFrame([{"id__c": str(i), "age__c": i} for i in range(4)]) + ) + + wrote = seeder.seed_source("Foo__dll", "dlo", str(tmp_path)) + + assert wrote is True + out_dir = tmp_path / "Foo__dll" + assert (out_dir / "_schema.json").exists() + assert (out_dir / "000_seed.json").exists() + + rows = [ + json.loads(line) + for line in (out_dir / "000_seed.json").read_text().splitlines() + ] + for row in rows: + assert cdf.COMMIT_VERSION in row + assert cdf.COMMIT_TIMESTAMP in row + assert cdf.MERGE_RECORD_TYPE in row + # Both operation types appear in the seed. + ops = {row[cdf.MERGE_RECORD_TYPE] for row in rows} + assert ops == { + cdf.MergeRecordType.UPSERT.value, + cdf.MergeRecordType.DELETE.value, + } + + +def test_empty_source_returns_false_and_writes_nothing(seeder, tmp_path): + seeder.reader.read_dlo.return_value = _stub_read_result(pd.DataFrame([])) + + wrote = seeder.seed_source("Foo__dll", "dlo", str(tmp_path)) + + assert wrote is False + assert not (tmp_path / "Foo__dll").exists() diff --git a/tests/io/writer/test_local_deltas.py b/tests/io/writer/test_local_deltas.py new file mode 100644 index 00000000..9c995220 --- /dev/null +++ b/tests/io/writer/test_local_deltas.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from datacustomcode.io import cdf +from datacustomcode.io.writer.base import WriteMode +from datacustomcode.io.writer.local_deltas import LocalDeltasWriter + + +@pytest.fixture +def writer(): + with patch.object(LocalDeltasWriter, "__init__", return_value=None): + w = LocalDeltasWriter(spark=None) + w.spark = MagicMock() + w._batch_writer = MagicMock() + yield w + + +def _configure_writestream_chain(df): + ws = MagicMock() + df.writeStream = ws + ws.foreachBatch.return_value = ws + ws.option.return_value = ws + ws.trigger.return_value = ws + return ws + + +def test_write_dlo_deltas_uses_trigger_available_now(writer): + df = MagicMock() + ws = _configure_writestream_chain(df) + + writer.write_dlo_deltas("Foo__dll", df) + + ws.trigger.assert_called_once_with(availableNow=True) + + +def test_preview_drops_cdf_metadata_columns(writer): + df = MagicMock() + ws = _configure_writestream_chain(df) + writer.write_dlo_deltas("Foo__dll", df) + callback = ws.foreachBatch.call_args.args[0] + + # Set up the batch DF so .withColumn().drop() → a mock we can inspect. + annotated_after_with = MagicMock() + annotated_after_drop = MagicMock() + annotated_after_drop.count.return_value = 2 + annotated_after_with.drop.return_value = annotated_after_drop + batch_df = MagicMock() + batch_df.withColumn.return_value = annotated_after_with + batch_df.select.return_value.limit.return_value.collect.return_value = [] + + with ( + patch("pyspark.sql.functions.col", MagicMock()), + patch("pyspark.sql.functions.when", MagicMock()), + patch("pyspark.sql.functions.lit", MagicMock()), + patch("pyspark.sql.functions.input_file_name", MagicMock()), + ): + callback(batch_df, 0) + + # drop() removed all three CDF metadata columns. + assert set(annotated_after_with.drop.call_args.args) == { + cdf.COMMIT_VERSION, + cdf.COMMIT_TIMESTAMP, + cdf.MERGE_RECORD_TYPE, + } + + +def test_batch_writes_delegate_to_print_writer(writer): + df = MagicMock() + + writer.write_to_dlo("Foo__dll", df, WriteMode.APPEND) + writer.auto_write_to_dlo("Foo__dll", df) + + writer._batch_writer.write_to_dlo.assert_called_once_with( + "Foo__dll", df, WriteMode.APPEND + ) + writer._batch_writer.auto_write_to_dlo.assert_called_once_with("Foo__dll", df) diff --git a/tests/io/writer/test_print.py b/tests/io/writer/test_print.py index a10f2a33..258a765a 100644 --- a/tests/io/writer/test_print.py +++ b/tests/io/writer/test_print.py @@ -65,6 +65,12 @@ def test_write_dlo_deltas_not_supported_locally(self, print_writer, mock_datafra print_writer.write_dlo_deltas("test_dll", mock_dataframe) 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) + assert "write_dmo_deltas" in str(exc_info.value) + def test_config_name(self): """Test that the CONFIG_NAME class variable is set correctly.""" assert PrintDataCloudWriter.CONFIG_NAME == "PrintDataCloudWriter" diff --git a/tests/lineage/__init__.py b/tests/lineage/__init__.py new file mode 100644 index 00000000..6ae52944 --- /dev/null +++ b/tests/lineage/__init__.py @@ -0,0 +1 @@ +# Package initialization file diff --git a/tests/lineage/conftest.py b/tests/lineage/conftest.py new file mode 100644 index 00000000..f262243d --- /dev/null +++ b/tests/lineage/conftest.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from pyspark.sql import SparkSession +import pytest + + +@pytest.fixture(scope="module") +def spark(): + # Arrow and case sensitivity match the SDK's default config.yaml + session = ( + SparkSession.builder.master("local[1]") + .appName("lineage-test") + .config("spark.ui.enabled", "false") + .config("spark.sql.caseSensitive", "true") + .config("spark.sql.execution.arrow.pyspark.enabled", "true") + .getOrCreate() + ) + session.sparkContext.setLogLevel("OFF") + yield session + session.stop() diff --git a/tests/lineage/lineage_test_io.py b/tests/lineage/lineage_test_io.py new file mode 100644 index 00000000..31913f9b --- /dev/null +++ b/tests/lineage/lineage_test_io.py @@ -0,0 +1,52 @@ +"""Reader/writer for the generate tests, importable by the lineage worker process. + +The worker re-imports this module (it is on ``sys.path`` via ``PYTHONPATH``), so +the writer reports validations through a file rather than shared memory. +""" + +from __future__ import annotations + +import json +import os + +import pandas as pd + +from datacustomcode.io.reader.base import BaseDataCloudReader +from datacustomcode.io.writer.base import BaseDataCloudWriter + +VALIDATED_FILE_ENV = "LINEAGE_TEST_VALIDATED_FILE" + +TABLES = { + "orders__dll": pd.DataFrame( + {"id": [1, 2], "first": ["a", "b"], "last": ["x", "y"], "amount": [1.0, 2.0]} + ), + "customers__dlm": pd.DataFrame({"id": [1, 2], "region": ["us", "eu"]}), +} + + +class InMemoryReader(BaseDataCloudReader): + CONFIG_NAME = "LineageTestInMemoryReader" + + def __init__(self, spark, dataspace=None): + super().__init__(spark) + + def read_dlo(self, name, schema=None): + return self.spark.createDataFrame(TABLES[name]) + + read_dmo = read_dlo + + +class RefusingWriter(BaseDataCloudWriter): + CONFIG_NAME = "LineageTestRefusingWriter" + + def __init__(self, spark, dataspace=None): + super().__init__(spark) + + def validate_dataframe_columns_against_dlo(self, dataframe, dlo_name): + with open(os.environ[VALIDATED_FILE_ENV], "a", encoding="utf-8") as f: + f.write(json.dumps([dlo_name, list(dataframe.columns)]) + "\n") + + def write_to_dlo(self, name, dataframe, write_mode): + raise AssertionError("lineage generation must never write") + + write_to_dmo = write_to_dlo diff --git a/tests/lineage/test_generate.py b/tests/lineage/test_generate.py new file mode 100644 index 00000000..c8ea6505 --- /dev/null +++ b/tests/lineage/test_generate.py @@ -0,0 +1,361 @@ +"""End-to-end tests for generate_lineage with an in-memory reader (no org).""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys +import textwrap + +import pytest +import yaml + +from datacustomcode.config import AccessLayerObjectConfig +from datacustomcode.lineage import LineageResult, generate_lineage +from datacustomcode.lineage.capture import LineageCaptureWriter, LineageCollector +from datacustomcode.scan import SDK_CONFIG_DIR, SDK_CONFIG_FILE + +# generate_lineage passes sys.path to its worker, so the worker can import this too +sys.path.insert(0, str(Path(__file__).parent)) +from lineage_test_io import ( + VALIDATED_FILE_ENV, + InMemoryReader, + RefusingWriter, +) + +pytestmark = pytest.mark.spark + +PREAMBLE = ( + "from pyspark.sql import functions as F\n" + "import lineage_test_io\n" + "from datacustomcode.client import Client\n" + "from datacustomcode.io.writer.base import WriteMode\n" +) + + +@pytest.fixture(autouse=True) +def validated(tmp_path, monkeypatch): + """Reads back the (dlo, columns) validations the worker's writer recorded.""" + path = tmp_path / "validated.jsonl" + monkeypatch.setenv(VALIDATED_FILE_ENV, str(path)) + + def read(): + if not path.exists(): + return [] + return [tuple(json.loads(line)) for line in path.read_text().splitlines()] + + return read + + +@pytest.fixture +def config_file(tmp_path): + path = tmp_path / "config.yaml" + path.write_text( + yaml.dump( + { + "reader_config": {"type_config_name": InMemoryReader.CONFIG_NAME}, + "writer_config": {"type_config_name": RefusingWriter.CONFIG_NAME}, + } + ) + ) + return str(path) + + +def make_package( + tmp_path, body: str, config_json=None, package_type=None, with_client=True +) -> str: + payload = tmp_path / "payload" + payload.mkdir() + entrypoint = payload / "entrypoint.py" + preamble = PREAMBLE + ("client = Client()\n" if with_client else "") + entrypoint.write_text(preamble + textwrap.dedent(body)) + (payload / "config.json").write_text( + json.dumps(config_json or {"dataspace": "default"}) + ) + if package_type: + sdk_dir = tmp_path / SDK_CONFIG_DIR + sdk_dir.mkdir() + (sdk_dir / SDK_CONFIG_FILE).write_text(json.dumps({"type": package_type})) + return str(entrypoint) + + +def test_generate_lineage_end_to_end(tmp_path, config_file, validated): + entrypoint = make_package( + tmp_path, + """ + orders = client.read_dlo("orders__dll") + lookup = orders.sparkSession.createDataFrame(orders.select("id").toPandas()) + df = orders.join(lookup, "id").select( + F.col("id").alias("id__c"), + F.concat_ws(" ", "first", "last").alias("name__c"), + F.lit("x").alias("const__c"), + lookup["id"].alias("lookup_id__c"), + ) + client.write_to_dlo("out__dll", df, WriteMode.APPEND) + """, + ) + + result = generate_lineage(entrypoint, config_file) + + assert result.to_dict() == { + "dataLineage": [ + {"targetField": "out__dll.id__c", "sourceFields": ["orders__dll.id"]}, + { + "targetField": "out__dll.name__c", + "sourceFields": ["orders__dll.first", "orders__dll.last"], + }, + ], + "unresolved": [ + {"targetField": "out__dll.lookup_id__c", "reason": "untraceable source"} + ], + "noSources": ["out__dll.const__c"], + "udfFields": [], + "targets": ["out__dll"], + "sources": ["orders__dll"], + "pairCount": 3, + } + assert validated() == [ + ("out__dll", ["id__c", "name__c", "const__c", "lookup_id__c"]) + ] + + +def test_repeat_writes_union_sources(tmp_path, config_file): + entrypoint = make_package( + tmp_path, + """ + orders = client.read_dlo("orders__dll") + client.write_to_dlo( + "out__dll", orders.select(F.col("first").alias("v__c")), WriteMode.APPEND + ) + client.write_to_dlo( + "out__dll", orders.select(F.col("last").alias("v__c")), WriteMode.APPEND + ) + """, + ) + + lineage = generate_lineage(entrypoint, config_file).to_dict()["dataLineage"] + + assert lineage == [ + { + "targetField": "out__dll.v__c", + "sourceFields": ["orders__dll.first", "orders__dll.last"], + } + ] + + +def test_udf_fields_are_reported(tmp_path, config_file): + entrypoint = make_package( + tmp_path, + """ + orders = client.read_dlo("orders__dll") + shout = F.udf(lambda a: a.upper(), "string") + constant = F.udf(lambda: "x", "string") + df = orders.select( + F.col("id").alias("id__c"), + shout("first").alias("loud__c"), + constant().alias("const__c"), + ) + client.write_to_dlo("out__dll", df, WriteMode.APPEND) + """, + ) + + result = generate_lineage(entrypoint, config_file).to_dict() + + assert result["udfFields"] == ["out__dll.const__c", "out__dll.loud__c"] + assert {e["targetField"]: e["sourceFields"] for e in result["dataLineage"]} == { + "out__dll.id__c": ["orders__dll.id"], + "out__dll.loud__c": ["orders__dll.first"], + } + assert result["noSources"] == ["out__dll.const__c"] + + +def test_repeat_writes_keep_udf_flag(tmp_path, config_file): + entrypoint = make_package( + tmp_path, + """ + orders = client.read_dlo("orders__dll") + shout = F.udf(lambda a: a.upper(), "string") + client.write_to_dlo( + "out__dll", orders.select(shout("first").alias("v__c")), WriteMode.APPEND + ) + client.write_to_dlo( + "out__dll", orders.select(F.col("last").alias("v__c")), WriteMode.APPEND + ) + """, + ) + + result = generate_lineage(entrypoint, config_file) + + assert result.data_lineage == { + "out__dll.v__c": ["orders__dll.first", "orders__dll.last"] + } + assert result.udf_fields == ["out__dll.v__c"] + + +def test_dmo_read_and_write(tmp_path, config_file, validated): + entrypoint = make_package( + tmp_path, + """ + df = client.read_dmo("customers__dlm").select( + F.upper("region").alias("region__c") + ) + client.write_to_dmo("out__dlm", df, WriteMode.APPEND) + """, + ) + + result = generate_lineage(entrypoint, config_file) + + assert result.data_lineage == {"out__dlm.region__c": ["customers__dlm.region"]} + assert validated() == [] + + +def test_rejects_function_packages(tmp_path, config_file): + entrypoint = make_package(tmp_path, "", package_type="function") + + with pytest.raises(ValueError, match="only be generated for script packages"): + generate_lineage(entrypoint, config_file) + + +def test_rejects_streaming_scripts(tmp_path, config_file): + entrypoint = make_package( + tmp_path, + "", + config_json={"dataspace": "default", "streamingSource": {"name": "a__dll"}}, + ) + + with pytest.raises(ValueError, match="does not support streaming"): + generate_lineage(entrypoint, config_file) + + +def test_script_error_propagates(tmp_path, config_file): + entrypoint = make_package(tmp_path, "raise RuntimeError('boom')\n") + + with pytest.raises(RuntimeError, match="boom"): + generate_lineage(entrypoint, config_file) + + +def test_non_builtin_error_is_reported_by_name(tmp_path, config_file): + entrypoint = make_package( + tmp_path, + """ + class CustomerError(Exception): + pass + raise CustomerError("bad row") + """, + ) + + with pytest.raises(RuntimeError, match="CustomerError: bad row"): + generate_lineage(entrypoint, config_file) + + +def test_worker_exit_without_response_is_reported(tmp_path, config_file): + entrypoint = make_package(tmp_path, "import os\nos._exit(3)\n") + + with pytest.raises(RuntimeError, match="exited with code 3"): + generate_lineage(entrypoint, config_file) + + +def test_retained_client_from_dependency_is_captured( + tmp_path, config_file, monkeypatch, validated +): + # A dependency that builds its Client at import time keeps it in a module + # global; its writes must still be captured, never reach the real writer + (tmp_path / "lineage_dep_helpers.py").write_text( + "import lineage_test_io # noqa: F401 registers the test reader/writer\n" + "from datacustomcode.client import Client\n" + "from datacustomcode.io.writer.base import WriteMode\n" + "client = Client()\n" + "def save(df):\n" + " client.write_to_dlo('out__dll', df, WriteMode.APPEND)\n" + ) + monkeypatch.syspath_prepend(str(tmp_path)) + entrypoint = make_package( + tmp_path, + """ + import lineage_dep_helpers + lineage_dep_helpers.save( + client.read_dlo("orders__dll").select(F.col("id").alias("id__c")) + ) + """, + ) + + result = generate_lineage( + entrypoint, config_file, dependencies=["lineage_dep_helpers"] + ) + + assert result.data_lineage == {"out__dll.id__c": ["orders__dll.id"]} + assert validated() == [("out__dll", ["id__c"])] + + +def test_repeated_generation_is_independent(tmp_path, config_file, validated): + entrypoint = make_package( + tmp_path, + """ + client.write_to_dlo( + "out__dll", + client.read_dlo("orders__dll").select(F.col("id").alias("id__c")), + WriteMode.APPEND, + ) + """, + ) + + for _ in range(2): + result = generate_lineage(entrypoint, config_file) + assert result.data_lineage == {"out__dll.id__c": ["orders__dll.id"]} + assert validated() == [("out__dll", ["id__c"])] * 2 + + +def test_client_built_with_explicit_reader_and_writer_is_captured( + tmp_path, config_file +): + # force=True overrides even a reader/writer passed straight to Client; the + # writer here would raise if it were used + entrypoint = make_package( + tmp_path, + """ + class ExplodingWriter(lineage_test_io.RefusingWriter): + CONFIG_NAME = "LineageTestExplodingWriter" + + def validate_dataframe_columns_against_dlo(self, dataframe, dlo_name): + raise AssertionError("explicit writer must not be used") + + from pyspark.sql import SparkSession + spark = SparkSession.builder.getOrCreate() + client = Client( + reader=lineage_test_io.InMemoryReader(spark), + writer=ExplodingWriter(spark), + ) + client.write_to_dlo( + "out__dll", client.read_dlo("orders__dll").select("id"), WriteMode.APPEND + ) + """, + with_client=False, + ) + + result = generate_lineage(entrypoint, config_file) + + assert result.data_lineage == {"out__dll.id": ["orders__dll.id"]} + + +def test_capture_falls_through_to_delegate_attributes(spark): + writer = LineageCaptureWriter( + spark, + AccessLayerObjectConfig(type_config_name=RefusingWriter.CONFIG_NAME), + LineageCollector(), + ) + + assert writer.validate_dataframe_columns_against_dlo is not None + assert isinstance(writer._delegate, RefusingWriter) + + +def test_result_round_trips_through_dict(): + result = LineageResult( + data_lineage={"out__dll.a__c": ["in__dll.a", "in__dll.b"]}, + unresolved={"out__dll.b__c": "untraceable source"}, + no_sources=["out__dll.c__c"], + udf_fields=["out__dll.a__c", "out__dll.c__c"], + targets=["out__dll"], + sources=["in__dll"], + ) + + assert LineageResult.from_dict(result.to_dict()).to_dict() == result.to_dict() diff --git a/tests/lineage/test_tracer.py b/tests/lineage/test_tracer.py new file mode 100644 index 00000000..30eb956d --- /dev/null +++ b/tests/lineage/test_tracer.py @@ -0,0 +1,476 @@ +"""Tests for analyzed-plan column lineage tracing (real local Spark).""" + +from __future__ import annotations + +import time + +import pandas as pd +from pyspark.sql import Window, functions as F +from pyspark.sql.types import StringType +import pytest + +from datacustomcode.lineage.tracer import ( + AMBIGUOUS_SOURCE, + UNTRACEABLE_SOURCE, + LineageTraceError, + SourceRegistry, + TraceResult, +) + +pytestmark = pytest.mark.spark + + +@pytest.fixture +def registry(): + return SourceRegistry() + + +@pytest.fixture +def orders(spark, registry): + df = spark.createDataFrame( + pd.DataFrame( + { + "id": [1, 2], + "first": ["a", "b"], + "last": ["x", "y"], + "amount": [1.0, 2.0], + "tags": [["t1", "t2"], ["t3"]], + } + ) + ) + registry.register(df, "orders__dll") + return df + + +@pytest.fixture +def customers(spark, registry): + df = spark.createDataFrame(pd.DataFrame({"id": [1, 2], "region": ["us", "eu"]})) + registry.register(df, "customers__dll") + return df + + +def sources(results: dict[str, TraceResult]) -> dict[str, set[str]]: + assert not [r for r in results.values() if r.unresolved], results + return {name: set(r.sources) for name, r in results.items()} + + +def test_passthrough(registry, orders): + assert sources(registry.trace(orders.select("id", "amount"))) == { + "id": {"orders__dll.id"}, + "amount": {"orders__dll.amount"}, + } + + +def test_rename_and_concat(registry, orders): + df = orders.select( + F.col("id").alias("order_id"), + F.concat_ws(" ", "first", "last").alias("full_name"), + ) + assert sources(registry.trace(df)) == { + "order_id": {"orders__dll.id"}, + "full_name": {"orders__dll.first", "orders__dll.last"}, + } + + +def test_filter_and_join_keys_are_not_sources(registry, orders, customers): + df = ( + orders.filter(F.col("amount") > 1) + .join(customers, orders.id == customers.id) + .select(orders["first"], customers["region"]) + ) + assert sources(registry.trace(df)) == { + "first": {"orders__dll.first"}, + "region": {"customers__dll.region"}, + } + + +def test_using_join_key_is_coalesced(registry, orders, customers): + df = orders.join(customers, "id", "full_outer").select("id") + assert sources(registry.trace(df)) == { + "id": {"orders__dll.id", "customers__dll.id"} + } + + +def test_python_udf_inputs(registry, orders): + shout = F.udf(lambda a, b: f"{a}{b}".upper(), StringType()) + df = orders.select(shout("first", "last").alias("loud")) + results = registry.trace(df) + assert sources(results) == {"loud": {"orders__dll.first", "orders__dll.last"}} + assert results["loud"].udf + + +def test_udf_flag_marks_only_udf_columns(registry, orders): + shout = F.udf(lambda a: a.upper(), StringType()) + df = orders.select("id", F.upper("last").alias("up"), shout("first").alias("s")) + results = registry.trace(df) + assert {name for name, r in results.items() if r.udf} == {"s"} + + +def test_pandas_udf_is_flagged(registry, orders): + @F.pandas_udf("double") + def double_it(s: pd.Series) -> pd.Series: + return s * 2 + + results = registry.trace(orders.select(double_it("amount").alias("dbl"))) + assert results["dbl"] == TraceResult( + sources=frozenset({"orders__dll.amount"}), udf=True + ) + + +def test_grouped_agg_pandas_udf_is_flagged(registry, orders): + @F.pandas_udf("double") + def total(s: pd.Series) -> float: + return float(s.sum()) + + results = registry.trace(orders.groupBy("first").agg(total("amount").alias("t"))) + assert sources(results) == { + "first": {"orders__dll.first"}, + "t": {"orders__dll.amount"}, + } + assert results["t"].udf + assert not results["first"].udf + + +def test_sql_registered_udf_is_flagged(spark, registry, orders): + spark.udf.register("lineage_shout", lambda a: a.upper(), StringType()) + orders.createOrReplaceTempView("orders_udf_view") + df = spark.sql("SELECT id, lineage_shout(first) AS s FROM orders_udf_view") + results = registry.trace(df) + assert results["s"] == TraceResult( + sources=frozenset({"orders__dll.first"}), udf=True + ) + assert not results["id"].udf + + +def test_udf_flag_survives_rename_and_later_expressions(registry, orders): + shout = F.udf(lambda a: a.upper(), StringType()) + df = ( + orders.select(shout("first").alias("s"), "last") + .withColumnRenamed("s", "renamed") + .withColumn("joined", F.concat("renamed", "last")) + ) + results = registry.trace(df) + assert results["renamed"].udf + assert results["joined"] == TraceResult( + sources=frozenset({"orders__dll.first", "orders__dll.last"}), udf=True + ) + assert not results["last"].udf + + +def test_udf_without_arguments_has_no_sources_but_is_flagged(registry, orders): + constant = F.udf(lambda: "x", StringType()) + results = registry.trace(orders.select(constant().alias("c"))) + assert results["c"] == TraceResult(udf=True) + + +def test_aggregate(registry, orders): + df = orders.groupBy("first").agg(F.sum("amount").alias("total")) + assert sources(registry.trace(df)) == { + "first": {"orders__dll.first"}, + "total": {"orders__dll.amount"}, + } + + +def test_literal_has_no_sources(registry, orders): + results = registry.trace(orders.select(F.lit("const").alias("c"))) + assert results["c"] == TraceResult() + + +def test_union_is_positional(registry, orders, customers): + df = orders.select("id", "first").union(customers.select("id", "region")) + assert sources(registry.trace(df)) == { + "id": {"orders__dll.id", "customers__dll.id"}, + "first": {"orders__dll.first", "customers__dll.region"}, + } + + +def test_union_by_name(registry, orders, customers): + df = orders.select("id", F.col("first").alias("region")).unionByName( + customers.select("region", "id") + ) + assert sources(registry.trace(df)) == { + "id": {"orders__dll.id", "customers__dll.id"}, + "region": {"orders__dll.first", "customers__dll.region"}, + } + + +def test_window_keys_are_not_sources(registry, orders): + window = Window.partitionBy("first").orderBy("id") + df = orders.select("id", F.sum("amount").over(window).alias("running")) + assert sources(registry.trace(df)) == { + "id": {"orders__dll.id"}, + "running": {"orders__dll.amount"}, + } + + +def test_window_matches_group_by(registry, orders): + grouped = orders.groupBy("first").agg(F.sum("amount").alias("total")) + windowed = orders.select( + F.sum("amount").over(Window.partitionBy("first")).alias("total") + ) + assert sources(registry.trace(grouped))["total"] == {"orders__dll.amount"} + assert sources(registry.trace(windowed))["total"] == {"orders__dll.amount"} + + +def test_ranking_function_has_no_sources(registry, orders): + window = Window.partitionBy("first").orderBy("amount") + df = orders.select(F.row_number().over(window).alias("rn")) + assert sources(registry.trace(df)) == {"rn": set()} + + +def test_when_condition_is_not_a_source(registry, orders): + df = orders.select( + F.when(F.col("first") == "a", F.col("amount")) + .when(F.col("last") == "y", F.col("id")) + .otherwise(F.col("last")) + .alias("picked") + ) + assert sources(registry.trace(df)) == { + "picked": {"orders__dll.amount", "orders__dll.id", "orders__dll.last"} + } + + +def test_sql_if_condition_is_not_a_source(registry, orders): + df = orders.select(F.expr("if(first = 'a', amount, id)").alias("picked")) + assert sources(registry.trace(df)) == { + "picked": {"orders__dll.amount", "orders__dll.id"} + } + + +def test_conditional_count_has_no_sources(registry, orders): + df = orders.select(F.sum(F.when(F.col("first") == "a", 1)).alias("count_a")) + assert sources(registry.trace(df)) == {"count_a": set()} + + +def test_aggregate_filter_matches_dataframe_filter(registry, orders): + filtered = orders.filter(F.col("first") == "a").agg(F.sum("amount").alias("t")) + sql_filter = orders.agg(F.expr("sum(amount) FILTER (WHERE first = 'a')").alias("t")) + assert sources(registry.trace(filtered))["t"] == {"orders__dll.amount"} + assert sources(registry.trace(sql_filter))["t"] == {"orders__dll.amount"} + + +def test_explode(registry, orders): + df = orders.select("id", F.explode("tags").alias("tag")) + assert sources(registry.trace(df)) == { + "id": {"orders__dll.id"}, + "tag": {"orders__dll.tags"}, + } + + +def test_rollup(registry, orders): + df = orders.rollup("first").agg(F.sum("amount").alias("total")) + assert sources(registry.trace(df)) == { + "first": {"orders__dll.first"}, + "total": {"orders__dll.amount"}, + } + + +def test_self_join(registry, orders): + left, right = orders.alias("l"), orders.alias("r") + df = left.join(right, F.col("l.id") == F.col("r.id")).select( + F.col("l.first").alias("left_first"), F.col("r.last").alias("right_last") + ) + assert sources(registry.trace(df)) == { + "left_first": {"orders__dll.first"}, + "right_last": {"orders__dll.last"}, + } + + +def test_dropped_then_readded(registry, orders): + df = orders.drop("first").withColumn("first", F.upper("last")) + assert sources(registry.trace(df.select("first"))) == { + "first": {"orders__dll.last"} + } + + +def test_to_pandas_round_trip_is_untraceable(spark, registry, orders): + df = spark.createDataFrame(orders.select("id").toPandas()) + assert registry.trace(df)["id"] == TraceResult(reason=UNTRACEABLE_SOURCE) + + +def test_unregistered_dataframe_is_untraceable(spark, registry, orders): + lookup = spark.createDataFrame(pd.DataFrame({"id": [1], "label": ["one"]})) + df = orders.join(lookup, "id").select("first", "label") + results = registry.trace(df) + assert results["first"].sources == {"orders__dll.first"} + assert results["label"] == TraceResult(reason=UNTRACEABLE_SOURCE) + + +def test_opaque_operator_is_unresolved(registry, orders): + def identity(batches): + yield from batches + + df = orders.select("id").mapInPandas(identity, "id long") + assert registry.trace(df)["id"].unresolved + + +def test_scalar_subquery_is_unresolved(spark, registry, orders): + orders.createOrReplaceTempView("orders_view") + df = spark.sql( + "SELECT id, (SELECT max(amount) FROM orders_view) AS top FROM orders_view" + ) + results = registry.trace(df) + assert results["id"].sources == {"orders__dll.id"} + assert results["top"].unresolved + + +def test_wide_passthrough_is_fast(spark): + columns = [f"field_{i:04d}__c" for i in range(512)] + wide = spark.createDataFrame(pd.DataFrame([list(range(512))], columns=columns)) + registry = SourceRegistry() + registry.register(wide, "wide__dll") + + start = time.monotonic() + results = sources(registry.trace(wide.select(*columns))) + elapsed = time.monotonic() - start + + assert results == {c: {f"wide__dll.{c}"} for c in columns} + assert elapsed < 1.0 + + +def test_spark_connect_dataframe_rejected(registry): + class ConnectLike: + pass + + with pytest.raises(LineageTraceError, match="Spark Connect"): + registry.trace(ConnectLike()) # type: ignore[arg-type] + + +def test_derived_reader_column_does_not_rename_its_source(spark, registry): + # A reader that exposes both a column and a value computed from it: the + # computed column must not take over the source column's field identity + base = spark.createDataFrame(pd.DataFrame({"name": ["a", "b"]})) + source = base.select("name", F.upper("name").alias("normalized")) + registry.register(source, "source__dll") + + results = registry.trace( + source.select( + F.col("name").alias("name__c"), F.col("normalized").alias("norm__c") + ) + ) + + assert sources(results) == { + "name__c": {"source__dll.name"}, + "norm__c": {"source__dll.name"}, + } + + +def test_renamed_reader_column_names_the_field(spark, registry): + base = spark.createDataFrame(pd.DataFrame({"raw": ["a"]})) + registry.register(base.select(F.col("raw").alias("name")), "source__dll") + + traced = registry.trace(base.select(F.col("raw").alias("name__c"))) + + assert sources(traced) == {"name__c": {"source__dll.name"}} + + +def test_two_objects_over_one_relation_are_ambiguous(spark, registry): + base = spark.createDataFrame(pd.DataFrame({"id": [1], "other": [2]})) + registry.register(base, "first__dll") + registry.register(base, "second__dll") + + results = registry.trace(base.select("id")) + + assert results["id"].reason == AMBIGUOUS_SOURCE + assert results["id"].unresolved + + +def test_one_leaf_under_two_names_is_ambiguous(spark, registry): + base = spark.createDataFrame(pd.DataFrame({"id": [1]})) + registry.register(base.select("id", F.col("id").alias("id_copy")), "src__dll") + + assert registry.trace(base.select("id"))["id"].reason == AMBIGUOUS_SOURCE + + +def test_stack_outputs_trace_positionally(registry, orders): + stacked = orders.selectExpr("stack(1, first, last) AS (x, y)") + assert sources(registry.trace(stacked)) == { + "x": {"orders__dll.first"}, + "y": {"orders__dll.last"}, + } + + +def test_stack_with_several_rows(registry, orders): + stacked = orders.selectExpr( + "stack(2, first, amount, last, CAST(id AS DOUBLE)) AS (name, n)" + ) + assert sources(registry.trace(stacked)) == { + "name": {"orders__dll.first", "orders__dll.last"}, + "n": {"orders__dll.id", "orders__dll.amount"}, + } + + +def test_inline_over_built_structs_traces_each_field(registry, orders): + inlined = orders.selectExpr( + "inline(array(named_struct('a', first, 'b', last), " + "named_struct('a', last, 'b', 'constant'))) AS (x, y)" + ) + assert sources(registry.trace(inlined)) == { + "x": {"orders__dll.first", "orders__dll.last"}, + "y": {"orders__dll.last"}, + } + + +def test_inline_literal_field_has_no_sources(spark, registry): + df = spark.createDataFrame(pd.DataFrame({"name": ["a"]})) + registry.register(df, "src__dll") + inlined = df.selectExpr("inline(array(struct(name, 'constant'))) AS (x, y)") + assert sources(registry.trace(inlined)) == {"x": {"src__dll.name"}, "y": set()} + + +def test_explode_of_built_map_traces_key_and_value(spark, registry): + df = spark.createDataFrame(pd.DataFrame({"name": ["a"]})) + registry.register(df, "src__dll") + assert sources(registry.trace(df.selectExpr("explode(map('key', name))"))) == { + "key": set(), + "value": {"src__dll.name"}, + } + exploded = df.selectExpr("posexplode(map('key', name)) AS (p, k, v)") + assert sources(registry.trace(exploded)) == { + "p": {"src__dll.name"}, + "k": set(), + "v": {"src__dll.name"}, + } + + +def test_inline_over_source_struct_column_shares_its_trace(spark, registry): + df = spark.createDataFrame([([("a", 1)],)], "items array>") + registry.register(df, "src__dll") + assert sources(registry.trace(df.selectExpr("inline(items)"))) == { + "s": {"src__dll.items"}, + "n": {"src__dll.items"}, + } + + +@pytest.mark.parametrize( + "build, generate", + [ + # The struct is built in an earlier projection, hidden behind a column + ( + "array(struct(name, 'constant')) AS items", + "inline(items) AS (x, y)", + ), + # The struct is built inline but wrapped in another function + ( + "name", + "inline(filter(array(struct(name, 'constant')), s -> true)) AS (x, y)", + ), + ("map('key', name) AS m", "explode(m) AS (k, v)"), + ], +) +def test_generator_over_computed_collection_is_unresolved( + spark, registry, build, generate +): + df = spark.createDataFrame(pd.DataFrame({"name": ["a"]})) + registry.register(df, "src__dll") + results = registry.trace(df.selectExpr(build).selectExpr(generate)) + assert all(r.unresolved for r in results.values()), results + assert "cannot be traced" in next(iter(results.values())).reason + + +def test_posexplode_outputs_share_their_single_input(registry, orders): + exploded = orders.select(F.posexplode("tags").alias("pos", "tag")) + assert sources(registry.trace(exploded)) == { + "pos": {"orders__dll.tags"}, + "tag": {"orders__dll.tags"}, + } diff --git a/tests/spark/test_column_hints.py b/tests/spark/test_column_hints.py new file mode 100644 index 00000000..f4ae5ab4 --- /dev/null +++ b/tests/spark/test_column_hints.py @@ -0,0 +1,118 @@ +# 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. +"""Tests for the column-casing hint hooks.""" +from __future__ import annotations + +from pyspark.sql import SparkSession +from pyspark.sql.functions import col +import pytest + +from datacustomcode.spark.column_hints import install_column_casing_hints + +HINT_FRAGMENT = "Data Cloud columns must be lowercase" + + +@pytest.fixture(scope="module") +def spark(): + # Case-sensitive to match the Data Cloud runtime (and config.yaml). + session = ( + SparkSession.builder.master("local[1]") + .appName("column-hints-test") + .config("spark.ui.enabled", "false") + .config("spark.sql.caseSensitive", "true") + .getOrCreate() + ) + session.sparkContext.setLogLevel("OFF") + install_column_casing_hints() + yield session + session.stop() + + +@pytest.fixture +def df(spark): + # Schema is lowercase, as Data Cloud / the SDK reader would produce it. + return spark.createDataFrame( + [(1, 2.0, "x")], schema=["unitprice__c", "qty__c", "name__c"] + ) + + +# Each case references the PascalCase name "UnitPrice__c" whose lowercase form +# "unitprice__c" is a real column. All should surface the casing hint. +ACCESS_PATHS = { + "getitem": lambda df: df["UnitPrice__c"], + "select_str": lambda df: df.select("UnitPrice__c").collect(), + "col_action": lambda df: df.select(col("UnitPrice__c")).collect(), + "filter": lambda df: df.filter(col("UnitPrice__c") > 0).collect(), + "with_column": lambda df: df.withColumn("x", col("UnitPrice__c")).collect(), + "select_expr": lambda df: df.selectExpr("UnitPrice__c + 1").collect(), + "getattr": lambda df: df.UnitPrice__c, +} +# Note: df.drop("UnitPrice__c") is intentionally omitted — Spark's drop() +# silently ignores non-matching names and never raises, so there is no error +# to augment (and no silent data loss risk, since nothing is dropped). + + +@pytest.mark.parametrize("path_name", sorted(ACCESS_PATHS)) +def test_casing_hint_added_for_all_access_paths(df, path_name): + access = ACCESS_PATHS[path_name] + with pytest.raises(Exception) as excinfo: + access(df) + message = str(excinfo.value) + assert HINT_FRAGMENT in message, f"{path_name!r} did not get a casing hint" + assert "UnitPrice__c" in message + assert "unitprice__c" in message + + +def test_original_message_preserved(df): + """The hint is prepended; Spark's original error detail must remain.""" + with pytest.raises(Exception) as excinfo: + df.select("UnitPrice__c").collect() + message = str(excinfo.value) + assert HINT_FRAGMENT in message + # Spark's own UNRESOLVED_COLUMN text / suggestion list is still present. + assert "UNRESOLVED_COLUMN" in message or "cannot be resolved" in message + + +def test_genuinely_missing_column_is_not_relabelled(df): + """A column with no lowercase match keeps the vanilla Spark message.""" + with pytest.raises(Exception) as excinfo: + df.select("TotallyMissing").collect() + assert HINT_FRAGMENT not in str(excinfo.value) + + +def test_already_lowercase_missing_column_no_hint(df): + """A lowercase typo is a real error, not a casing issue — no hint.""" + with pytest.raises(Exception) as excinfo: + df.select("nonexistent__c").collect() + assert HINT_FRAGMENT not in str(excinfo.value) + + +def test_getattr_missing_no_match_keeps_attribute_error(df): + """Attribute access for a truly-absent name still raises AttributeError.""" + with pytest.raises(AttributeError): + getattr(df, "NoSuchThing") + + +def test_install_is_idempotent(): + """Repeated installs must not stack wrappers.""" + from pyspark.errors.exceptions import captured + from pyspark.sql import DataFrame + + install_column_casing_hints() + conv1 = captured.convert_exception + getattr1 = DataFrame.__getattr__ + install_column_casing_hints() + assert captured.convert_exception is conv1 + assert DataFrame.__getattr__ is getattr1 diff --git a/tests/spark/test_column_hints_deferred.py b/tests/spark/test_column_hints_deferred.py new file mode 100644 index 00000000..9c094ebc --- /dev/null +++ b/tests/spark/test_column_hints_deferred.py @@ -0,0 +1,201 @@ +# 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. +"""Tests for deferred (pyspark-free) installation of the column-casing hooks. + +These exercise ``install_column_casing_hints`` before ``pyspark.sql`` has +been imported. ``test_column_hints.py`` always imports ``pyspark.sql`` at +module scope, so it can never observe the deferred branch; the subprocess +tests here start from a clean interpreter where pyspark genuinely hasn't +been imported yet. +""" +from __future__ import annotations + +import subprocess +import sys +import textwrap + +import pytest + +from datacustomcode.spark import column_hints +from datacustomcode.spark.column_hints import _PySparkImportHook + + +def _run(script: str) -> None: + """Run *script* in a fresh interpreter; fail loudly on error.""" + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(script)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + if result.returncode != 0: + pytest.fail( + f"subprocess failed (rc={result.returncode}):\n" + f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}" + ) + + +def test_install_before_pyspark_import_does_not_import_pyspark() -> None: + _run( + """ + import sys + from datacustomcode.spark.column_hints import install_column_casing_hints + + assert "pyspark" not in sys.modules + install_column_casing_hints() + assert "pyspark" not in sys.modules + assert "pyspark.sql" not in sys.modules + """ + ) + + +def test_install_before_pyspark_import_registers_finder() -> None: + _run( + """ + import sys + from datacustomcode.spark.column_hints import ( + _PySparkImportHook, + install_column_casing_hints, + ) + + install_column_casing_hints() + hooks = [f for f in sys.meta_path if isinstance(f, _PySparkImportHook)] + assert len(hooks) == 1 + """ + ) + + +def test_repeated_deferred_install_does_not_stack_finders() -> None: + _run( + """ + import sys + from datacustomcode.spark.column_hints import ( + _PySparkImportHook, + install_column_casing_hints, + ) + + install_column_casing_hints() + install_column_casing_hints() + install_column_casing_hints() + hooks = [f for f in sys.meta_path if isinstance(f, _PySparkImportHook)] + assert len(hooks) == 1 + """ + ) + + +@pytest.mark.spark +def test_hooks_install_when_pyspark_sql_is_later_imported() -> None: + _run( + """ + from datacustomcode.spark.column_hints import ( + _WRAPPED_MARKER, + install_column_casing_hints, + ) + + install_column_casing_hints() + + import pyspark.sql # noqa: F401 - triggers the deferred install + from pyspark.errors.exceptions import captured + from pyspark.sql import DataFrame + + assert getattr(captured.convert_exception, _WRAPPED_MARKER, False) + assert getattr(DataFrame.__getattr__, _WRAPPED_MARKER, False) + """ + ) + + +@pytest.mark.spark +def test_install_installs_immediately_when_pyspark_already_loaded() -> None: + _run( + """ + import sys + + import pyspark.sql # noqa: F401 - pyspark is loaded before install + from datacustomcode.spark.column_hints import ( + _PySparkImportHook, + _WRAPPED_MARKER, + install_column_casing_hints, + ) + + install_column_casing_hints() + + from pyspark.errors.exceptions import captured + from pyspark.sql import DataFrame + + assert getattr(captured.convert_exception, _WRAPPED_MARKER, False) + assert getattr(DataFrame.__getattr__, _WRAPPED_MARKER, False) + assert not any(isinstance(f, _PySparkImportHook) for f in sys.meta_path) + """ + ) + + +class _FakeLoader: + def __init__(self) -> None: + self.exec_calls: list[object] = [] + + def exec_module(self, module: object) -> None: + self.exec_calls.append(module) + + +class _FakeSpec: + def __init__(self, loader: _FakeLoader) -> None: + self.loader = loader + + +class _FakeFinder: + """Stands in for the real pyspark finder on ``sys.meta_path``.""" + + def __init__(self, spec: object | None) -> None: + self._spec = spec + + def find_spec(self, fullname, path, target=None): # type: ignore[no-untyped-def] + return self._spec + + +def test_find_spec_ignores_other_module_names() -> None: + hook = _PySparkImportHook() + assert hook.find_spec("pyspark", None) is None + assert hook.find_spec("some.other.module", None) is None + + +def test_find_spec_returns_none_when_no_other_finder_can_resolve(monkeypatch) -> None: + hook = _PySparkImportHook() + monkeypatch.setattr(sys, "meta_path", [hook, _FakeFinder(None)]) + assert hook.find_spec("pyspark.sql", None) is None + + +def test_find_spec_wraps_loader_exec_module_and_installs_hooks_after( + monkeypatch, +) -> None: + loader = _FakeLoader() + spec = _FakeSpec(loader) + hook = _PySparkImportHook() + monkeypatch.setattr(sys, "meta_path", [hook, _FakeFinder(spec)]) + + calls: list[str] = [] + monkeypatch.setattr( + column_hints, "_install_hooks_now", lambda: calls.append("installed") + ) + + found = hook.find_spec("pyspark.sql", None) + assert found is spec + # The loader's exec_module has been swapped for a wrapper. + assert loader.exec_module is not _FakeLoader.exec_module.__get__(loader) + + fake_module = object() + spec.loader.exec_module(fake_module) + assert loader.exec_calls == [fake_module] # original behavior preserved + assert calls == ["installed"] # hint hooks installed right after diff --git a/tests/test_auth.py b/tests/test_auth.py index 974b3c0d..8095963b 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -14,12 +14,16 @@ # limitations under the License. from __future__ import annotations +import base64 +import hashlib import queue from unittest.mock import ( + ANY, MagicMock, Mock, patch, ) +from urllib.parse import parse_qs, urlparse import click import pytest @@ -28,6 +32,7 @@ from datacustomcode.auth import ( OAuthCallbackHandler, _exchange_code_for_tokens, + _generate_pkce_pair, _run_oauth_callback_server, configure_oauth_tokens, do_oauth_browser_flow, @@ -48,10 +53,11 @@ def test_do_get_with_code(self, mock_init): client_address=("127.0.0.1", 5555), server=Mock(), auth_code_queue=auth_code_queue, + expected_state="expected_state_123", ) # Mock the request path with code - handler.path = "/callback?code=test_auth_code_123" + handler.path = "/callback?code=test_auth_code_123&state=expected_state_123" handler.send_response = Mock() handler.send_header = Mock() handler.end_headers = Mock() @@ -77,9 +83,13 @@ def test_do_get_with_error(self, mock_init): client_address=("127.0.0.1", 5555), server=Mock(), auth_code_queue=auth_code_queue, + expected_state="expected_state_123", ) - handler.path = "/callback?error=access_denied&error_description=User%20denied" + handler.path = ( + "/callback?error=access_denied&error_description=User%20denied" + "&state=expected_state_123" + ) handler.send_response = Mock() handler.send_header = Mock() handler.end_headers = Mock() @@ -104,6 +114,7 @@ def test_do_get_invalid_callback(self, mock_init): client_address=("127.0.0.1", 5555), server=Mock(), auth_code_queue=auth_code_queue, + expected_state="expected_state_123", ) handler.path = "/callback" @@ -118,6 +129,63 @@ def test_do_get_invalid_callback(self, mock_init): assert auth_code_queue.empty() handler.send_response.assert_called_once_with(400) + @pytest.mark.parametrize( + "path", + [ + "/callback?code=attacker_code", + "/callback?code=attacker_code&state=", + "/callback?code=attacker_code&state=wrong_state", + "/callback?error=access_denied&state=wrong_state", + "/callback?error=access_denied", + ], + ) + @patch("datacustomcode.auth.http.server.SimpleHTTPRequestHandler.__init__") + def test_do_get_rejects_missing_or_mismatched_state(self, mock_init, path): + """Callbacks without the expected state must not reach the queue.""" + auth_code_queue = queue.Queue() + mock_init.return_value = None + + handler = OAuthCallbackHandler( + request=Mock(), + client_address=("127.0.0.1", 5555), + server=Mock(), + auth_code_queue=auth_code_queue, + expected_state="expected_state_123", + ) + handler.path = path + handler.send_response = Mock() + handler.send_header = Mock() + handler.end_headers = Mock() + handler.wfile = Mock() + + handler.do_GET() + + assert auth_code_queue.empty() + handler.send_response.assert_called_once_with(400) + + @patch("datacustomcode.auth.http.server.SimpleHTTPRequestHandler.__init__") + def test_do_get_rejects_when_no_expected_state(self, mock_init): + """A handler without an expected state fails closed.""" + auth_code_queue = queue.Queue() + mock_init.return_value = None + + handler = OAuthCallbackHandler( + request=Mock(), + client_address=("127.0.0.1", 5555), + server=Mock(), + auth_code_queue=auth_code_queue, + ) + handler.path = "/callback?code=some_code&state=anything" + handler.send_response = Mock() + handler.send_header = Mock() + handler.end_headers = Mock() + handler.wfile = Mock() + + handler.do_GET() + + assert auth_code_queue.empty() + handler.send_response.assert_called_once_with(400) + @patch("datacustomcode.auth.http.server.SimpleHTTPRequestHandler.__init__") def test_log_message_suppressed(self, mock_init): """Test that log messages are suppressed.""" @@ -148,7 +216,9 @@ def test_run_oauth_callback_server_valid_uri( mock_server.server_address = ("localhost", 5555) mock_tcpserver.return_value = mock_server - _server, port = _run_oauth_callback_server(redirect_uri, auth_code_queue) + _server, port = _run_oauth_callback_server( + redirect_uri, auth_code_queue, "state" + ) assert port == 5555 mock_tcpserver.assert_called_once() @@ -162,7 +232,7 @@ def test_run_oauth_callback_server_invalid_uri_no_host(self): auth_code_queue = queue.Queue() with pytest.raises(ValueError, match="Invalid redirect URI"): - _run_oauth_callback_server(redirect_uri, auth_code_queue) + _run_oauth_callback_server(redirect_uri, auth_code_queue, "state") def test_run_oauth_callback_server_invalid_uri_no_port(self): """Test starting callback server with invalid URI (no port).""" @@ -170,7 +240,7 @@ def test_run_oauth_callback_server_invalid_uri_no_port(self): auth_code_queue = queue.Queue() with pytest.raises(ValueError, match="Invalid redirect URI"): - _run_oauth_callback_server(redirect_uri, auth_code_queue) + _run_oauth_callback_server(redirect_uri, auth_code_queue, "state") @patch("datacustomcode.auth.socketserver.TCPServer") @patch("datacustomcode.auth.threading.Thread") @@ -186,7 +256,9 @@ def test_run_oauth_callback_server_different_port( mock_server.server_address = ("localhost", 8080) mock_tcpserver.return_value = mock_server - _server, port = _run_oauth_callback_server(redirect_uri, auth_code_queue) + _server, port = _run_oauth_callback_server( + redirect_uri, auth_code_queue, "state" + ) assert port == 8080 mock_tcpserver.assert_called_once() @@ -195,6 +267,28 @@ def test_run_oauth_callback_server_different_port( assert mock_server.allow_reuse_address is True +class TestGeneratePkcePair: + """Test suite for _generate_pkce_pair.""" + + def test_verifier_and_challenge(self): + code_verifier, code_challenge = _generate_pkce_pair() + + # RFC 7636 section 4.1: 43-128 unreserved characters + assert 43 <= len(code_verifier) <= 128 + expected = ( + base64.urlsafe_b64encode( + hashlib.sha256(code_verifier.encode("ascii")).digest() + ) + .rstrip(b"=") + .decode("ascii") + ) + assert code_challenge == expected + assert "=" not in code_challenge + + def test_pairs_are_unique(self): + assert _generate_pkce_pair()[0] != _generate_pkce_pair()[0] + + class TestExchangeCodeForTokens: """Test suite for _exchange_code_for_tokens.""" @@ -216,6 +310,7 @@ def test_exchange_code_for_tokens_success(self, mock_post): client_secret="test_client_secret", redirect_uri="http://localhost:5555/callback", auth_code="test_auth_code", + code_verifier="test_code_verifier", ) assert result["access_token"] == "test_access_token" @@ -228,6 +323,7 @@ def test_exchange_code_for_tokens_success(self, mock_post): assert call_args[1]["data"]["client_id"] == "test_client_id" assert call_args[1]["data"]["client_secret"] == "test_client_secret" assert call_args[1]["data"]["redirect_uri"] == "http://localhost:5555/callback" + assert call_args[1]["data"]["code_verifier"] == "test_code_verifier" @patch("datacustomcode.auth.requests.post") def test_exchange_code_for_tokens_http_error(self, mock_post): @@ -241,6 +337,7 @@ def test_exchange_code_for_tokens_http_error(self, mock_post): client_secret="test_client_secret", redirect_uri="http://localhost:5555/callback", auth_code="test_auth_code", + code_verifier="test_code_verifier", ) @patch("datacustomcode.auth.requests.post") @@ -255,6 +352,7 @@ def test_exchange_code_for_tokens_connection_error(self, mock_post): client_secret="test_client_secret", redirect_uri="http://localhost:5555/callback", auth_code="test_auth_code", + code_verifier="test_code_verifier", ) @patch("datacustomcode.auth.requests.post") @@ -269,6 +367,7 @@ def test_exchange_code_for_tokens_timeout(self, mock_post): client_secret="test_client_secret", redirect_uri="http://localhost:5555/callback", auth_code="test_auth_code", + code_verifier="test_code_verifier", ) @@ -288,7 +387,7 @@ def test_do_oauth_browser_flow_success( auth_code_queue = queue.Queue() auth_code_queue.put("test_auth_code") - def server_factory(redirect_uri, queue): + def server_factory(redirect_uri, queue, expected_state): return (mock_server_instance, 5555) mock_server.side_effect = server_factory @@ -315,9 +414,34 @@ def server_factory(redirect_uri, queue): "test_client_secret", "http://localhost:5555/callback", "test_auth_code", + ANY, ) mock_server_instance.shutdown.assert_called() + # Authorize URL carries state + S256 PKCE challenge + auth_url = mock_browser.call_args[0][0] + params = parse_qs(urlparse(auth_url).query) + assert params["response_type"] == ["code"] + assert params["client_id"] == ["test_client_id"] + assert params["redirect_uri"] == ["http://localhost:5555/callback"] + assert params["code_challenge_method"] == ["S256"] + + # The callback server expects the same state sent to the browser + server_state = mock_server.call_args[0][2] + assert params["state"] == [server_state] + assert len(server_state) >= 32 + + # The verifier sent at token exchange matches the challenge + code_verifier = mock_exchange.call_args[0][5] + expected_challenge = ( + base64.urlsafe_b64encode( + hashlib.sha256(code_verifier.encode("ascii")).digest() + ) + .rstrip(b"=") + .decode("ascii") + ) + assert params["code_challenge"] == [expected_challenge] + @patch("datacustomcode.auth.webbrowser.open") @patch("datacustomcode.auth._run_oauth_callback_server") @patch("datacustomcode.auth.click.echo") @@ -325,7 +449,7 @@ def test_do_oauth_browser_flow_timeout(self, mock_echo, mock_server, mock_browse """Test OAuth browser flow with timeout.""" mock_server_instance = MagicMock() - def server_factory(redirect_uri, queue): + def server_factory(redirect_uri, queue, expected_state): return (mock_server_instance, 5555) mock_server.side_effect = server_factory @@ -356,7 +480,7 @@ def test_do_oauth_browser_flow_oauth_error( """Test OAuth browser flow with OAuth error response.""" mock_server_instance = MagicMock() - def server_factory(redirect_uri, queue): + def server_factory(redirect_uri, queue, expected_state): return (mock_server_instance, 5555) mock_server.side_effect = server_factory @@ -388,7 +512,7 @@ def test_do_oauth_browser_flow_no_refresh_token( """Test OAuth browser flow when no refresh token is returned.""" mock_server_instance = MagicMock() - def server_factory(redirect_uri, queue): + def server_factory(redirect_uri, queue, expected_state): return (mock_server_instance, 5555) mock_server.side_effect = server_factory diff --git a/tests/test_client.py b/tests/test_client.py index 4f3f2f47..748c0fc9 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -159,6 +159,44 @@ def test_initialization_with_config(self, mock_config, reset_client, mock_spark) assert client._reader is mock_reader assert client._writer is mock_writer + @patch("datacustomcode.client.config") + def test_forced_config_overrides_provided_reader_and_writer( + self, mock_config, reset_client, mock_spark + ): + """Forced configs replace a passed reader and writer, which needs a + session even though both were provided.""" + from datacustomcode.spark.default import DefaultSparkSessionProvider + + with patch.object( + DefaultSparkSessionProvider, "get_session" + ) as mock_get_session: + mock_get_session.return_value = mock_spark + + mock_reader = MagicMock(spec=BaseDataCloudReader) + mock_reader_config = MagicMock() + mock_reader_config.to_object.return_value = mock_reader + mock_reader_config.force = True + + mock_writer = MagicMock(spec=BaseDataCloudWriter) + mock_writer_config = MagicMock() + mock_writer_config.to_object.return_value = mock_writer + mock_writer_config.force = True + + mock_config.spark_provider_config = None + mock_config.reader_config = mock_reader_config + mock_config.writer_config = mock_writer_config + mock_config.spark_config = MagicMock(spec=SparkConfig) + + client = Client( + reader=MagicMock(spec=BaseDataCloudReader), + writer=MagicMock(spec=BaseDataCloudWriter), + ) + + mock_reader_config.to_object.assert_called_once_with(mock_spark) + mock_writer_config.to_object.assert_called_once_with(mock_spark) + assert client._reader is mock_reader + assert client._writer is mock_writer + def test_read_dlo(self, reset_client, mock_spark): reader = MagicMock(spec=BaseDataCloudReader) writer = MagicMock(spec=BaseDataCloudWriter) @@ -402,6 +440,40 @@ def test_write_dlo_deltas_after_dmo_read_raises_exception( assert "test_dmo" in str(exc_info.value) writer.write_dlo_deltas.assert_not_called() + def test_write_dmo_deltas(self, reset_client, mock_spark): + reader = MagicMock(spec=BaseDataCloudReader) + writer = MagicMock(spec=BaseDataCloudWriter) + mock_df = MagicMock(spec=DataFrame) + mock_query = MagicMock() + writer.write_dmo_deltas.return_value = mock_query + + client = StreamingClient(reader=reader, writer=writer) + client._record_dmo_access("some_dmo") + + result = client.write_dmo_deltas("test_dmo", mock_df, extra_param=True) + + writer.write_dmo_deltas.assert_called_once_with( + "test_dmo", mock_df, extra_param=True + ) + assert result is mock_query + + def test_write_dmo_deltas_after_dlo_read_raises_exception( + self, reset_client, mock_spark + ): + """Streaming DMO write is subject to the same DLO/DMO mixing guard.""" + reader = MagicMock(spec=BaseDataCloudReader) + writer = MagicMock(spec=BaseDataCloudWriter) + mock_df = MagicMock(spec=DataFrame) + + client = StreamingClient(reader=reader, writer=writer) + client._record_dlo_access("test_dlo") + + with pytest.raises(DataCloudAccessLayerException) as exc_info: + client.write_dmo_deltas("test_dmo", mock_df) + + assert "test_dlo" in str(exc_info.value) + writer.write_dmo_deltas.assert_not_called() + def test_streaming_read_write_flow(self, reset_client, mock_spark): """A read_dlo_deltas → write_dlo_deltas flow stays within the DLO layer.""" reader = MagicMock(spec=BaseDataCloudReader) @@ -420,6 +492,24 @@ def test_streaming_read_write_flow(self, reset_client, mock_spark): writer.write_dlo_deltas.assert_called_once_with("target_dll", stream_df) assert "source_dll" in client._data_layer_history[DataCloudObjectType.DLO] + def test_streaming_dmo_read_write_flow(self, reset_client, mock_spark): + """A read_dmo_deltas → write_dmo_deltas flow stays within the DMO layer.""" + reader = MagicMock(spec=BaseDataCloudReader) + writer = MagicMock(spec=BaseDataCloudWriter) + stream_df = MagicMock(spec=DataFrame) + reader.read_dmo_deltas.return_value = stream_df + + client = StreamingClient(reader=reader, writer=writer) + + 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) + + reader.read_dmo_deltas.assert_called_once_with() + writer.write_dmo_deltas.assert_called_once_with("target_dlm", stream_df) + assert "source_dlm" in client._data_layer_history[DataCloudObjectType.DMO] + def test_auto_write_to_dlo(self, reset_client, mock_spark): reader = MagicMock(spec=BaseDataCloudReader) writer = MagicMock(spec=BaseDataCloudWriter) @@ -733,6 +823,27 @@ def test_delegates_to_spark_named_credential(self, mock_build, reset_client): assert result is sentinel_col mock_nc.request_col.assert_called_once_with(request, body=body_col) + @patch("datacustomcode.client._build_spark_named_credential") + def test_forwards_per_row_path_column(self, mock_build, reset_client): + mock_nc = MagicMock() + sentinel_col = MagicMock(name="col") + mock_nc.request_col.return_value = sentinel_col + mock_build.return_value = mock_nc + + reader = MagicMock(spec=BaseDataCloudReader) + writer = MagicMock(spec=BaseDataCloudWriter) + Client(reader=reader, writer=writer) + + request = MagicMock(name="request") + body_col = MagicMock(name="body_col") + path_col = MagicMock(name="path_col") + result = named_credential_request_col(request, body_col, path=path_col) + + assert result is sentinel_col + mock_nc.request_col.assert_called_once_with( + request, body=body_col, path=path_col + ) + class TestClientNamedCredentialRequest: diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 0cbaf156..dc167a00 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -841,6 +841,44 @@ def test_zip_excludes_ds_store_and_external_credentials( assert not any(".DS_Store" in path for path in written) +class TestZipSymlinks: + """zip() must skip symlinked files instead of following them into the archive.""" + + @pytest.fixture + def mocks(self): + with ( + patch( + "datacustomcode.deploy.has_nonempty_requirements_file", + return_value=False, + ), + patch("zipfile.ZipFile") as mock_zipfile, + patch("os.walk") as mock_walk, + ): + yield mock_walk, mock_zipfile.return_value.__enter__.return_value + + def test_zip_skips_symlinked_files(self, mocks): + mock_walk, mock_zipfile_instance = mocks + mock_walk.return_value = [ + ("/test/dir", ["subdir"], ["entrypoint.py", "linked.txt"]), + ("/test/dir/subdir", [], ["nested.py", "linked.py"]), + ] + links = {"/test/dir/linked.txt", "/test/dir/subdir/linked.py"} + + with patch("os.path.islink", side_effect=lambda path: path in links): + zip("/test/dir", "default", "script") + + written = [call.args[0] for call in mock_zipfile_instance.write.call_args_list] + assert written == ["/test/dir/entrypoint.py", "/test/dir/subdir/nested.py"] + + def test_zip_skips_symlinked_directories(self, mocks): + mock_walk, _ = mocks + mock_walk.return_value = [] + + zip("/test/dir", "default", "script") + + mock_walk.assert_called_once_with("/test/dir", followlinks=False) + + class TestUploadZip: @patch("datacustomcode.deploy.requests.put") @patch("builtins.open", new_callable=mock_open, read_data=b"test data") @@ -1097,6 +1135,37 @@ def test_get_config_dmo_with_data_objects(self, mock_file): assert obj.fields[0].dataType == "text" assert obj.fields[0].keyQualifierFieldName == "KQ_Id1__c" + @patch( + "builtins.open", + new_callable=mock_open, + read_data=( + '{"sdkVersion": "0.1.14", "entryPoint": "entrypoint.py", ' + '"dataspace": "default", ' + '"permissions": {"read": {"dlo": ["input_dlo"]}, ' + '"write": {"dlo": ["output_dlo"]}}, ' + '"dataObjects": [{' + '"name": "output_dlo", ' + '"label": "Output DLO", ' + '"type": "dataLakeObject", ' + '"category": "profile", ' + '"fields": [{"name": "Id__c", "label": "Id", ' + '"dataType": "text", "isPrimaryKey": true, ' + '"keyQualifierFieldName": "KQ_Id1__c"}]' + "}]}" + ), + ) + def test_get_config_dlo_with_data_objects(self, mock_file): + """config.json parses the optional dataObjects schema for DLO writes.""" + result = get_config("/test/dir") + assert isinstance(result, DataTransformConfig) + assert result.dataObjects is not None + assert len(result.dataObjects) == 1 + obj = result.dataObjects[0] + assert obj.name == "output_dlo" + assert obj.category == "profile" + assert obj.fields[0].dataType == "text" + assert obj.fields[0].keyQualifierFieldName == "KQ_Id1__c" + class TestCreateDataTransform: @patch("datacustomcode.deploy.get_config") @@ -1365,12 +1434,93 @@ def test_create_data_transform_dmo_emits_output_data_objects( } ] + @patch("datacustomcode.deploy.get_config") + @patch("datacustomcode.deploy._make_api_call") + def test_create_data_transform_dlo_emits_output_data_objects( + self, mock_make_api_call, mock_get_config + ): + """DLO transforms include outputDataObjects with transformed field names.""" + access_token = AccessTokenResponse( + access_token="test_token", instance_url="https://instance.example.com" + ) + metadata = CodeExtensionMetadata( + name="test_package", + version="1.0.0", + description="DLO with schema", + computeType="CPU_M", + codeType="script", + ) + + data_transform_config = DataTransformConfig( + sdkVersion="0.1.14", + entryPoint="entrypoint.py", + dataspace="default", + permissions=Permissions( + read=DloPermission(dlo=["input_dlo"]), + write=DloPermission(dlo=["output_dlo"]), + ), + dataObjects=[ + DataObject( + name="output_dlo", + label="Output DLO", + type="dataLakeObject", + category="profile", + fields=[ + DataObjectField( + name="Id__c", + label="Id", + dataType="text", + isPrimaryKey=True, + keyQualifierFieldName="KQ_Id1__c", + ), + DataObjectField( + name="KQ_Id1__c", + label="Key Qualifier Id", + dataType="text", + isPrimaryKey=False, + keyQualifierFieldName=None, + ), + ], + ) + ], + ) + mock_make_api_call.return_value = {"id": "transform_id"} + + create_data_transform( + "/test/dir", access_token, metadata, data_transform_config + ) + + request_body = mock_make_api_call.call_args[1]["json"] + assert request_body["definition"]["outputDataObjects"] == [ + { + "category": "profile", + "fields": [ + { + "isPrimaryKey": True, + "keyQualifierField": "KQ_Id1__c", + "label": "Id", + "name": "Id__c", + "type": "text", + }, + { + "isPrimaryKey": False, + "label": "Key Qualifier Id", + "name": "KQ_Id1__c", + "type": "text", + }, + ], + "label": "Output DLO", + "name": "output_dlo", + "type": "dataLakeObject", + } + ] + @patch("datacustomcode.deploy.get_config") @patch("datacustomcode.deploy._make_api_call") def test_create_data_transform_dlo_omits_output_data_objects( self, mock_make_api_call, mock_get_config ): - """DLO transforms must not include outputDataObjects in the payload.""" + """DLO transforms without dataObjects omit outputDataObjects from the payload""" access_token = AccessTokenResponse( access_token="test_token", instance_url="https://instance.example.com" ) @@ -1533,9 +1683,7 @@ def test_is_streaming_false_when_source_absent(self): ) assert config.is_streaming is False - def test_streaming_allows_dmo_read_dlo_write(self): - """Streaming may read a DMO change feed and write a DLO (writes are - DLO-only)""" + def test_streaming_allows_dmo_read_dmo_write(self): config = DataTransformConfig( sdkVersion="1.0.0", entryPoint="entrypoint.py", @@ -1543,24 +1691,24 @@ def test_streaming_allows_dmo_read_dlo_write(self): streamingSource=StreamingSource(type="dmo", name="input_dmo__dlm"), permissions=Permissions( read=DmoPermission(dmo=["input_dmo__dlm"]), - write=DloPermission(dlo=["output_dlo"]), + write=DmoPermission(dmo=["output_dmo__dlm"]), ), ) assert config.is_streaming is True assert isinstance(config.permissions.read, DmoPermission) - assert isinstance(config.permissions.write, DloPermission) + assert isinstance(config.permissions.write, DmoPermission) - def test_streaming_rejects_dmo_write(self): - """Streaming writes must target a DLO.""" - with pytest.raises(ValueError, match="must write to a DLO"): + def test_streaming_rejects_dmo_read_dlo_write(self): + """Streaming follows the same same-layer rule as batch.""" + with pytest.raises(ValueError, match="both reference"): DataTransformConfig( sdkVersion="1.0.0", entryPoint="entrypoint.py", dataspace="default", - streamingSource=StreamingSource(type="dlo", name="input_dlo"), + streamingSource=StreamingSource(type="dmo", name="input_dmo__dlm"), permissions=Permissions( - read=DloPermission(dlo=["input_dlo"]), - write=DmoPermission(dmo=["output_dmo__dlm"]), + read=DmoPermission(dmo=["input_dmo__dlm"]), + write=DloPermission(dlo=["output_dlo"]), ), ) diff --git a/tests/test_describe_supported_signatures.py b/tests/test_describe_supported_signatures.py new file mode 100644 index 00000000..767a28a3 --- /dev/null +++ b/tests/test_describe_supported_signatures.py @@ -0,0 +1,23 @@ +from datacustomcode.deploy import describe_supported_signatures + + +def test_describe_supported_signatures(tmp_path): + entrypoint = tmp_path / "entrypoint.py" + chunk_pair = ( + "SearchIndexChunkingV1Request/SearchIndexChunkingV1Response " + "for use_in_feature: SearchIndexChunking" + ) + + def describe(request_type, response_type): + entrypoint.write_text( + f"def function(request: {request_type}, runtime)" + f" -> {response_type}:\n pass\n" + ) + return describe_supported_signatures(str(entrypoint)) + + # A recognised request or response narrows the hint to its own feature + assert describe("SearchIndexChunkingV1Request", "dict") == chunk_pair + assert describe("dict", "SearchIndexChunkingV1Response") == chunk_pair + # Unrecognised types fall back to listing every supported pair + fallback = describe("dict", "dict") + assert fallback == chunk_pair diff --git a/tests/test_named_credential.py b/tests/test_named_credential.py index d486a743..70a73999 100644 --- a/tests/test_named_credential.py +++ b/tests/test_named_credential.py @@ -403,6 +403,138 @@ def test_defaults_body_to_typed_null_column(self, mock_lit, mock_udf): # With no body column, a typed null string column is applied instead. sentinel_udf.assert_called_once_with(null_col) + @patch("pyspark.sql.functions.udf") + @patch("pyspark.sql.functions.lit") + def test_per_row_path_is_appended_to_request_url(self, mock_lit, mock_udf): + from datacustomcode.named_credential.spark_default import ( + DefaultSparkNamedCredential, + ) + + sentinel_udf = MagicMock(name="udf") + mock_udf.return_value = sentinel_udf + + underlying = MagicMock() + underlying.request.return_value = HTTPResponse( + status_code=200, headers={}, body="{}" + ) + spark_nc = DefaultSparkNamedCredential(named_credential=underlying) + + request = ( + HTTPRequestBuilder() + .set_url("callout:gemini") + .set_method("POST") + .set_headers({"Accept": "application/json"}) + .build() + ) + body_col = MagicMock(name="body_col") + path_col = MagicMock(name="path_col") + spark_nc.request_col(request, body_col, path=path_col) + + # The UDF is applied over both the body and the per-row path columns. + sentinel_udf.assert_called_once_with(body_col, path_col) + + udf_fn = mock_udf.call_args.args[0] + out = udf_fn('{"q": 1}', "/gemini-2.5-pro") + + assert out["status"] == "SUCCESS" + sent_request, sent_body = underlying.request.call_args.args + # The row's path is joined onto the template url; method/headers kept. + assert sent_request.url == "callout:gemini/gemini-2.5-pro" + assert sent_request.method == "POST" + assert sent_request.headers == {"Accept": "application/json"} + assert sent_body == '{"q": 1}' + # The caller's template request is left untouched. + assert request.url == "callout:gemini" + + @pytest.mark.parametrize( + "base, path, expected", + [ + ("callout:gemini", "/v1/models", "callout:gemini/v1/models"), + ("callout:gemini", "?key=a", "callout:gemini?key=a"), + ( + "callout:Geo/geocode", + "?address=1+Main", + "callout:Geo/geocode?address=1+Main", + ), + ("callout:Geo/v1", "/places/42", "callout:Geo/v1/places/42"), + # Without a leading separator a "/" is inserted, so the row can never + # extend the Named Credential name (callout:gemini2/...). + ("callout:gemini", "2/v1", "callout:gemini/2/v1"), + ("callout:gemini", "@evil.example.com", "callout:gemini/@evil.example.com"), + ], + ) + @patch("pyspark.sql.functions.udf") + @patch("pyspark.sql.functions.lit") + def test_path_join_keeps_named_credential_fixed( + self, mock_lit, mock_udf, base, path, expected + ): + from datacustomcode.named_credential.spark_default import ( + DefaultSparkNamedCredential, + ) + + mock_udf.return_value = MagicMock(name="udf") + underlying = MagicMock() + underlying.request.return_value = HTTPResponse( + status_code=200, headers={}, body="" + ) + spark_nc = DefaultSparkNamedCredential(named_credential=underlying) + + request = HTTPRequestBuilder().set_url(base).build() + spark_nc.request_col(request, path=MagicMock(name="path_col")) + + udf_fn = mock_udf.call_args.args[0] + udf_fn(None, path) + + assert underlying.request.call_args.args[0].url == expected + + @pytest.mark.parametrize("path", [None, ""]) + @patch("pyspark.sql.functions.udf") + @patch("pyspark.sql.functions.lit") + def test_null_or_empty_row_path_uses_request_url(self, mock_lit, mock_udf, path): + from datacustomcode.named_credential.spark_default import ( + DefaultSparkNamedCredential, + ) + + mock_udf.return_value = MagicMock(name="udf") + + underlying = MagicMock() + underlying.request.return_value = HTTPResponse( + status_code=200, headers={}, body="" + ) + spark_nc = DefaultSparkNamedCredential(named_credential=underlying) + + request = HTTPRequestBuilder().set_url("callout:NC/default").build() + spark_nc.request_col(request, path=MagicMock(name="path_col")) + + udf_fn = mock_udf.call_args.args[0] + udf_fn('{"a": 1}', path) + + sent_request, sent_body = underlying.request.call_args.args + assert sent_request is request + assert sent_body == '{"a": 1}' + + @patch("pyspark.sql.functions.udf") + @patch("pyspark.sql.functions.lit") + def test_path_without_body_applies_typed_null_body(self, mock_lit, mock_udf): + from datacustomcode.named_credential.spark_default import ( + DefaultSparkNamedCredential, + ) + + null_col = MagicMock(name="null_col") + lit_none = MagicMock(name="lit_none") + lit_none.cast.return_value = null_col + mock_lit.return_value = lit_none + + sentinel_udf = MagicMock(name="udf") + mock_udf.return_value = sentinel_udf + + spark_nc = DefaultSparkNamedCredential(named_credential=MagicMock()) + request = HTTPRequestBuilder().set_url("callout:NC/status").build() + path_col = MagicMock(name="path_col") + spark_nc.request_col(request, path=path_col) + + sentinel_udf.assert_called_once_with(null_col, path_col) + class TestInvokeCalloutAsStruct: """The callout-to-struct shaping shared by every row.""" diff --git a/tests/test_run.py b/tests/test_run.py index 154b0bf9..c09db5f6 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -575,3 +575,32 @@ def test_streaming_source_set_from_streaming_source_field(self): def test_streaming_source_none_for_batch_without_field(self): content = self._run_capturing_streaming_source({"dataspace": "default"}) assert "streaming_source: None" in content + + +def test_prepare_run_resolves_without_executing(tmp_path): + from datacustomcode.run import prepare_run + + entrypoint = tmp_path / "entrypoint.py" + entrypoint.write_text("raise AssertionError('must not run')\n") + (tmp_path / "config.json").write_text(json.dumps({"dataspace": "ds1"})) + + context = prepare_run(str(entrypoint), None, [], "default") + + assert context.package_type == "script" + assert context.config_json == {"dataspace": "ds1"} + assert config.reader_config.options["dataspace"] == "ds1" + + +def test_execute_entrypoint_runs_prepared_script(tmp_path): + from datacustomcode.run import execute_entrypoint, prepare_run + + marker = tmp_path / "ran.txt" + entrypoint = tmp_path / "entrypoint.py" + entrypoint.write_text(f"open({str(marker)!r}, 'w').write(__name__)\n") + (tmp_path / "config.json").write_text(json.dumps({"dataspace": "default"})) + + context = prepare_run(str(entrypoint), None, [], "default") + assert not marker.exists() + execute_entrypoint(str(entrypoint), context) + + assert marker.read_text() == "__main__" diff --git a/tests/test_scan.py b/tests/test_scan.py index 716c233c..71ead13d 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -735,7 +735,7 @@ def my_function(event, context): client = StreamingClient() deltas = client.read_dmo_deltas() - query = client.write_dlo_deltas("Account_copy__dll", deltas) + query = client.write_dmo_deltas("Account_copy__dlm", deltas) query.awaitTermination() """ ) @@ -751,6 +751,13 @@ def test_file_is_streaming_true_for_delta_methods(self): finally: os.unlink(temp_path) + def test_file_is_streaming_true_for_dmo_delta_methods(self): + temp_path = create_test_script(STREAMING_DMO_ENTRYPOINT) + try: + assert file_is_streaming(temp_path) is True + finally: + os.unlink(temp_path) + def test_file_is_streaming_false_for_batch(self): content = textwrap.dedent( """ @@ -778,13 +785,72 @@ def test_scan_file_streaming_dlo(self): finally: os.unlink(temp_path) - def test_scan_file_streaming_dmo_read(self): + def test_scan_file_streaming_dmo(self): temp_path = create_test_script(STREAMING_DMO_ENTRYPOINT) try: result = scan_file_streaming(temp_path) + assert result.read_dlo_deltas is False assert result.read_dmo_deltas is True assert result.read_layer == "dmo" - assert "Account_copy__dll" in result.write_dlo_deltas + assert "Account_copy__dlm" in result.write_dmo_deltas + assert result.write_layer == "dmo" + assert not result.write_dlo_deltas + finally: + os.unlink(temp_path) + + def test_scan_file_streaming_rejects_both_write_methods(self): + content = textwrap.dedent( + """ + from datacustomcode.client import StreamingClient + + client = StreamingClient() + deltas = client.read_dlo_deltas() + client.write_dlo_deltas("Account_copy__dll", deltas) + client.write_dmo_deltas("Account_copy__dlm", deltas) + """ + ) + temp_path = create_test_script(content) + try: + with pytest.raises(ValueError, match="Cannot write DLO and DMO deltas"): + scan_file_streaming(temp_path) + finally: + os.unlink(temp_path) + + def test_scan_file_streaming_rejects_dlo_read_dmo_write(self): + content = textwrap.dedent( + """ + from datacustomcode.client import StreamingClient + + client = StreamingClient() + deltas = client.read_dlo_deltas() + client.write_dmo_deltas("Account_copy__dlm", deltas) + """ + ) + temp_path = create_test_script(content) + try: + with pytest.raises( + ValueError, match=r"same layer \(got read=dlo, write=dmo\)" + ): + scan_file_streaming(temp_path) + finally: + os.unlink(temp_path) + + def test_scan_file_streaming_rejects_dmo_read_dlo_write(self): + content = textwrap.dedent( + """ + from datacustomcode.client import StreamingClient + + client = StreamingClient() + deltas = client.read_dmo_deltas() + client.write_dlo_deltas("Account_copy__dll", deltas) + """ + ) + temp_path = create_test_script(content) + try: + with pytest.raises( + ValueError, match=r"same layer \(got read=dmo, write=dlo\)" + ): + scan_file_streaming(temp_path) finally: os.unlink(temp_path) @@ -875,6 +941,7 @@ def test_reasserts_layer_from_code(self): assert updated["streamingSource"]["type"] == "dmo" assert updated["streamingSource"]["name"] == "Account__dlm" assert updated["permissions"]["read"]["dmo"] == ["Account__dlm"] + assert updated["permissions"]["write"] == {"dmo": ["Account_copy__dlm"]} def test_batch_entrypoint_drops_stale_streaming_source(self): """Switching a streaming entrypoint to batch clears streamingSource.""" diff --git a/tests/test_template.py b/tests/test_template.py index 7475a971..89c0c3e9 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -114,3 +114,28 @@ def test_copy_template_with_existing_content(self, temp_dir): template_items = os.listdir(script_template_dir) for item in template_items: assert os.path.exists(os.path.join(temp_dir, item)) + + # --- streaming=True behavior --- + + def test_copy_template_streaming_writes_config_yaml(self, temp_dir): + """Design: streaming init drops a config.yaml at the project root + that wires LocalDeltasReader + LocalDeltasWriter, so + `datacustomcode run` picks the streaming reader/writer via + run.py's auto-discovery. + """ + copy_script_template(temp_dir, streaming=True) + + config_yaml = os.path.join(temp_dir, "config.yaml") + assert os.path.isfile(config_yaml) + content = open(config_yaml).read() + assert "LocalDeltasReader" in content + assert "LocalDeltasWriter" in content + + def test_copy_template_default_batch_omits_streaming_config(self, temp_dir): + """Design: batch init MUST NOT write config.yaml — batch projects + keep using the SDK-shipped default (QueryAPIDataCloudReader + + PrintDataCloudWriter). Regression guard: dropping a project-local + config.yaml would silently override the batch profile. + """ + copy_script_template(temp_dir) + assert not os.path.exists(os.path.join(temp_dir, "config.yaml"))