All posts

What's new in Apache Spark 4.0

Spark 4.0 new features: ANSI mode by default, VARIANT, pipe syntax, SQL UDFs, session variables, collation, XML, the Python Data Source API and transformWithState. Each feature has its area, a source ticket, the code before and with 4.0, and what to check before you upgrade from 3.x.

33 min read Spark

Spark 4.0 is a break with the past and a step forward in the same release. Scala 2.12 and JDK 8 and 11 are gone, ANSI mode is the default so bad data stops a job instead of turning into NULL, and SQL picks up the pieces it was missing: a type for JSON, functions, variables, collations and a query syntax you can read top to bottom.

The release notes put 4.0.0, out on 23 May 2025, at over 5,100 resolved tickets from more than 390 people. It’s the first release of the 4.x line and the one every later 4.x release builds on, so it’s where to start if you’re meeting Spark 4 for the first time or planning a move from 3.x.

Below are ten features. Each one shows the code you’d have written before 4.0, the code you write now, and what it needs before it works. If a term is new, the glossary covers it. The upgrade section, near the end, is the one to read if you’re coming from 3.x. The features-by-release post lines up all the Spark 4 releases, and Spark 4.1 is the release that follows this one.

Spark 4.0.0 in numbers: over 5,100 Jira tickets resolved, more than 390 contributors, and Scala 2.13 with Java 17 as the baseline

Image 1: Spark 4.0.0 in numbers, and what the release is about.

Spark 4.0 features by area, each with what it replaces and what you write now, and the two ways to install it

Image 2: Spark 4.0 by area, with what each feature replaces and what you write now.

Key takeaways

  • ANSI mode is on by default. A bad cast or a divide by zero now raises an error, and try_cast and try_divide give you NULL when that’s what you want. This is the change most likely to turn a green pipeline red.
  • Scala 2.13 and Java 17 are the baseline, so every jar your jobs depend on needs a Scala 2.13 build.
  • SQL gets VARIANT, user-defined functions, session variables, collation and pipe syntax, all without a flag.
  • The built-in XML source and the Python Data Source API replace a dependency and a Scala connector.
  • transformWithState lets you keep custom per-key state in a stream, and a state data source lets you read it back.

Features at a glance

Feature Area On by default? How to turn it on
ANSI mode SQL Yes spark.sql.ansi.enabled=false turns it off
VARIANT Types Yes Nothing
SQL pipe syntax SQL Yes Nothing
SQL user-defined functions SQL Yes Nothing
Session variables SQL Yes Nothing
String collation Types Yes Nothing
XML data source and functions Formats Yes Nothing
Python Data Source API Python Yes PyArrow installed
GROUP BY on maps, DESCRIBE ... AS JSON SQL Yes Nothing
transformWithState Streaming Yes RocksDB state store, PyArrow, pandas, protobuf and gRPC

Before you start

What you need

Need Detail
Java 17 or 21, per the Spark 4.0.5 overview; 17 is the baseline for 4.0. The apache/spark:4.0.5-python3 image ships Java 17
Scala 2.13. Every jar your jobs depend on needs a Scala 2.13 build
Python, for PySpark 3.9 or newer, the lowest floor of the Spark 4 releases
Spark pip install pyspark==4.0.5, the apache/spark:4.0.5-python3 image, or the 4.0.5 release tarball
PyArrow and pandas For features 8 and 10: pip install "pyspark[sql]" brings them
protobuf and gRPC packages For feature 10: pip install protobuf grpcio grpcio-status googleapis-common-protos
The RocksDB state store For feature 10: set spark.sql.streaming.stateStore.providerClass to RocksDBStateStoreProvider
plotly Only to try the plotting API in the smaller additions

Install Spark 4.0

You’ve got two ways in. 4.0.5 is the latest 4.0 release (4.0.0 shipped on 23 May 2025 and 4.0.5 on 27 October 2026).

Option 1: pip. The wheel bundles Spark, so you need Java (17 or 21) and Python 3.9 or newer. The sql extra adds PyArrow, pandas and NumPy.

python3 -m venv .venv && source .venv/bin/activate
pip install "pyspark[sql]==4.0.5"
python -c "import pyspark; print(pyspark.__version__)"

The last command prints 4.0.5. Point PYSPARK_PYTHON at the same interpreter if your shell’s python3 is a different one, because the workers use it.

Option 2: the release tarball in a common path. Download it, check the checksum, unpack it under /opt and point SPARK_HOME at a stable link.

curl -LO https://archive.apache.org/dist/spark/spark-4.0.5/spark-4.0.5-bin-hadoop3.tgz
curl -s https://archive.apache.org/dist/spark/spark-4.0.5/spark-4.0.5-bin-hadoop3.tgz.sha512
shasum -a 512 spark-4.0.5-bin-hadoop3.tgz   # compare with the line above
sudo tar -xzf spark-4.0.5-bin-hadoop3.tgz -C /opt
sudo ln -sfn /opt/spark-4.0.5-bin-hadoop3 /opt/spark
export SPARK_HOME=/opt/spark PATH=/opt/spark/bin:$PATH
spark-submit --version

The file is 549,108,494 bytes (about 524 MiB). Add the two export lines to ~/.zshrc or ~/.bashrc to keep them. If the version printed isn’t 4.0.5, an older SPARK_HOME in your shell is winning; start with env -u SPARK_HOME.

Sample data

Several examples read two small views, orders and names. Create them first, in the session that runs the examples. From PySpark, pass each statement to spark.sql.

