spark-test commented on code in PR #60546: URL: https://github.com/apache/spark/pull/60546#discussion_r4584916686
########## examples/src/main/python/pipelines/hello_world/transformations/orders.py: ########## @@ -0,0 +1,49 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# + +""" +Python datasets for the hello_world pipeline. + +- `customers` is a materialized view computed from a small in-line batch dataset. +- `orders` is a streaming table that incrementally ingests the JSON files in `data/orders/`. + Each run processes only the files that arrived since the previous run. +""" + +from pathlib import Path + +from pyspark import pipelines as dp +from pyspark.sql import DataFrame, SparkSession + +# SDP also injects the session as `spark`; assigning it explicitly keeps linters happy. +spark = SparkSession.active() + +ORDERS_DIR = (Path(__file__).parent.parent / "data" / "orders").resolve().as_uri() + + [email protected]_view +def customers() -> DataFrame: + return spark.createDataFrame( + [(1, "Alice", "US"), (2, "Bob", "DE"), (3, "Carol", "US")], + "customer_id INT, name STRING, country STRING", Review Comment: **Non-blocking (P2):** With Spark Connect, `createDataFrame` parses a string schema by sending an AnalyzePlan `ddl_parse` request. SDP calls this function while it registers the materialized view, inside a pipeline analysis context, and the server rejects every analysis request made there with `ATTEMPT_ANALYSIS_IN_PIPELINE_QUERY_FUNCTION`. By this review's reading of the CLI and Spark Connect code, every `spark-pipelines run` and `dry-run` of the copied example therefore fails while it loads definitions, and readers copy a pattern that SDP rejects. The companion changes, as the PR description describes them, do not touch this path. Building the schema as a `StructType` from `pyspark.sql.types` (`customer_id` as `IntegerType()`, `name` and `country` as `StringType()`) avoids the request and keeps the column types. A list of column names would also avoid it, but would infer `customer_id` as BIGINT. The `orders` reader's DDL schema string is fine: the streaming reader sends it inside the plan instead of parsing it with a separate request. **Verification:** - **Regression:** Running spark-pipelines dry-run on the copied example loads every definition without ATTEMPT_ANALYSIS_IN_PIPELINE_QUERY_FUNCTION, where the current files fail while registering customers. - **Behavior:** After a run of the example with the storage fix and both companion changes applied, customers has the columns customer_id INT, name STRING and country STRING with its three in-line rows, and revenue_by_country shows the per-country results the README lists. ########## examples/src/main/python/pipelines/hello_world/spark-pipeline.yml: ########## @@ -0,0 +1,27 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# + +name: hello_world +# Relative paths are resolved against the directory that contains this file. +storage: pipeline-storage Review Comment: **Non-blocking (P2):** `spark-pipelines` does not resolve `storage` against this file's directory: it sends the value to the server unchanged, and only the `libraries` globs are resolved relative to the spec. The server checks the storage root when it builds the run context, before it branches on dry-run, and rejects with `PIPELINE_STORAGE_ROOT_INVALID` any value that is not an absolute URI with a scheme; its unit tests reject bare names such as `pipelines`. By this review's reading of that code, every run and dry-run of the example fails, even with the `customers` problem fixed and both companion changes merged, and the comment on line 19 documents a rule that SDP does not implement. Projects from `spark-pipelines init`, which the quick start uses, get an absolute `file://` URI and are not affected. **Recommended change:** Give the example an absolute storage root inside the copied project, the way spark-pipelines init does. Remove the relative storage line and its comment from spark-pipeline.yml, leaving a comment that README step 1 adds storage. Then add a command to README step 1, after cd /tmp/hello_world, that appends storage: "file://$PWD/pipeline-storage" to spark-pipeline.yml. **Why this works:** spark-pipelines sends the spec's storage value to the server unchanged, and the server accepts only an absolute URI with a scheme. Writing the URI when the project is copied gives every later run and dry-run a value the check accepts. It also keeps the checkpoints in the project directory, next to spark-warehouse/ and metastore_db/, which the README's start-over step deletes together. **Scope:** Example-only change: the hello world spec and README step 1 together give the example an absolute storage root inside the copied project. No Spark code changes. **Compatibility:** The quick start, whose spark-pipelines init project already carries an absolute storage URI, and the server's storage-root validation stay unchanged. **Risks:** Readers who skip the new command in step 1 get PIPELINE_SPEC_MISSING_REQUIRED_FIELD for storage, an explicit error that names the missing field. A copy destination whose path contains a double quote or a backslash would need different quoting in the appended line; the README's /tmp/hello_world destination contains neither. **Constraints:** Keep the storage root inside the copied project, so that deleting spark-warehouse/, metastore_db/ and pipeline-storage/ there, as the README says, removes all pipeline state. Leave the spec's other fields unchanged, including spark.sql.catalogImplementation: hive, which still relies on the companion change that skips static settings in per-flow configuration. **Exclusions:** - Resolving a relative storage value against the spec file's directory in the spark-pipelines CLI is left to a separate change; the server's storage-root check and the CLI's pass-through of storage stay as they are. **Success:** After README step 1, the copied project's spark-pipeline.yml names an absolute file:// storage URI inside that project. spark-pipelines run and dry-run in the copied project pass the storage-root check, and the first run writes streaming checkpoints under the project's pipeline-storage/. The shipped spec no longer claims that relative paths are resolved against its directory. **Verification:** - **Regression:** With the customers schema fix and both companion changes applied, running spark-pipelines dry-run after README step 1, and then README steps 2 to 5, in a fresh environment completes every command without PIPELINE_STORAGE_ROOT_INVALID, and the runs print the outputs the README shows. - **Behavior:** After step 4, deleting spark-warehouse/, metastore_db/ and pipeline-storage/ in the copied project and running again rebuilds orders from both batches, which shows that no checkpoint is left outside the project. ########## docs/declarative-pipelines-quick-start.md: ########## @@ -0,0 +1,236 @@ +--- +layout: global +title: Spark Declarative Pipelines Quick Start +displayTitle: Spark Declarative Pipelines Quick Start +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You 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. +--- + +* Table of contents +{:toc} + +This page takes you from an empty machine to a running [Spark Declarative Pipelines (SDP)](declarative-pipelines-programming-guide.html) +pipeline on your laptop. You install PySpark, generate a pipeline project, run it, query its +output tables, and then add a streaming table and a materialized view that depends on it. + +## Prerequisites + +- Java 21 or 25. `java` must be on your `PATH`, or `JAVA_HOME` must point to the Java installation. +- Python 3.11 or later. + +## Install + +Create a virtual environment and install PySpark with the `pipelines` extra. The extra installs the +Spark Connect and YAML dependencies that the `spark-pipelines` command needs. + +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install "pyspark[pipelines]" +``` + +The quotes around `pyspark[pipelines]` are required in shells such as zsh, which otherwise treat +the brackets as a glob pattern. + +## Create a pipeline project + +```bash +spark-pipelines init --name hello_pipeline +cd hello_pipeline +``` + +This creates the following project: + +``` +hello_pipeline/ +|-- spark-pipeline.yml +|-- pipeline-storage/ +`-- transformations/ + |-- example_python_materialized_view.py + `-- example_sql_materialized_view.sql +``` + +`spark-pipeline.yml` is the pipeline spec. It names the pipeline, points `libraries` at the source +files under `transformations/`, sets `storage` to the directory that holds streaming checkpoints, +and sets `spark.sql.catalogImplementation: hive` so that table metadata is kept in a local Hive +metastore and survives across runs. See [Pipeline Projects](declarative-pipelines-programming-guide.html#pipeline-projects) +for all fields. + +The two example files define one materialized view each. The Python file: + +```python +from pyspark import pipelines as dp +from pyspark.sql import DataFrame + [email protected]_view +def example_python_materialized_view() -> DataFrame: + return spark.range(10) +``` + +The SQL file reads from the Python one: + +```sql +CREATE MATERIALIZED VIEW example_sql_materialized_view AS +SELECT id FROM example_python_materialized_view +WHERE id % 2 = 0 +``` + +## Run the pipeline + +```bash +spark-pipelines run +``` + +SDP analyzes the dependencies between the datasets, runs +`example_python_materialized_view` first, and then `example_sql_materialized_view`. The output +ends with: + +``` +... Flow spark_catalog.default.example_python_materialized_view has COMPLETED. +... +... Flow spark_catalog.default.example_sql_materialized_view has COMPLETED. +... Run is COMPLETED. +``` + +The run writes table data to `spark-warehouse/` and table metadata to `metastore_db/`, both in the +current directory. + +## Query the output tables + +From the project directory, query the tables with the `spark-sql` command installed with PySpark: + +```bash +spark-sql -e "SELECT * FROM example_sql_materialized_view ORDER BY id" +``` + +``` +0 +2 +4 +6 +8 +``` + +You can also start the PySpark shell with `pyspark` from the same directory and run +`spark.table("example_sql_materialized_view").show()`. + +Run `spark-pipelines`, `spark-sql` and `pyspark` from the project directory: the local Hive +metastore lives in `metastore_db/` under the current directory. + +## Add a streaming table and a materialized view + +A streaming table processes only the data that arrived since the previous run. Create a directory +of JSON order events with a first batch of two orders: + +```bash +mkdir -p data/orders +cat > data/orders/batch-1.json <<'EOF' +{"order_id": 1, "customer": "alice", "amount": 20.0} +{"order_id": 2, "customer": "bob", "amount": 35.5} +EOF +``` + +Define a streaming table that ingests the files, in `transformations/orders.py`: + +```bash +cat > transformations/orders.py <<'EOF' +from pathlib import Path + +from pyspark import pipelines as dp +from pyspark.sql import DataFrame + +ORDERS_DIR = (Path(__file__).parent.parent / "data" / "orders").resolve().as_uri() Review Comment: **Non-blocking (P2):** `as_uri()` percent-encodes the path, so a project under `/Users/Jane Doe/projects` gets `file:///Users/Jane%20Doe/projects/hello_pipeline/data/orders`. The file source parses that string with Hadoop's `Path`, which does not decode escapes, a behavior the base branch's `containsSpecialCharsInPath` streaming test pins. By this review's reading of the code, the orders flow then fails with `PATH_NOT_FOUND` naming a path that does not exist, for any project path that contains a space, parentheses, a non-ASCII letter or another character that `as_uri()` escapes. The example's `transformations/orders.py` (line 34) has the same expression and breaks the same way when the project is copied under such a path; the README's `/tmp/hello_world` destination is unaffected. Building the URI from the unescaped path, as `spark-pipelines init` does for `storage`, avoids it: ```suggestion ORDERS_DIR = f"file://{(Path(__file__).parent.parent / 'data' / 'orders').resolve()}" ``` With this form, a project path that contains a glob character such as `[` or `*` is read as a pattern and can match no files without an error, so such paths stay unsupported. **Verification:** - **Regression:** Following the quick start from a working directory whose path contains characters that percent-encoding escapes, such as a space, parentheses and a non-ASCII letter, reaches the revenue_by_customer output the page shows after both runs, where the current snippet fails with PATH_NOT_FOUND naming the percent-encoded path. - **Behavior:** With the other example fixes applied, the example placed under a path that contains a space and a non-ASCII letter ingests both order batches into orders across its two runs. - **Inspection:** Both copies of orders.py build the reader path as file:// followed by the resolved data directory, with no call to as_uri() or any other percent-encoding. ########## docs/declarative-pipelines-quick-start.md: ########## @@ -0,0 +1,236 @@ +--- +layout: global +title: Spark Declarative Pipelines Quick Start +displayTitle: Spark Declarative Pipelines Quick Start +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You 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. +--- + +* Table of contents +{:toc} + +This page takes you from an empty machine to a running [Spark Declarative Pipelines (SDP)](declarative-pipelines-programming-guide.html) +pipeline on your laptop. You install PySpark, generate a pipeline project, run it, query its +output tables, and then add a streaming table and a materialized view that depends on it. + +## Prerequisites + +- Java 21 or 25. `java` must be on your `PATH`, or `JAVA_HOME` must point to the Java installation. +- Python 3.11 or later. + +## Install + +Create a virtual environment and install PySpark with the `pipelines` extra. The extra installs the +Spark Connect and YAML dependencies that the `spark-pipelines` command needs. + +```bash +python3 -m venv .venv +source .venv/bin/activate +pip install "pyspark[pipelines]" +``` + +The quotes around `pyspark[pipelines]` are required in shells such as zsh, which otherwise treat +the brackets as a glob pattern. + +## Create a pipeline project + +```bash +spark-pipelines init --name hello_pipeline +cd hello_pipeline +``` + +This creates the following project: + +``` +hello_pipeline/ +|-- spark-pipeline.yml +|-- pipeline-storage/ +`-- transformations/ + |-- example_python_materialized_view.py + `-- example_sql_materialized_view.sql +``` + +`spark-pipeline.yml` is the pipeline spec. It names the pipeline, points `libraries` at the source +files under `transformations/`, sets `storage` to the directory that holds streaming checkpoints, +and sets `spark.sql.catalogImplementation: hive` so that table metadata is kept in a local Hive +metastore and survives across runs. See [Pipeline Projects](declarative-pipelines-programming-guide.html#pipeline-projects) +for all fields. + +The two example files define one materialized view each. The Python file: + +```python +from pyspark import pipelines as dp +from pyspark.sql import DataFrame + [email protected]_view +def example_python_materialized_view() -> DataFrame: + return spark.range(10) +``` + +The SQL file reads from the Python one: + +```sql +CREATE MATERIALIZED VIEW example_sql_materialized_view AS +SELECT id FROM example_python_materialized_view +WHERE id % 2 = 0 +``` + +## Run the pipeline + +```bash +spark-pipelines run +``` + +SDP analyzes the dependencies between the datasets, runs +`example_python_materialized_view` first, and then `example_sql_materialized_view`. The output +ends with: + +``` +... Flow spark_catalog.default.example_python_materialized_view has COMPLETED. +... +... Flow spark_catalog.default.example_sql_materialized_view has COMPLETED. +... Run is COMPLETED. +``` + +The run writes table data to `spark-warehouse/` and table metadata to `metastore_db/`, both in the +current directory. + +## Query the output tables + +From the project directory, query the tables with the `spark-sql` command installed with PySpark: + +```bash +spark-sql -e "SELECT * FROM example_sql_materialized_view ORDER BY id" +``` + +``` +0 +2 +4 +6 +8 +``` + +You can also start the PySpark shell with `pyspark` from the same directory and run +`spark.table("example_sql_materialized_view").show()`. + +Run `spark-pipelines`, `spark-sql` and `pyspark` from the project directory: the local Hive +metastore lives in `metastore_db/` under the current directory. + +## Add a streaming table and a materialized view + +A streaming table processes only the data that arrived since the previous run. Create a directory +of JSON order events with a first batch of two orders: + +```bash +mkdir -p data/orders +cat > data/orders/batch-1.json <<'EOF' +{"order_id": 1, "customer": "alice", "amount": 20.0} +{"order_id": 2, "customer": "bob", "amount": 35.5} +EOF +``` + +Define a streaming table that ingests the files, in `transformations/orders.py`: + +```bash +cat > transformations/orders.py <<'EOF' +from pathlib import Path + +from pyspark import pipelines as dp +from pyspark.sql import DataFrame + +ORDERS_DIR = (Path(__file__).parent.parent / "data" / "orders").resolve().as_uri() + + [email protected] +def orders() -> DataFrame: + return ( + spark.readStream + .schema("order_id INT, customer STRING, amount DOUBLE") + .json(ORDERS_DIR) + ) +EOF +``` + +`@dp.table` defines a streaming table because the function returns a streaming DataFrame +(`spark.readStream`). Streaming file sources need an explicit schema. Review Comment: **Nit (P3):** The decorator sets the dataset type, not the return value: `@dp.table` always registers a streaming table, and a `@dp.table` function that returns a batch DataFrame fails analysis with `INVALID_FLOW_QUERY_TYPE.BATCH_RELATION_FOR_STREAMING_TABLE`, the mistake this PR fixes in the guide's for-loop example. As written, the sentence suggests that `@dp.table` over a batch read defines a non-streaming table. ```suggestion `@dp.table` defines a streaming table, so its function must return a streaming DataFrame (`spark.readStream`). Streaming file sources need an explicit schema. ``` **Verification:** - **Inspection:** The quick start no longer attributes the dataset type to the function's return value, and its description of @dp.table agrees with the programming guide's streaming-table section. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
