Home / Databricks on Azure

Databricks on AzureTroubleshootingBeginner

Databricks Py4JJavaError and \"Job aborted due to stage failure\": find the real error in a long stack trace

A failed Databricks task shows hundreds of lines of Java and Python. Find the line that names the cause, map it to a fix, and catch errors by condition in code.

Deepak Bhardwaj7 min read

Applies toAzure Databricks notebooks and Lakeflow Jobs on classic compute (dedicated and standard access mode) and serverless; PySpark 3.5 (DBR 14.3-16.4 LTS) and Spark 4.x (DBR 17+); Databricks CLI (current version)

Symptom

A job task or notebook cell fails and the output is a wall of text. It usually starts with one of these:

  • Py4JJavaError: An error occurred while calling o123.save.
  • org.apache.spark.SparkException: Job aborted due to stage failure: Task 7 in stage 42.0 failed 4 times, most recent failure: Lost task 7.3 in stage 42.0 (TID 913) (10.139.64.12 executor 3): ...
  • pyspark.errors.exceptions.captured.AnalysisException: [TABLE_OR_VIEW_NOT_FOUND] ...
  • PythonException: An exception was thrown from the Python worker.

The first line is almost never the cause. It tells you which layer failed: Python, the driver JVM, or a task on an executor. The cause is further down.

How to read the trace in 60 seconds

Work through the trace in this order.

  1. Look for an error condition in square brackets. Since Spark 3.4, most errors carry a name such as [UNRESOLVED_COLUMN.WITH_SUGGESTION] or [DELTA_CONCURRENT_APPEND], plus a SQLSTATE. If you see one, that is your cause. Search the name in the Databricks error conditions reference.
  2. If there is no bracketed name, find the last Caused by:. Java chains exceptions. The outermost one (SparkException, Py4JJavaError) is a wrapper. The innermost Caused by: is what actually broke.
  3. For Job aborted due to stage failure, read the text after most recent failure: Lost task ...:. That is the exception the task threw. "Failed 4 times" means Spark retried the task up to spark.task.maxFailures (default 4). If all four attempts show the same error, the problem is in the data or the code. If the attempts show different errors, the cause is usually the environment, such as a lost executor or a storage throttle.
  4. For PythonException, skip to the Python traceback inside it. The File "...", line N, in <func> lines and the last line (KeyError: 'amount', ValueError: ...) come from your UDF or applyInPandas code running on an executor.
  5. Ignore frames from py4j, sun.reflect, java.lang.Thread and org.apache.spark.scheduler. They show how the call travelled, not why it failed.

Tip

The full trace from a failed job task is available outside the UI. Copy it into a text file and search for Caused by and Exception rather than scrolling through it in the browser.

Get the full error from the CLI

The job run page shortens long errors. Use the Databricks CLI to get the complete text. Task runs have their own run IDs, so first list the task runs of the job run.

# Task runs, their state and the short error message
databricks jobs get-run 987654321 -o json \
  | jq -r '.tasks[] | [.task_key, .run_id, .state.result_state, .state.state_message] | @tsv'

# Full error and trace for one task run
databricks jobs get-run-output 123456789 -o json | jq -r '.error'
databricks jobs get-run-output 123456789 -o json | jq -r '.error_trace' > trace.txt

# The lines that usually matter
grep -nE '^\s*Caused by:|\[[A-Z_]+(\.[A-Z_]+)?\]|most recent failure' trace.txt | tail -20

The same thing in PowerShell:

$out = databricks jobs get-run-output 123456789 -o json | ConvertFrom-Json
$out.error_trace | Set-Content trace.txt -Encoding utf8
Select-String -Path trace.txt -Pattern 'Caused by:', 'most recent failure', '\[[A-Z_]+' | Select-Object -Last 20

To find out whether this task fails every night or just started failing, query the job system tables. Column availability varies by release, so run DESCRIBE system.lakeflow.job_task_run_timeline first.

SELECT job_id, task_key, run_id, period_start_time, result_state, termination_code
FROM system.lakeflow.job_task_run_timeline
WHERE job_id = '1122334455'
  AND period_start_time >= current_date() - INTERVAL 14 DAYS
ORDER BY period_start_time DESC;

Map the root cause to a fix

Use the innermost exception or the bracketed condition from the trace.