CREATE OR REPLACE TEMP VIEW orders AS SELECT * FROM VALUES
  (1,'eu',10.0D), (2,'us',20.0D), (3,'eu',30.0D), (4,'us',5.0D) AS t(id, region, amount);
CREATE OR REPLACE TEMP VIEW names AS SELECT * FROM VALUES ('Ana'),('ana'),('ANA'),('Bob') AS t(n);

Glossary

Term Meaning
ANSI mode Spark follows the SQL standard for errors: a bad cast or a divide by zero raises instead of returning NULL
try_ function A variant such as try_cast that returns NULL on bad input instead of raising
UDF User-defined function: a function you write yourself
UDTF User-defined table function: returns several rows per call
Collation A rule for how strings compare and sort, such as case-insensitive
Session variable A typed value that lives for the session, set with DECLARE and SET VAR
VARIANT The Spark type for semi-structured data such as JSON, encoded once in binary
rowTag The XML element that the XML reader treats as one row
State What a streaming query remembers per key between micro-batches

1. ANSI mode on by default

Since: 4.0.0 · Area: SQL · Source: SPARK-44444

Lineage: ANSI mode existed as a setting, off by default; 4.0 flips the default.

Until 4.0, a bad cast or a division by zero quietly gave you NULL and the job carried on. That’s friendly right up to the day you notice a column that’s been NULL for a month. In 4.0 spark.sql.ansi.enabled is true by default (SPARK-44444), so the same statements raise an error and the query stops. The message names the fix: use try_cast or try_divide where NULL was what you wanted all along.

It also breaks things. A pipeline that used to finish with some nulls in it may now fail on its first bad row, so run your real data through a 4.0 cluster before you upgrade.

Before Spark 4.0

With ANSI off, which was the 3.x default, both bad inputs came back as NULL.

Runnable file: 14_ansi_mode_before.sql.

SET spark.sql.ansi.enabled=false;
SELECT CAST('abc' AS INT) AS bad_cast, 1/0 AS div_zero;    -- NULL, NULL

The 3.x default on the left returns NULL for a bad cast and a divide by zero, and the 4.0 default on the right raises CAST_INVALID_INPUT and DIVIDE_BY_ZERO, with try_cast and try_divide returning NULL

Image 3: The same two statements, with ANSI off and with the 4.0 default.

With Spark 4.0: sample code

Runnable file: 01_ansi_mode.sql.

RESET spark.sql.ansi.enabled;           -- back to the default if you turned it off
SET spark.sql.ansi.enabled;             -- true
SELECT try_cast('abc' AS INT);          -- NULL
SELECT try_divide(1, 0);                -- NULL
-- these two fail on purpose:
SELECT CAST('abc' AS INT);              -- [CAST_INVALID_INPUT]
SELECT 1/0;                             -- [DIVIDE_BY_ZERO]

When it fits, and when it doesn’t

Leave it on. It’s what makes bad data visible, and the try_* functions are there for the places where NULL is the right answer. Turn it off only as a stopgap while you fix the data, with spark.sql.ansi.enabled=false. Other ANSI behaviour, overflow for example, changes too, so test with your own data and not a toy table.

The ANSI off case returns NULL for a bad cast and a divide by zero, the ANSI on case raises CAST_INVALID_INPUT and DIVIDE_BY_ZERO, and try_cast and try_divide give NULL when you want it

Image 4: Bad rows used to slip through as NULL. Now they stop the query.

2. VARIANT

Since: 4.0.0 · Area: Types · Source: SPARK-45827

Lineage: new in 4.0.

VARIANT is a Spark type for semi-structured data such as JSON (SPARK-45827). parse_json turns a string into one, stored in a binary encoding so it’s parsed once and not on every read. variant_get pulls a value out by path and gives it back as the type you ask for, and schema_of_variant tells you the shape Spark found.

The difference from the old approach is the type. get_json_object always returns a string, so you cast it yourself. variant_get(v, '$.b[1]', 'int') returns an int.

Before Spark 4.0

You stored JSON as a string column and read fields with get_json_object, which returns text.

Runnable file: 15_variant_before.sql.

SELECT typeof(get_json_object('{"a":1,"b":[1,2,3]}', '$.b[1]')) AS before_type;   -- string

get_json_object returning a string on the left and variant_get returning an int on the right for the same document

Image 5: A string you cast yourself becomes a typed value.

With Spark 4.0: sample code

Runnable file: 02_variant.sql.

SELECT parse_json('{"a":1,"b":[1,2,3],"c":{"d":"x"}}') AS v;
SELECT variant_get(parse_json('{"a":1,"b":[1,2,3]}'), '$.b[1]', 'int');   -- 2
SELECT schema_of_variant(parse_json('{"a":1,"b":[1,2,3]}'));              -- OBJECT<a: BIGINT, b: ARRAY<BIGINT>>

When it fits, and when it doesn’t

Use it for payloads whose shape changes from row to row, such as events with different fields, where a fixed schema would either drop data or fill up with nulls. If the shape is fixed, a typed struct is easier to filter and document. The path syntax in 4.0 is variant_get with a path string and a type string.

A JSON document goes through parse_json into a VARIANT value, which variant_get, schema_of_variant and typeof then read

Image 6: Parse once, then read typed values out of the binary encoding.

3. SQL pipe syntax

Since: 4.0.0 · Area: SQL · Source: SPARK-49555

Lineage: new in 4.0.

