Notes · Debugging Spark
A Spark 3.5 optimizer crash that a cache was hiding
In early November a production job started failing on every retry with an internal Spark error. None of our code was in the stack trace. The cause was an ordinary join key, and a persist() that had been hiding the problem.
[INTERNAL_ERROR] The Spark SQL phase optimization failed with an internal error.
java.lang.AssertionError ... at PushablePredicate ... V2ScanRelationPushDown
The job builds a dimension table by joining several reference views over Iceberg. Those views were keyed on nullif(trim(id), ''), so blank IDs became NULL and wouldn't match anything. It's a common idiom and it does what it says.
What Spark did with it
For an inner join, Spark infers key IS NOT NULL on both sides and tries to push that predicate down toward the scan. Here it went through a max_by aggregate and reached the Iceberg source. On the way, Spark 3.5.1 simplified IsNotNull(nullif(...)) into a top-level If expression. The code that turns Catalyst filters into data source V2 filters asserts that whatever it receives can be translated. An If can't, so the optimizer threw.
This had been sitting there for a while. An upstream persist() meant later stages reused the cached result, so the pushdown never got planned. An unrelated change made the plans stop matching the cache, and from then on every run hit the assertion.
The fix
I changed the keys to trim(id). Blank keys now group under an empty string instead of NULL, and they still match nothing, because the columns they're compared with are nullif'd. I reproduced the failure with PySpark 3.5.1 and Iceberg 1.5.2 using the real views first. The old code failed once the cache was out of the way, the new code passed with and without it, and the output was the same.
Ten days later
A different job hit the same assertion, this time from filters in its own SQL:
-- before: can't be translated to a V2 filter
NULLIF(TRIM(service_name), '') IS NOT NULL
NOT COALESCE(is_deleted, false)
-- after: same meaning
service_name IS NOT NULL AND TRIM(service_name) <> ''
NOT (is_deleted <=> true)
Rewriting the filters took a few minutes. What bothered me more was that the job's tests had all passed. They ran on in-memory DataFrames, and nothing gets pushed down to an in-memory DataFrame, so those tests could never have caught it. I added one that runs the job's SQL against real Iceberg tables in a local catalog. It fails on the old code with the same AssertionError and passes on the new code.
I write Spark SQL a little differently now. Filters that sit directly on a scan stay plain: columns, comparisons, IS NULL, IN, with anything fancier applied after the read. And when a job breaks right after an unrelated change, one of the first things I check is whether a cache used to short-circuit the plan.
More notes at ankitkhare.dev. Questions or corrections: ankit@ankitkhare.dev.