Spark Tasks
This guide is for data engineers and ML engineers who want to run a Uniflow task on Spark instead of Ray. By the end, you'll know when Spark is the right backend, how to declare and size a Spark task, how its output reaches the next task, and you'll have a complete read, transform, write example that hands its result to a Ray task.
A Spark task is an ordinary @uniflow.task whose config is a SparkTask. Michelangelo AI runs the task body on a Spark driver and executors that the Spark operator manages on your compute cluster. Your function sees a ready-to-use Spark session.
What you'll learn
- When to pick a Spark task and when to pick a Ray task
- How to declare a Spark task and which
SparkTaskfields exist - How data moves between a Spark task and other tasks with
DatasetVariable - How to build a read, transform, write task and hand its output to a downstream task
- What the sandbox needs to run Spark tasks, and the current limitations
Prerequisites
- Familiarity with
@uniflow.taskand@uniflow.workflow. See Getting Started with ML Pipelines. - For remote runs, a running sandbox. See Sandbox Setup.
ma sandbox createinstalls the Spark operator for you, unless you pass--exclude spark. See Running the example. - For local runs, JDK 17 or newer on your machine and the Python extras that include PySpark (
cd python && poetry install -E example). Spark 4 doesn't start on older JDKs. The example image uses OpenJDK 17.
Spark task or Ray task
Both backends run the same kind of @uniflow.task and can be mixed in one workflow. The choice is about the shape of the work.
SparkTask | RayTask | |
|---|---|---|
| Cluster shape | One driver plus executor_instances executors | One head plus worker_instances workers |
| Your code works with | A Spark session (SQL and DataFrame APIs, Hive support enabled) | Ray, Ray Datasets, and anything else Python |
| Typical use | Batch ETL: filters, joins, and aggregations over large tables or Parquet | Model training, inference, and Python-native or GPU-heavy processing |
| Used by | HiveSink accepts only Spark DataFrames | LightningTrainer runs on Ray. See Distributed Training |
A common split is to prepare data on Spark, then train on Ray. DatasetVariable carries the dataset across that boundary.
The OSS Ray and Spark runtimes don't accept image_spec, and the Spark task factory has no container_image or recipe parameter. Build one image that contains your task code and pass it with --image.
Declare a Spark task
Import SparkTask from michelangelo.uniflow.plugins.spark and pass an instance as config. config is a required argument of @uniflow.task, so a bare @uniflow.task() fails. Leave every SparkTask field out to take the defaults.
import michelangelo.uniflow.core as uniflow
from michelangelo.uniflow.plugins.spark import SparkTask
@uniflow.task(
config=SparkTask(
driver_cpu=1,
driver_memory="2G",
executor_cpu=2,
executor_memory="4G",
executor_instances=2,
)
)
def count_rows(data_url: str) -> int:
from pyspark.sql import SparkSession
spark = SparkSession.getActiveSession()
return spark.read.parquet(data_url).count()
Before your function runs, SparkTask starts a Spark session with Hive support enabled. After it returns, SparkTask stops the session. Get the session with SparkSession.getActiveSession() and don't call spark.stop() yourself.
To add Spark properties to that session, set the _SPARK_PROPERTIES environment variable in the task container to comma-separated key=value pairs, for example spark.sql.shuffle.partitions=64,spark.sql.session.timeZone=UTC. A property value can't contain a comma.
The decorator's other arguments work the same as for Ray tasks, including alias, cache_enabled, cache_version, and retry_attempts. See Caching and Pipeline Run Resume.
Configure resources
SparkTask has nine fields. All are optional. Any field you leave out falls back to a default set by the Starlark task factory (python/michelangelo/uniflow/plugins/spark/task.star).
| Field | Type | Default | What it sets |
|---|---|---|---|
driver_cpu | int | 4 | CPUs for the driver pod |
driver_memory | str | "16G" | Memory for the driver pod |
driver_disk | str | "512G" | Disk size recorded on the driver pod spec. See Limitations |
driver_gpu | int | 0 | GPUs for the driver pod |
executor_cpu | int | 4 | CPUs per executor pod |
executor_memory | str | "16G" | Memory per executor pod |
executor_disk | str | "512G" | Disk size recorded on each executor pod spec. See Limitations |
executor_gpu | int | 0 | GPUs per executor pod |
executor_instances | int | 1 | Number of executors |
Memory and disk are strings with a unit suffix, such as "4G". CPU, GPU, and instance counts are integers.
The defaults ask for 4 CPUs and 16G for the driver and for each executor. That is more than a laptop-sized sandbox can usually schedule. Set driver_* and executor_* explicitly for sandbox runs, as the examples here do.
You can change the defaults for one run by putting SPARK_DEFAULT_* variables in that run's environment, for example --environ SPARK_DEFAULT_EXECUTOR_MEMORY=8G on remote-run, or the environ in a pipeline's config. To change one task's resources, set SPARK_OVERRIDE_<FIELD>.<task_path> the same way. These are read from the run's environment, not from the workflow worker's, so setting them on the worker has no effect.
To run the same function with different resources, call with_overrides:
big_count_rows = count_rows.with_overrides(
alias="count_rows_large",
config=SparkTask(
driver_cpu=1,
driver_memory="2G",
executor_cpu=4,
executor_memory="16G",
executor_instances=8,
),
)
At module level, as above, the new config replaces the original: a field you leave out falls back to the defaults in the table, not to the original task's value. Inside a @workflow body the two configs are merged field by field instead. In both cases, repeat every field you want to keep and the result is the same.
Pass data between tasks
A task's inputs and outputs travel through object storage, not through the workflow process. For datasets, use DatasetVariable from michelangelo.workflow.variables. It holds a storage path and an optional in-memory value, and it reads and writes through the right I/O handler for each backend.
| Where | Call | Effect |
|---|---|---|
| Spark task, producing | DatasetVariable.create(spark_df), then .save_spark_dataframe() | Writes the DataFrame as Parquet to a new path under UF_STORAGE_URL |
| Spark task, consuming | dv.load_spark_dataframe(), then dv.value | Reads the Parquet back as a Spark DataFrame |
| Ray task, consuming | dv.load_ray_dataset(), then dv.value | Reads the same Parquet as a Ray Dataset |
| Any task, consuming | dv.load_pandas_dataframe(), then dv.value | Reads the same Parquet as a pandas DataFrame |
Call save_spark_dataframe() before you return the variable. Return the DatasetVariable itself, not .value. The next task receives the path and loads the data in its own format. Because the file format is Parquet in all three cases, a Spark task can feed a Ray task and the reverse.
Small results such as counts, metrics, and file paths can be returned directly as dicts, lists, or numbers.
For the full DatasetVariable API and the other ways to share data, see Workflow Patterns.
Worked example: clean and aggregate events
This workflow reads raw event rows from Parquet on a Spark task, drops bad rows, aggregates events per user per day, and writes the result. A Ray task then loads that result and reports its size.
Save this as python/examples/events_etl/events_etl.py, and add an empty python/examples/events_etl/__init__.py next to it so the example image picks both up.
import michelangelo.uniflow.core as uniflow
from michelangelo.uniflow.plugins.ray import RayTask
from michelangelo.uniflow.plugins.spark import SparkTask
from michelangelo.workflow.variables import DatasetVariable
@uniflow.task(
config=SparkTask(
driver_cpu=1,
driver_memory="2G",
executor_cpu=2,
executor_memory="4G",
executor_instances=2,
)
)
def clean_events(raw_path: str) -> DatasetVariable:
"""Read raw events, clean and aggregate them, and hand off the result."""
from michelangelo.uniflow.plugins.spark.io import SparkIO
from pyspark.sql import functions as F
# Read: SparkIO.read_data applies the S3A settings from the pod environment.
raw = SparkIO.read_data(raw_path)
# Transform: drop bad rows, normalize types, aggregate per user per day.
daily = (
raw.dropna(subset=["user_id", "event_ts"])
.withColumn("event_date", F.to_date("event_ts"))
.withColumn("amount", F.col("amount").cast("double"))
.filter(F.col("amount") >= 0)
.groupBy("user_id", "event_date")
.agg(
F.count("*").alias("event_count"),
F.sum("amount").alias("total_amount"),
)
)
# Write: persist under UF_STORAGE_URL and return a reference.
out = DatasetVariable.create(daily)
out.save_spark_dataframe()
return out
@uniflow.task(config=RayTask(head_cpu=1, head_memory="2Gi"))
def summarize(cleaned: DatasetVariable) -> dict:
"""Load the Spark output as a Ray Dataset and report basic facts."""
cleaned.load_ray_dataset()
ds = cleaned.value
return {"rows": ds.count(), "columns": ds.columns()}
@uniflow.workflow()
def events_etl(raw_path: str):
cleaned = clean_events(raw_path)
return summarize(cleaned)
if __name__ == "__main__":
ctx = uniflow.create_context()
ctx.run(events_etl, raw_path="/tmp/raw_events.parquet")
How the pieces work:
- Read.
SparkIO.read_data(url)reads Parquet with the active Spark session. It first applies S3A settings from theAWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY, andAWS_ENDPOINT_URLenvironment variables, sos3://paths work with the sandbox object store. For a local path,spark.read.parquet(path)does the same job. - Transform. Ordinary PySpark. The
pysparkandSparkIOimports sit inside the task body, following the convention in the other examples of keeping imports out of the workflow module's top level. - Write.
DatasetVariable.create(daily)picks a unique path underUF_STORAGE_URL, andsave_spark_dataframe()writes Parquet there. The task returns the variable, and Uniflow passes it tosummarizeas a reference. - Hand-off.
summarizeruns on a Ray cluster.load_ray_dataset()reads the Parquet that Spark wrote. - Workflow. The
events_etlbody only sequences task calls. Keep Starlark's restrictions in mind there, such as no f-strings and notry. See Workflow constraints.
The input needs user_id, event_ts, and amount columns. To make a small test file, run this once:
import pandas as pd
pd.DataFrame(
{
"user_id": ["u1", "u1", "u2", None],
"event_ts": ["2026-11-01 09:00:00", "2026-11-01 17:30:00", "2026-11-02 08:15:00", "2026-11-02 09:00:00"],
"amount": ["10.5", "4.5", "-3", "7"],
}
).to_parquet("/tmp/raw_events.parquet")
With this input, the row with a null user_id and the row with a negative amount are dropped. The result has one row: u1 on 2026-11-01, with event_count 2 and total_amount 15.0. The Ray task prints:
{'rows': 1, 'columns': ['user_id', 'event_date', 'event_count', 'total_amount']}
Running the example
Locally
From the python/ directory:
PYTHONPATH=. poetry run python -m examples.events_etl.events_etl
A local run executes the tasks on your machine. The Spark task starts a local Spark session, so it needs a JDK. Local runs store task outputs under ~/uf_storage. After the Spark session stops, you may see a py4j connection traceback in the log. The run still succeeds. The result line is what to check.
On the sandbox
Remote runs need three things in place.
-
The Spark operator.
ma sandbox createinstalls it with Helm into thespark-operatornamespace unless you excluded it.ma sandbox syncleaves infrastructure alone, so it won't add the operator back. If you used--exclude spark, recreate the sandbox without that flag, or install the operator the same wayma sandbox createdoes:helm repo add spark-operator https://kubeflow.github.io/spark-operator
helm upgrade --install spark-operator spark-operator/spark-operator \
--namespace spark-operator --create-namespace --wait --timeout 20m -
A task image that contains Java and Spark. The image Dockerfile at
python/examples/Dockerfileinstalls OpenJDK 17, Apache Spark, and the S3A jars, and copies your code into/app. Build it frompython/, then import it into the cluster:docker build -t examples:latest -f ./examples/Dockerfile .
k3d image import examples:latest -c michelangelo-sandboxThe import is required. The Spark task creates its pods with
imagePullingPolicy: Never, so the cluster never pulls the image itself. -
Input the Spark pods can read. Put the Parquet file in the sandbox object store, for example the
defaultbucket, and pass itss3://URL. You can upload it with the AWS CLI against the sandbox's S3 endpoint, as in Sandbox Ports and Endpoints:AWS_ACCESS_KEY_ID=michelangeloadmin AWS_SECRET_ACCESS_KEY=michelangeloadmin \
aws --endpoint-url http://localhost:9091 --region us-east-1 \
s3 cp /tmp/raw_events.parquet s3://default/raw_events.parquet
Set raw_path in the ctx.run call to that URL, then start the run:
PYTHONPATH=. poetry run python -m examples.events_etl.events_etl remote-run \
--image docker.io/library/examples:latest \
--storage-url s3://default
For the full remote-run flow, including Cadence and Temporal options, see Running Uniflow Pipelines and Pipeline Running Modes.
Limitations
These come from the current source and may change.
- Disk fields are recorded but not applied.
driver_diskandexecutor_diskare written to theSparkJobpod spec, but the SparkJob controller doesn't copy a disk size into the Spark operator'sSparkApplication. Setting them doesn't change the disk your pods get. - The image is never pulled. Spark tasks always set
imagePullingPolicy: Never, so the image must already exist on every node that can run the driver or executors. - Tasks use the
defaultnamespace for theSparkJobresource. The generated resource doesn't take a namespace from your code. DatasetVariablesaves once.DatasetVariable.create()picks a unique path underUF_STORAGE_URL, so a rerun writes to a new path and doesn't collide. A secondsave_spark_dataframe()on the same variable does nothing and raises no error. If you pass your ownpath=and it already exists, the write fails.- Sandbox sizing. Defaults are 4 CPUs and 16G per pod. Size tasks explicitly on a laptop.
Next steps
- Workflow Patterns: sequencing, parallel tasks, and more on
DatasetVariable. - Distributed Training: the Ray side, for training on the data you just prepared.
- Prepare Your Data: loading, cleaning, and splitting datasets.
- Examples Gallery: end-to-end pipelines that mix Spark preprocessing with Ray training.