Ordinary SQL starts with SELECT, but you think about a query starting from the table. Pipe syntax (SPARK-49555) lets you write it that way: start with FROM, then chain steps with |>, each one taking the result so far and doing one thing to it. You can still mix it with ordinary SQL, and it compiles to the same plans.

It reads like a DataFrame chain. There’s less nesting, and you can comment out a step to see what the query did before it.

Before Spark 4.0

The same query written the usual way, with SELECT first and the filter and grouping after it.

Runnable file: 16_pipe_syntax_before.sql.

SELECT region, sum(amount) AS total
FROM orders WHERE amount > 5
GROUP BY region ORDER BY total DESC;     -- eu 40.0, us 20.0

A conventional SELECT on the left and the same query in pipe syntax on the right, both returning eu 40.0 and us 20.0

Image 7: The same query, written in the order you think about it.

With Spark 4.0: sample code

Runnable file: 03_pipe_syntax.sql.

FROM orders
|> WHERE amount > 5
|> AGGREGATE sum(amount) AS total GROUP BY region
|> ORDER BY total DESC;                  -- eu 40.0, us 20.0

FROM orders |> EXTEND amount * 2 AS doubled |> SELECT id, doubled |> LIMIT 2;

When it fits, and when it doesn’t

It’s a good fit for exploratory queries and for long chains of filters and aggregates, where each step is easy to read on its own line. It isn’t a different engine, so a query that’s slow in ordinary SQL is slow here too. Teams that share query templates may want to pick one style, since mixing both in a codebase is allowed but not always pleasant.

A pipeline of four steps, FROM orders, WHERE amount > 5, AGGREGATE by region and ORDER BY total, each showing its result

Image 8: Each pipe takes the result so far and does one thing to it.

4. SQL user-defined functions

Since: 4.0.0 · Area: SQL · Source: SPARK-46057

Lineage: new in 4.0.

You can now write a function in SQL, scalar or table-valued, with CREATE FUNCTION (SPARK-46057). The body is a SQL expression or query, and Spark inlines it into the plan of the query that calls it, so there’s no trip to a Python worker. In the plan, the Python version shows a pythonUDF0 node, and the SQL version shows only the scan, because the expression got folded in.

A table function returns rows, so it can sit in a FROM clause. It’s close to a parameterised view.

Before Spark 4.0

For logic you wanted to reuse, a Python UDF was the usual answer, with all the overhead of a Python worker.

Runnable file: 17_sql_udf_before.py.

spark.udf.register("add_tax_py", lambda x: x * 1.18, "double")
spark.sql("SELECT id, add_tax_py(amount) AS gross FROM orders").explain()
# Project [id, pythonUDF0 AS gross]

A Python UDF that runs in a worker on the left and a SQL function inlined into the plan on the right, both producing the same four gross values

Image 9: The same calculation, in a Python worker and inlined as SQL.

With Spark 4.0: sample code

Runnable file: 04_sql_udf.sql.

CREATE OR REPLACE TEMPORARY FUNCTION add_tax(x DOUBLE) RETURNS DOUBLE RETURN x * 1.18;
SELECT id, add_tax(amount) AS gross FROM orders ORDER BY id;     -- 11.8, 23.6, 35.4, 5.9

CREATE OR REPLACE TEMPORARY FUNCTION big_orders(min_amt DOUBLE)
  RETURNS TABLE (id INT, amount DOUBLE)
  RETURN SELECT id, amount FROM orders WHERE amount >= min_amt;
SELECT * FROM big_orders(20.0);                                   -- ids 2 and 3

When it fits, and when it doesn’t

Use them for small, reusable calculations that can be written as an expression, and for parameterised queries. They’re not the place for anything that needs a loop, a library or an external call; that’s still a Python UDF’s job. The floating-point output (11.799999999999999 for the first row) is ordinary DOUBLE arithmetic, and you’d round it for display.

A Python UDF takes a trip through a Python worker while a SQL UDF is inlined into a LocalTableScan, both ending with the same four values

Image 10: A Python UDF leaves the JVM. A SQL UDF stays in the plan.

5. Session variables

Since: 4.0.0 · Area: SQL · Source: SPARK-42849

Lineage: new in 4.0.

A session variable is a typed value that lives as long as your session (SPARK-42849). You declare it with DECLARE VARIABLE, change it with SET VAR, and use it in any query by name. Because it has a type, 15.0 is a DOUBLE and not text that gets pasted into the statement.

Before this, the usual trick was SET name=value and then ${name} in the query, which is text substitution. It works, but nothing checks the type and it’s easy to get a quote wrong.

Before Spark 4.0

A configuration value and ${...} substitution did the job, as untyped text.

Runnable file: 18_session_variables_before.sql.

SET threshold=15.0;
SELECT id FROM orders WHERE amount > ${threshold} ORDER BY id;     -- ids 2, 3

SET with a text substitution on the left and a declared DOUBLE variable on the right, returning ids 2 and 3, and then 3 after the variable changes

Image 11: A pasted value becomes a typed variable.

With Spark 4.0: sample code

Runnable file: 05_session_variables.sql.

DECLARE OR REPLACE VARIABLE threshold DOUBLE DEFAULT 15.0;
SELECT id FROM orders WHERE amount > threshold ORDER BY id;     -- 2, 3

SET VAR threshold = 25.0;
SELECT id FROM orders WHERE amount > threshold ORDER BY id;     -- 3

When it fits, and when it doesn’t

Use them for parameters you want to change between queries in one session, such as a date range or a threshold. They live in the session only, so they’re no use for sharing a value between applications. A variable is session-scoped, so a new session starts without it, and a DECLARE has to run again.