What you find in the trace Usual cause First fix
[TABLE_OR_VIEW_NOT_FOUND] (SQLSTATE 42P01) Wrong catalog or schema, missing USE CATALOG privilege, job running in a different default catalog Use three-level names; check grants for the job's run-as identity
[UNRESOLVED_COLUMN.WITH_SUGGESTION] (42703) Upstream column renamed or dropped Compare the source schema with the code; the message suggests close matches
[CAST_INVALID_INPUT], [DIVIDE_BY_ZERO], [ARITHMETIC_OVERFLOW] Bad input values under ANSI mode try_cast, try_divide, or quarantine the bad rows
java.io.FileNotFoundException on a .parquet file Files removed by VACUUM, an overwrite or a storage cleanup while a reader was running Re-run the read; check DESCRIBE HISTORY for overlapping writes and VACUUM
AbfsRestOperationException with 403 / AuthorizationPermissionMismatch Storage RBAC, firewall or external location permission Check the access connector role and the storage firewall
AbfsRestOperationException with 503 / ServerBusy Storage account throttling Reduce parallel listing, spread data across accounts
SparkOutOfMemoryError, ExecutorLostFailure ... exit code 137 Executor memory exhausted, skew, oversized partitions Check the Spark UI for skewed tasks; use more partitions or a larger VM
[DELTA_CONCURRENT_APPEND], ConcurrentAppendException Two writers touched the same files Narrow the write predicate or serialise the writers
SQLServerException, PSQLException, Connection refused JDBC target, network path or credentials Test connectivity from the cluster; check firewall and secret
PythonException + KeyError / TypeError Bug or unexpected data in a UDF Reproduce on a sample with the same input row

Warning

Don't fix a FileNotFoundException by setting spark.sql.files.ignoreMissingFiles to true in production. The job will succeed while silently skipping data.

Catch errors by condition in code

Matching on message text breaks when Databricks rewords a message. Match on the error condition and SQLSTATE instead. In PySpark, errors raised by Spark inherit from pyspark.errors.PySparkException. This works on classic compute and on Spark Connect (serverless and standard access mode).

from pyspark.errors import PySparkException

def error_condition(e: PySparkException):
    # getCondition() exists from Spark 4.0 (DBR 17+); getErrorClass() on older runtimes
    return e.getCondition() if hasattr(e, "getCondition") else e.getErrorClass()

try:
    spark.read.table("main.sales.orders").write.mode("append").saveAsTable("main.sales.orders_copy")
except PySparkException as e:
    cond = error_condition(e)
    print(f"condition={cond} sqlstate={e.getSqlState()} params={e.getMessageParameters()}")
    if cond == "TABLE_OR_VIEW_NOT_FOUND":
        raise RuntimeError("Source table missing - check upstream job and grants") from e
    raise

On DBR 17 and later, getErrorClass() still works but raises a FutureWarning. The helper above avoids that.

On classic compute, some JVM errors still come through as a raw py4j.protocol.Py4JJavaError. Its java_exception attribute holds the Java exception, and you can walk the cause chain:

from py4j.protocol import Py4JJavaError

try:
    df.write.format("jdbc").options(**jdbc_opts).save()
except Py4JJavaError as e:
    cause = e.java_exception
    while cause.getCause() is not None:
        cause = cause.getCause()
    print(cause.getClass().getName(), cause.getMessage())
    raise

Spark Connect does not use Py4J, so this block never runs on serverless or standard access mode. Catch PySparkException there.

Caution

Always re-raise after logging. A try/except that swallows the exception makes the job task show Succeeded. Downstream tasks then run on missing or partial data.

When the trace is not enough

  • The driver trace only says the task failed. Open the Spark UI, go to Stages, find the failed stage and open the failed task's error. To see what the executor logged before it failed, open the executor's stderr from the Executors tab.
  • The cluster died rather than the task. Look at the cluster event log and the termination reason, not the notebook output.
  • The error appears only under the job, not interactively. Compare the run-as identity, the compute (job cluster vs your all-purpose cluster), the runtime version and the default catalog. All four commonly differ.

Prevent it next time

  • Put a short, specific message on each failure you expect (missing input, empty source, schema drift) and raise it before Spark does. A clear message in the job's error field saves the on-call engineer the trace.
  • Log the condition and SQLSTATE from PySparkException to a run log table so recurring failures can be grouped with SQL.
  • Remove broad except Exception: pass blocks from production notebooks. Search the repo for them before each release.
  • Add a job failure notification to the on-call channel that includes the run URL. The trace is one click away from the run page.
  • Pin the runtime version for production jobs, and test runtime upgrades in a lower environment. Error behaviour changes, such as ANSI mode defaults, show up in that test.