A DECLARE statement creates a threshold variable holding 15.0, a WHERE clause reads it to return ids 2 and 3, and SET VAR changes it to 25.0 so only id 3 returns

Image 12: Declare once, read it in any query, change it with SET VAR.

6. String collation

Since: 4.0.0 · Area: Types · Source: SPARK-46830

Lineage: new in 4.0.

A collation is a rule for how strings compare and sort. Spark 4.0 lets you attach one to a string, so case-insensitive comparison is something you declare, not something you fake with lower() on both sides (SPARK-46830). UTF8_LCASE compares ignoring case, and UNICODE_CI is case-insensitive under Unicode rules. collation('x' COLLATE UNICODE_CI) reports the collation name, which shows as SYSTEM.BUILTIN.UNICODE_CI.

The practical gain is that the comparison, a DISTINCT or a GROUP BY follows the rule, and the engine knows about it, so it doesn’t have to wrap every column in a function.

Before Spark 4.0

You lowercased both sides, and every query had to remember to do it.

Runnable file: 19_collation_before.sql.

SELECT lower('Apple') = lower('apple') AS eq;                   -- true
SELECT count(DISTINCT lower(n)) FROM names;                      -- 2

lower() on both sides on the left and a collation on the comparison on the right, both returning true and 2 distinct names

Image 13: The same answers, with the rule declared on the comparison instead of a function on every column.

With Spark 4.0: sample code

Runnable file: 06_string_collation.sql.

SELECT 'Apple' = 'apple';                                  -- false
SELECT 'Apple' COLLATE UTF8_LCASE = 'apple';               -- true
SELECT collation('x' COLLATE UNICODE_CI);                  -- SYSTEM.BUILTIN.UNICODE_CI

CREATE OR REPLACE TEMP VIEW names AS SELECT * FROM VALUES ('Ana'),('ana'),('ANA'),('Bob') AS t(n);
SELECT count(DISTINCT n COLLATE UTF8_LCASE) FROM names;    -- 2

When it fits, and when it doesn’t

Use it when case, or accents, shouldn’t matter for a comparison or a group. It’s less useful for data you only display. The usual surprise is that two strings with different collations can’t be compared directly, so choose one for the column and stay with it.

The names Ana, ana, ANA and Bob counted with a UTF8_LCASE collation give two distinct names, and the apple comparison is false without a collation and true with one

Image 14: The rule goes on the comparison, and the engine follows it.

7. The built-in XML data source

Since: 4.0.0 · Area: Formats · Source: SPARK-44265, SPARK-44753

Lineage: new in 4.0 as a built-in; earlier versions needed an external package.

Spark 4.0 reads and writes XML itself (SPARK-44265), with no extra package to install on every cluster. Two things come with it: a data source, spark.read.format("xml"), with a rowTag option that names the element to treat as one row, and functions for XML held in a string column. from_xml parses it into a struct, to_xml writes one back, and schema_of_xml infers the schema.

The source infers a schema from the elements it finds. With the sample document, the inferred schema is STRUCT<age: BIGINT, name: STRING>, with the fields in alphabetical order. The release notes list the XML reader and writer for PySpark and Spark Connect as well.

Before Spark 4.0

Without a parser you pulled values out with XPath functions, one at a time.

Runnable file: 20_xml_before.sql.

SELECT xpath_string('<p><name>Ana</name><age>30</age></p>', 'p/name') AS name,   -- Ana
       xpath_int('<p><name>Ana</name><age>30</age></p>', 'p/age') AS age;        -- 30

Two xpath calls returning Ana and 30 on the left and one from_xml call returning a struct on the right

Image 15: Two separate calls become one parse into a struct.

With Spark 4.0: sample code

Runnable file: 07_xml_functions.sql.

SELECT from_xml('<p><name>Ana</name><age>30</age></p>', 'name STRING, age INT');   -- {Ana, 30}
SELECT schema_of_xml('<p><name>Ana</name><age>30</age></p>');                       -- STRUCT<age: BIGINT, name: STRING>
# write a two-record file (local mode), then read one <person> element per row
with open("/tmp/people.xml", "w") as f:
    f.write("<people><person><name>Ana</name><age>30</age></person>"
            "<person><name>Bob</name><age>41</age></person></people>")

df = spark.read.format("xml").option("rowTag", "person").load("file:///tmp/people.xml")
df.show()
# age: long, name: string  ->  (30, 'Ana'), (41, 'Bob')

When it fits, and when it doesn’t

It fits feeds from vendors or older systems that still speak XML. If the data is already JSON or Parquet, you don’t need it. The classic stumble is leaving out rowTag: the reader needs to know which element is one row.

An XML document goes through from_xml into a struct with name Ana and age 30, and a file read with rowTag gives one row per element

Image 16: A string column becomes a struct, and XML files become a DataFrame.

8. The Python Data Source API and Python UDTFs

Since: 4.0.0 · Area: Python · Source: SPARK-44076, SPARK-43797

Lineage: Python UDTFs arrived earlier (SPARK-43797); the Data Source API and polymorphic UDTFs are new in 4.0.

You can write a data source in plain Python, register it, and read it by name, from SQL too (SPARK-44076). A data source is two small classes: a DataSource that names it and gives its schema, and a DataSourceReader whose read method yields rows. No Scala connector to build and ship.

A Python user-defined table function, a UDTF, returns several rows for each input row. It’s a class with an eval method that yields tuples. Python workers run the reader and the data moves through Arrow, so PyArrow has to be installed. On the official image the data source worker fails with ModuleNotFoundError: No module named 'pyarrow' until it is.

Before Spark 4.0

You built the rows in the driver and handed them to createDataFrame, which only works for data that fits there.

Runnable file: 21_python_data_source_before.py.

spark.createDataFrame([(i, i * i) for i in range(1, 5)], "n int, square int").show()

createDataFrame from a driver list on the left and a registered Python data source read by name on the right, both returning four rows of n and square

Image 17: A one-off list on the driver becomes a reusable source with options.

With Spark 4.0: sample code

Runnable file: 09_python_data_source.py.

from pyspark.sql.datasource import DataSource, DataSourceReader

class CounterDataSource(DataSource):
    @classmethod
    def name(cls): return "counter"
    def schema(self): return "n INT, square INT"
    def reader(self, schema): return CounterReader(self.options)

class CounterReader(DataSourceReader):
    def __init__(self, options): self.limit = int(options.get("limit", 3))
    def read(self, partition):
        for i in range(1, self.limit + 1):
            yield (i, i * i)

spark.dataSource.register(CounterDataSource)
spark.read.format("counter").option("limit", 4).load().show()    # n 1..4, square 1, 4, 9, 16
from pyspark.sql.functions import udtf

@udtf(returnType="word: string, length: int")
class SplitWords:
    def eval(self, text: str):
        for w in text.split():
            yield (w, len(w))

spark.udtf.register("split_words", SplitWords)
spark.sql("SELECT * FROM split_words('spark four point zero')").show()   # spark 5, four 4, point 5, zero 4

When it fits, and when it doesn’t

It fits when the source is an API or a custom file format and a few lines of Python will do. If a JVM connector already exists, or the source has to be as fast as possible, use that instead. The usual stumble is running without PyArrow.

A DataSource class and a DataSourceReader class registered with spark.dataSource.register and read with spark.read.format, producing n and square rows

Image 18: Two classes and one registration call make the source readable by name.

9. GROUP BY on maps and DESCRIBE … AS JSON

Since: 4.0.0 · Area: SQL · Source: SPARK-47430, SPARK-50541

Lineage: new in 4.0.

Two small gaps closed together. GROUP BY now accepts a MAP column (SPARK-47430), and DESCRIBE ... AS JSON returns a table’s description as a JSON document a program can read (SPARK-50541).

Grouping by a map was an error before. Comparing two maps with = still isn’t allowed in 4.0: a MAP can be a grouping key, and a join on one fails with [DATATYPE_MISMATCH.INVALID_ORDERING_TYPE].

Before Spark 4.0

To group by a map you had to turn it into something sortable, usually a JSON string.

Runnable file: 22_group_by_map_before.sql.

SELECT to_json(m) AS m, count(*) AS n
FROM VALUES (map('k', 1)), (map('k', 1)), (map('k', 2)) AS t(m)
GROUP BY to_json(m) ORDER BY n;       -- {"k":2} 1, {"k":1} 2

to_json used as the grouping key on the left and GROUP BY on the map itself on the right, each returning two groups

Image 19: The grouping key stays a map instead of turning into a string.

With Spark 4.0: sample code

Runnable file: 10_group_by_map_describe_json.sql.

SELECT m, count(*) AS n
FROM VALUES (map('k', 1)), (map('k', 1)), (map('k', 2)) AS t(m)
GROUP BY m ORDER BY n;                -- {k -> 2} 1, {k -> 1} 2

CREATE TABLE people (id INT, name STRING) USING parquet;
DESCRIBE EXTENDED people AS JSON;     -- one JSON document

When it fits, and when it doesn’t

Group by a map when the map is the identity of the row, a set of labels for example. For a join, extract the keys you need and compare those. DESCRIBE ... AS JSON is for tooling that inspects table metadata; for reading by eye, plain DESCRIBE is easier.

Three map rows group into two groups, and DESCRIBE AS JSON returns the table name and columns as a JSON document

Image 20: Maps group as maps, and a table describes itself as JSON.

10. transformWithState and the state data source

Since: 4.0.0 · Area: Streaming · Source: SPARK-46815, SPARK-45511

Lineage: applyInPandasWithState and flatMapGroupsWithState came before; transformWithState is the new API.

Structured Streaming remembers things per key between micro-batches, a running count for example. That memory is called state. transformWithState (SPARK-46815) lets you write the logic yourself as a stateful processor: a class with an init method that declares typed state variables, a handleInputRows method that receives the rows for one key, and a close method. It exists in Scala, Java and Python, where the Python form is transformWithStateInPandas.

The state data source (SPARK-45511) reads that state back as a table with spark.read.format("statestore"), so you can query what a stream remembers instead of guessing.

Two things have to be set up first, and each one fails with its own error if it isn’t. A processor’s state variables are separate column families, which only the RocksDB state store supports, so the default provider fails with UNSUPPORTED_FEATURE.STATE_STORE_MULTIPLE_COLUMN_FAMILIES. And the Python runner needs protobuf and the gRPC packages; without them the query fails with STREAMING_PYTHON_RUNNER_INITIALIZATION_FAILURE.

With Spark 4.0: sample code

Runnable file: 12_transform_with_state.py.

# needs RocksDBStateStoreProvider as the state store, and the protobuf and gRPC packages
import pandas as pd
from pyspark.sql.streaming import StatefulProcessor
from pyspark.sql.types import IntegerType, StructField, StructType

class CountProcessor(StatefulProcessor):
    def init(self, handle):
        schema = StructType([StructField("value", IntegerType())])
        self.count = handle.getValueState("count", schema)
    def handleInputRows(self, key, rows, timerValues):
        total = self.count.get()[0] if self.count.exists() else 0
        for pdf in rows:
            total += len(pdf)
        self.count.update((total,))
        yield pd.DataFrame({"id": [key[0]], "count": [total]})
    def close(self): pass
# `stream` is a streaming DataFrame with a string column `id`, and `checkpoint` is the
# query's checkpoint path; the runnable file builds both and starts the query
counts = stream.groupBy("id").transformWithStateInPandas(statefulProcessor=CountProcessor(),
    outputStructType="id STRING, count INT", outputMode="Update", timeMode="None")
state = spark.read.format("statestore").option("stateVarName", "count").load(checkpoint)
# [('0', 78), ('1', 78), ('2', 78)] from both the output and the state data source

The rate source produced the keys 0, 1 and 2, and after 40 seconds each key held 78, in the output and in the state data source alike. The number depends on how long the query runs. Reading state before any batch has committed fails with STDS_COMMITTED_BATCH_UNAVAILABLE.

When it fits, and when it doesn’t

Use it when a stream needs custom per-key logic, such as running counts, sessions or timers, and you want to be able to look at the state. A plain groupBy(...).count() does the job when all you need is a count, and then you can skip all of this setup. There’s no before-and-after pair for this one, because the older state APIs work differently enough that the code doesn’t translate line by line.

A rate source feeds a CountProcessor that keeps a value state per key, and the state data source reads the same counts back from the checkpoint

Image 21: The same per-key counts come out of the query and out of the state data source.

Smaller additions worth knowing

Feature What it does Needs
Named and unnamed parameter markers (SPARK-41666) spark.sql("SELECT :a + :b", args={...}) and ? with a list; values stay out of the SQL text Nothing
Polymorphic Python UDTFs analyze() decides the output schema from the arguments Nothing
EXECUTE IMMEDIATE (SPARK-46246) Runs a SQL string with bound parameters Nothing
Lightweight Python client and spark.api.mode The pyspark-client package, about 1.5 MB, and a setting to turn Spark Connect on Nothing
ML on Spark Connect pyspark.ml over a Connect server A Connect server
Structured JSON logging (SPARK-47240) Machine-readable driver and executor logs, enabled with spark.log.structuredLogging.enabled The setting
Spark Kubernetes operator (SPARK-45923) Run Spark applications as Kubernetes custom resources A Kubernetes cluster
PySpark plotting API (SPARK-49530) df.plot.bar(x="k", y="v") returns a Plotly figure plotly installed
Unified PySpark UDF profiling One profiler for Python UDFs Nothing

Smaller additions in code

Parameter markers and a polymorphic UDTF.

Runnable file: 13_pyspark_extras.py.

spark.sql("SELECT :a + :b AS s", args={"a": 1, "b": 2})        # 3, named, bound from a dictionary
spark.sql("SELECT ? + ? AS s", args=[1, 2])                    # 3, unnamed, bound from a list
spark.sql("SELECT :s AS s", args={"s": "x'; DROP TABLE t; --"})   # comes back as a plain string
from pyspark.sql.functions import udtf
from pyspark.sql.types import StructType
from pyspark.sql.udtf import AnalyzeArgument, AnalyzeResult

@udtf
class Echo:
    @staticmethod
    def analyze(a: AnalyzeArgument) -> AnalyzeResult:
        return AnalyzeResult(StructType().add("c1", a.dataType))
    def eval(self, a):
        yield (a,)

spark.udtf.register("echo", Echo)
spark.sql("SELECT * FROM echo(5)")      # c1 int
spark.sql("SELECT * FROM echo('x')")    # c1 string

EXECUTE IMMEDIATE.

Runnable file: 08_execute_immediate.sql.

EXECUTE IMMEDIATE 'SELECT count(*) FROM orders WHERE amount > ?' USING 8;     -- 3

In 4.0 a parameter marker stands where a literal value would, so it can’t replace a table name.

Version lineage

Most of these are new in 4.0. The 3.5 column is what you had before.

Feature 3.5 4.0
ANSI mode A setting, off by default On by default (SPARK-44444)
Semi-structured data JSON strings and get_json_object VARIANT (SPARK-45827)
SQL syntax SELECT ... FROM only Pipe syntax (SPARK-49555)
Reusable logic Python and Scala UDFs SQL UDFs and session variables (SPARK-46057, SPARK-42849)
Strings Binary comparison Collation (SPARK-46830)
XML An external package A built-in source and functions (SPARK-44265)
Python extensibility Python UDTFs (SPARK-43797) Data Source API and polymorphic UDTFs (SPARK-44076)
Streaming state applyInPandasWithState, flatMapGroupsWithState transformWithState, state data source (SPARK-46815, SPARK-45511)
Platform Scala 2.12 and 2.13, Java 8, 11 and 17 Scala 2.13 and Java 17 or 21 (SPARK-45314, SPARK-45315)

Settings and costs

Defaults the 4.0 release notes list as changed.

Setting Default in 4.0 Source
spark.sql.ansi.enabled true SPARK-44444
spark.eventLog.rolling.enabled true SPARK-45771
spark.ui.prometheus.enabled true SPARK-46886
spark.shuffle.service.db.backend ROCKSDB SPARK-45351
Feature Cost to plan for
ANSI mode The change most likely to turn a green pipeline red. Test your real data before the upgrade
Python data source and UDTFs PyArrow must be installed on every node that runs a Python worker
transformWithState The RocksDB state store, and protobuf and gRPC packages for the Python form
Scala 2.13 and Java 17 Every jar the jobs depend on needs a Scala 2.13 build

When these features bite

These are the errors you’re most likely to hit, with the text Spark prints so you can search for it. Each one has its own anchor, so you can link straight to it.

[UNSUPPORTED_FEATURE.STATE_STORE_MULTIPLE_COLUMN_FAMILIES]. transformWithState stores each state variable as its own column family, and the default HDFS-backed state store doesn’t support that. Fix: Set spark.sql.streaming.stateStore.providerClass to the RocksDB provider.

[STREAMING_PYTHON_RUNNER_INITIALIZATION_FAILURE] with ImportError: cannot import name 'descriptor' from 'google.protobuf'. The Python runner for transformWithStateInPandas needs protobuf and the gRPC packages, which the official image lacks. Fix: pip install protobuf grpcio grpcio-status googleapis-common-protos.

[STDS_COMMITTED_BATCH_UNAVAILABLE]. The state data source was read before the query committed a batch. Fix: Let the query commit at least one micro-batch before you read its checkpoint.

[CAST_INVALID_INPUT], [DIVIDE_BY_ZERO]. ANSI mode is on by default, so work that silently produced NULL now stops. Fix: Use try_cast and try_divide where NULL was the intended answer, or set spark.sql.ansi.enabled=false while you fix the data.

ModuleNotFoundError: No module named 'pyarrow' from the Python data source worker. The official image has no PyArrow. Fix: Install pyarrow and pandas.

[DATATYPE_MISMATCH.INVALID_ORDERING_TYPE] on map(...) = map(...). A MAP can be a grouping key in 4.0, but two maps can’t be compared with =. Fix: Group on the map; don’t join on it.

Upgrade checklist: what can break

For most teams the move from 3.x is more than a version bump: Scala, Java, ANSI and a long list of defaults change. Work through this on a staging copy of your heaviest job first.

1. Runtime and dependencies

Requirement 4.0 value Source
Java 17 or 21; JDK 8 and 11 are dropped Spark 4.0.5 overview, SPARK-45315
Scala 2.13 only; Scala 2.12 is dropped SPARK-45314
Python 3.9 or newer requires_python of pyspark==4.0.5 on PyPI
pandas, PyArrow, NumPy (pyspark[sql]) 2.0.0, 11.0.0 and 1.21 or newer requires_dist on PyPI
pyspark[connect] extras grpcio and grpcio-status 1.67.0 or newer requires_dist on PyPI
Kafka connector spark-sql-kafka-0-10_2.13:4.0.5 is published Maven Central

2. Check every connector jar before you upgrade

Connector runtimes are built per Spark minor version and per Scala version, so a jar built for Spark 3.5 and Scala 2.12 won’t load. List the artifacts from your spark.jars.packages and ask Maven Central whether each has a 4.0.5 build, so you find a missing one before the cluster does.

Runnable file: 23_check_maven_artifacts.py.

import urllib.request

# group, artifact: edit to match your spark.jars.packages
ARTIFACTS = [
    ("org.apache.spark", "spark-sql-kafka-0-10_2.13"),
    ("org.apache.spark", "spark-avro_2.13"),
]
SPARK = "4.0.5"

for group, artifact in ARTIFACTS:
    base = f"https://repo1.maven.org/maven2/{group.replace('.', '/')}/{artifact}"
    try:
        urllib.request.urlopen(f"{base}/{SPARK}/{artifact}-{SPARK}.pom", timeout=10)
        print(f"OK       {artifact}:{SPARK}")
    except Exception:
        print(f"MISSING  {artifact}  -> no {SPARK} build published")

The output:

OK       spark-sql-kafka-0-10_2.13:4.0.5
OK       spark-avro_2.13:4.0.5

For third-party connectors, the artifact name carries both the Scala and the Spark version, so use the name the project documents for Spark 4.0. A MISSING line means keep those jobs on their current Spark version.

3. Behaviour changes to test

These come from the official SQL and PySpark migration guides and the release notes, which list many more.

Change What to do Source
Scala 2.13 and JDK 17 are the baseline; Scala 2.12 and JDK 8 and 11 are gone Rebuild every jar for Scala 2.13 SPARK-45314, SPARK-45315
ANSI mode is on by default Test your data; use try_*; spark.sql.ansi.enabled=false restores NULL SPARK-44444
CREATE TABLE without USING uses spark.sql.sources.default, not Hive spark.sql.legacy.createHiveTableByDefault=true SQL migration guide
ORC default compression is zstd, not snappy spark.sql.orc.compression.codec=snappy SQL migration guide
Inner CTEs take precedence (ctePrecedencePolicy is CORRECTED) spark.sql.legacy.ctePrecedencePolicy=EXCEPTION or LEGACY SQL migration guide
Timestamp parse failures raise CANNOT_PARSE_TIMESTAMP in ANSI mode, NULL otherwise spark.sql.legacy.timeParserPolicy=EXCEPTION SQL migration guide
! is no longer accepted as NOT in expr ! IN (...) and similar spark.sql.legacy.bangEqualsNot=true, or write NOT SQL migration guide
JDBC type mappings changed for Postgres, MySQL, Oracle, SQL Server and DB2 Per-database spark.sql.legacy.*Mapping.enabled settings, listed in the guide SQL migration guide
Hive metastore versions before 2.0.0 are unsupported Upgrade the metastore SQL migration guide
Python 3.8 dropped; pandas 2.0.0, NumPy 1.21 and PyArrow 11.0.0 are the minimums Upgrade the Python environment SPARK-47993, SPARK-50657
Many pandas API on Spark removals (iteritems, append, mad, Int64Index) and compute.ops_on_diff_frames on by default Run your pandas-on-Spark code first PySpark migration guide
from pyspark.sql.functions import * no longer exports DataFrame, Column or StructType Import them from pyspark.sql or pyspark.sql.types PySpark migration guide
A map column’s schema is inferred from all key-value pairs, not the first spark.sql.pyspark.legacy.inferMapTypeFromFirstPair.enabled=true PySpark migration guide
spark.eventLog.rolling.enabled, spark.ui.prometheus.enabled and a RocksDB shuffle-service store are on by default Recheck log and metrics setups SPARK-45771, SPARK-46886, SPARK-45351

4. Roll out in this order

  1. Dependencies first. Rebuild your jars for Scala 2.13 and run the connector script above. Keep any job whose connector is missing where it is.
  2. Python. Move to a supported Python with PyArrow 11.0.0 or newer, and test the pandas-on-Spark changes.
  3. Turn ANSI off first, then on. Run the batch job on 4.0 with spark.sql.ansi.enabled=false to separate the upgrade from the data problems, then turn it on and fix what it finds.
  4. Batch jobs. Compare outputs and runtimes against the old cluster.
  5. Streaming jobs last. Restart a copy of each job from a copy of its existing checkpoint in staging first, and keep the old checkpoint and the old Spark version until that run passes.

5. Common mistakes

  • Leaving ANSI untested. It’s the most common reason a job that worked on 3.x fails on 4.0.
  • Forgetting rowTag. The XML reader needs it.
  • Running transformWithState on the default state store. Switch to RocksDB first.
  • Running the Python data source without PyArrow. The official image doesn’t have it.
  • Comparing maps with =. Group by a map, don’t join on one.

Known limitations in this release

  • ANSI mode. Invalid casts and divide by zero are the commonly hit cases; other ANSI behaviours, such as overflow, change too.
  • XML. The reader needs a rowTag, and the inferred field order is alphabetical.
  • Python data source and UDTFs. PyArrow has to be installed on every node that runs a Python worker.
  • transformWithState. The RocksDB state store is required, and the counts in the sample depend on how long the query ran.
  • Maps. A MAP can be a grouping key, but two maps can’t be compared with =.

Cheat sheet

Spark 4.0 cheat sheet: the syntax of each feature and what it needs first, such as PyArrow or the RocksDB state store

Image 22: The syntax of each feature and what has to be on first.

Download the cheat sheet as a PNG.

Frequently Asked Questions

What is new in Apache Spark 4.0?

Spark 4.0.0, released on 23 May 2025, makes Scala 2.13 and Java 17 the baseline, turns ANSI mode on by default, and adds VARIANT, SQL pipe syntax, SQL UDFs, session variables, string collation, a built-in XML source, the Python Data Source API and transformWithState.

Why did my job start failing with CAST_INVALID_INPUT after upgrading?

ANSI mode is on by default in 4.0, so a bad cast raises where it used to return NULL. Use try_cast, or set spark.sql.ansi.enabled=false while you fix the data.

Which Scala and Java versions does Spark 4.0 need?

Scala 2.13 and Java 17. Scala 2.12 and JDK 8 and 11 are no longer supported, so jars need a Scala 2.13 build.

What Python version does Spark 4.0 need?

Python 3.9 or newer, with pandas 2.0.0, PyArrow 11.0.0 and NumPy 1.21 as the minimums for the sql extra.

How do I read XML in Spark 4.0?

Use spark.read.format("xml").option("rowTag", "person").load(path) for files, or from_xml for XML held in a string column. No external package is needed.

Why does my Python data source fail with No module named 'pyarrow'?

The data source worker moves rows through Arrow. The official image doesn’t ship PyArrow, so pip install pyarrow pandas, or use pip install "pyspark[sql]".

Why does transformWithState fail on the default state store?

Each state variable is a separate column family, which only RocksDB supports. Set spark.sql.streaming.stateStore.providerClass to the RocksDB provider.

Can I group by a map column?

Yes, in 4.0. Comparing two maps with = is still an error, so group on the map and don’t join on it.

Which Spark 4.0 release should I use?

4.0.5 is the latest 4.0 release. Fixes land in the patch releases, so start there.

Is it safe to turn ANSI mode off?

It’s a valid stopgap, and spark.sql.ansi.enabled=false restores the old behaviour. Treat it as a way to separate the upgrade from your data problems, not as the place to stay.

Summary

Spark 4.0 changes the baseline and the defaults, and adds the SQL features that were missing. ANSI mode makes bad data visible, VARIANT, UDFs, variables, collation and pipe syntax make SQL more capable, and the XML source and Python Data Source API reduce the connectors you need to build. A few things need setup, PyArrow or the RocksDB state store, so check those before you plan around them.

If you only test one thing before upgrading, make it ANSI mode against your real data. It’s the change that decides whether the rest of the move is smooth.

Further reading

Trademarks

Apache Spark, Apache Kafka, Apache Parquet, Apache Arrow and Apache are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. The Apache Software Foundation does not endorse this post.

Found this useful?

These posts and tools are free. If one saved you an afternoon, you can buy me a coffee.

Buy me a coffee

Comments

Questions, corrections and reviews are welcome. Sign in with GitHub to post; comments are stored in this site's public GitHub Discussions.