# i almost died trying to figure out what's up with my solution through spark logs- so i automated it, for myself and for y'all.

i built spark-sentinel, a pypi package that analyzes your local spark event logs on your behalf.

last week, i was working my way around some parquet files and an error prompted a quick look at the spark jobs running. it's a canon event in a data engineering career trajectory when you transition from 'i'll build this fecking pipeline and get done with this shi-' to 'how do i solve this problem business presents me with?'. you think beyond getting the job done and more towards how to get the job done with least possible compute, reduce costs, etc. you want the solution to be optimized to its best possible way because that is a significant amount of what businesses want in general anyways(we ain't got enough money to spare). that is the point where every data engineer has had to take a deeper look into the intricacies of the architecture and be presented with shit-tons of logs to skim through. when a spark job runs, it automatically generates an event log file, but what it doesn't do for you is explain what is slowing your query down. we usually got that one on ourselves to figure out.\\

i'm just another node in the ocean of nodes here. event jobs are difficult to look at, requires a couple back and forth explaining sprees with the LLM of your choice, consume enough tokens and use up enough freshwater to cool that damn server. you're adding up to earth debt! and if you're a seasoned one, it takes very long to summon the Apache spark documentation lords to figure out WHAT could have been better, what's taking up space and a lot of mental calculations in the backend as well. you got the data right in front of your eyes, but what spark won't do for you is straight-away tell you to fix xyz. so, i built something that'll do the job of explaining optimization points architecture-wise and also give you a pretty looking report that'll get you to convince your team that you've been doing your job right. (i have intense pytest-coverage report building trauma). spark-sentinel does all that and more, for you. take a join where 70% of the rows share one key. in the ui you see a stage of 16 tasks where one task runs far longer than the rest. to call it data skew, you have to notice that this task also read far more shuffle data than the median, find the sql query that ran the stage, and know that aqe's skew-join handling was switched off. that takes experience, and it takes time on every job. the good news is that you don't need to instrument anything. with *spark.eventlog.enabled=true*, spark writes every task, stage, job, sql plan and setting to an event log: the same file the history server reads. spark sentinel reads that file and does the diagnosis for you. install it and point it at a log spark sentinel is a python command-line tool (python 3.11 or newer).

spark sentinel 0.1 is out on pypi. it reads the event log a spark job already writes and tells you what made the job slow, where it happened, and how to fix it. slow spark jobs hide their causes in plain sight when a spark job is slow, the evidence is usually all there. the spark ui lists every stage and every task, with times, bytes read, bytes shuffled and bytes spilled. it doesn't need spark, java or a cluster: only the log file.

```shell
pipx install spark-sentinel # or: pip install spark-sentinel sentinel analyze /tmp/spark-events
```

if your job doesn't write logs yet, turn them on when you build the session:

```python
spark = (sparksession.builder .config("spark.eventlog.enabled", "true") .config("spark.eventlog.dir", "file:///tmp/spark-events") .getorcreate())
```

here is part of the report for the skewed join from the introduction, run on my laptop:

```python
MED   SKEW001  Stage 4: slowest task is 7x the median
      Query 0 · stage 4
      slowest task 2.6s vs median 363 ms · its input + shuffle read 69.8 MB vs median 2.3 MB
      Data skew: the slowest task read 69.8 MB, 31x the median task's 2.3 MB. One key (or a few)
      holds a large share of the rows.
      → Turn on AQE skew-join handling: spark.sql.adaptive.skewJoin.enabled=true (it is off for this app). Spark then splits the hot partition automatically.
      → Find the hot key(s) of the join on customer_id:
        df.groupBy('customer_id').count().orderBy(F.desc('count')).show(10)
      Spark docs: Optimizing Skew Join
```

it names the stage and the query, shows the numbers behind the verdict, tells data skew apart from compute skew, and starts with the fix that costs least. in the same run it also flagged the join that should have been a broadcast join, and the three settings that turned spark's automatic optimizations off.

add `-f html -o report.html` for a single-file html report that works offline, `-f md` for markdown, or `-f json` for other tools. small local runs finish in seconds, so their problems are small too: `--profile laptop` lowers the thresholds to match.

## thirteen rules, each backed by the spark docs

version 0.1 ships 13 rules. i didn't invent the advice: each rule follows a section of spark's own tuning guides, and every finding links to it, so you can check the reasoning against the source.

## table of rules inclusive of this version:

| rule | what it finds | based on (spark docs) |
| --- | --- | --- |
| `skew001` | one task takes far longer than its siblings; tells data skew from compute skew | [optimizing skew join](https://spark.apache.org/docs/latest/sql-performance-tuning.html#optimizing-skew-join) |
| `spill001` | tasks spill to disk for lack of execution memory | [memory usage of reduce tasks](https://spark.apache.org/docs/latest/tuning.html#memory-usage-of-reduce-tasks) |
| `gc001` | tasks spend a large share of their time in garbage collection | [garbage collection tuning](https://spark.apache.org/docs/latest/tuning.html#garbage-collection-tuning) |
| `files001` | a write produces many small files | [coalesce hints](https://spark.apache.org/docs/latest/sql-performance-tuning.html#coalesce-hints) |
| `part001` | too many shuffle partitions for the data | [coalescing post shuffle partitions](https://spark.apache.org/docs/latest/sql-performance-tuning.html#coalescing-post-shuffle-partitions) |
| `part002` | too few shuffle partitions, so each task is huge | [tuning partitions](https://spark.apache.org/docs/latest/sql-performance-tuning.html#tuning-partitions) |
| `par001` | a long stage with fewer tasks than cores | [level of parallelism](https://spark.apache.org/docs/latest/tuning.html#level-of-parallelism) |
| `plan001` | a python udf in a filter blocks pushdown into the file scan | [arrow python udfs](https://spark.apache.org/docs/latest/api/python/tutorial/sql/arrow_pandas.html#arrow-python-udfs) |
| `plan002` | a join without an equality key: a cartesian or nested-loop join | [join strategy hints](https://spark.apache.org/docs/latest/sql-performance-tuning.html#join-strategy-hints) |
| `plan003` | all of a query's data goes through one task, e.g. a window without `partitionBy` | [avoid computation on single partition](https://spark.apache.org/docs/latest/api/python/tutorial/pandas_on_spark/best_practices.html#avoid-computation-on-single-partition) |
| `plan004` | a sort-merge join where one side was small enough to broadcast | [automatically broadcasting joins](https://spark.apache.org/docs/latest/sql-performance-tuning.html#automatically-broadcasting-joins) |
| `plan005` | a python udf runs row by row instead of in arrow batches | [arrow python udfs](https://spark.apache.org/docs/latest/api/python/tutorial/sql/arrow_pandas.html#arrow-python-udfs) |
| `conf001` | settings that switch off spark's automatic optimizations (informational) | [adaptive query execution](https://spark.apache.org/docs/latest/sql-performance-tuning.html#adaptive-query-execution) |

every finding has the same shape: a severity, the place (stage, job and sql query), the evidence as numbers, a one-sentence cause, fixes in order of effort, and the doc links. because the shape is shared, every report format and every ci check works for any rule, including ones added later.

the [rule catalog](https://github.com/r4otxrhs3/spark-sentinel/blob/main/docs/rule-catalog.md) goes further. it maps every section of spark's tuning guides to the symptom sentinel looks for, including rules planned for later and advice an event log can't check at all.

## how it works

sentinel parses a log once into tables, then answers every question about it with sql.

```plaintext
event log → reader → parser → parquet + duckdb → 13 rules → reports
```

the reader streams the log line by line, so a multi-gigabyte log never has to fit in memory. the parser turns spark's events into eight tables, stored as parquet and queried with duckdb. parsing is the slow part and happens once; each rule is then one sql query plus the code that turns its result into a diagnosis.

the tables keep spark's links between things: each task belongs to a stage, each stage to a job, and each job to a sql query and its physical plan. that chain is how a finding can name the join key, the udf or the repartition(500) behind a slow task, not just the stage number. you can query the same tables yourself with sentinel.

```sql
SELECT ... FROM tasks
```

## a gallery of bad jobs keeps the false alarms out

a linter that cries wolf gets switched off, so false alarms worried me more than missed problems. to test both, i wrote a gallery of 11 small pyspark jobs: 10 that each cause one known problem on purpose, and one clean job that should trigger nothing.

| job | how it causes the problem | what the log shows |
| --- | --- | --- |
| `skew` | 70% of rows share one join key | slowest task 7x the median, reading 31x the median's shuffle data |
| `spill` | sorts 6m wide rows in 4 partitions with 1 gb of memory | about 250 mb spilled to disk |
| `small_files` | `repartition(500)` before a write of a few mb | 500 files, median 7 kb each |
| `over_partitioned` | 1,000 shuffle partitions for about 5 mb of data | median task reads 5 kb |
| `cross_join` | a join on `a < b - 80`, with no equality key | `CartesianProduct` in the final plan |
| `window_no_partition` | a running total over `Window.orderBy("ts")` | one task reads all 35 mb |
| `gc_pressure` | a 2 mb young generation while `collect_list` allocates | 27% and 37% of task time in gc |
| `clean` | pushed-down filter, even keys, aqe on | nothing |

the table of which rule must fire on which job lives in the gallery's readme, and the test suite reads it from there. every expected rule must fire and every blank cell must stay blank. that's checked on logs from spark 4.3 and spark 3.5, under both threshold profiles. all 13 rules give the same results on both versions.

i also measured how far each threshold sits from a false alarm. on the gallery, gc001 would only misfire near an 8% gc share, and par001 only on stages of about 1 second. on top of that come boundary tests (fires exactly at a threshold, not one unit below), and mutation testing: breaking a rule on purpose must turn a test red. the release shipped with over 400 tests that run in about 30 seconds, without spark.

## what surprised me along the way

most of the work wasn't writing rules. it was learning where the event log, spark and my tools don't behave the way you'd assume. a few of the lessons:

- **a cold jvm looks like skew.** in one job, the first wave of tasks took about 1.5 s each and every later task about 0.15 s: a 10x gap with no skew at all. bytes settle it. the truly skewed task read 31x the median's data, so skew001 trusts bytes over time.
- **aqe hides problems on small data.** with partition coalescing on, spark merged the skewed join's 16 partitions into 3, and the 31x hot partition looked like 2.7x. on a real cluster, check the `spark.sql.adaptive.*` settings before blaming the code.
- **a plan with aqe lists every operator twice:** once in the final plan and once in the initial one, under different ids. rules must read only the final plan, or they report every problem twice, including ones aqe already fixed.
- **arrow python udfs are on by default from spark 4.2, but fall back silently** to row-by-row udfs when pandas or pyarrow is missing, and `pip install pyspark` installs neither. so a `BatchEvalPython` node in a 4.2+ plan means the udf opted out or fell back.
- **"nothing pushed down" is a missing line, not an empty list.** a parquet scan with no pushed filters simply has no `PushedFilters` line in the plan.
- **in duckdb,** `x / 0` **is infinity, not null.** every ratio in a rule's sql needs `NULLIF(x, 0)`, or an empty stage turns into an "infinitely bad" finding.

the gallery readme lists all 15 lessons, each with the job that taught it.

## make it fail the build

sentinel is built for ci as much as for a terminal. run a small test job in your pipeline with event logging on, then:

```bash
sentinel analyze path/to/eventlogs --fail-on high -f md -o sentinel.md
```

the markdown report reads well as a pull-request comment, and the exit code tells the pipeline what happened:

| exit code | meaning |
| --- | --- |
| 0 | analysis ran, and nothing was at or above `--fail-on` (by default, findings never fail the build) |
| 1 | a finding at or above `--fail-on` |
| 2 | bad options or config |
| 3 | an event log couldn't be read, or a rule crashed |

settings can live in a `sentinel.toml` next to your code, and command-line options override them:

```toml
profile = "laptop"     # ci test jobs are small
fail_on = "high"
format  = "md"
ignore  = ["CONF001"]

[thresholds.SKEW001]
min_time_lost_ms = 5000
```

## what 0.1 doesn't do yet, and what's next

version 0.1 has clear limits:

- it reads local files only, so copy logs from s3, hdfs or dbfs first.
- it reads plain, gzip and zstd logs (zstd is spark's default), but not spark's `lz4`, `lzf` or `snappy` codecs.
- it doesn't parse per-operator sql metrics yet (rows per plan node, files read), so the rules that need them are still on the catalog's planned list.
- thresholds default to production-sized jobs. use `--profile laptop` for small runs.

next comes **diff mode**, which is built and will ship in the next release. `sentinel diff` compares a baseline run with a pull request's run and explains what changed. for example: "query 0 is 1.5x slower: the broadcast join became a sort-merge join, after `spark.sql.autoBroadcastJoinThreshold` changed to -1." getting it right meant handling noise: an unchanged job's first run after a pause was 1.7x slower than the next one. so a slowdown only counts when something measurable changed with it, such as the plan, the data shuffled, spill or a setting.

after that: a github action that posts the diff on every pull request, cost estimates from executor lifetimes, and write-ups of the design decisions.

## try it on your own logs

```bash
pipx install spark-sentinel
sentinel analyze /path/to/your/spark-events --profile laptop
```

the real test is a log from a real job. the gallery was built to trigger the rules, so a production log is the honest check of how often sentinel is right. if a finding looks wrong, or a problem you know about goes unreported, please open an issue. those reports are the most useful input for the next release.

new rules are welcome too. the [contributing guide](https://github.com/r4otxrhs3/spark-sentinel/blob/main/CONTRIBUTING.md) walks through adding one: reproduce the problem in a gallery job, find the signal with `sentinel sql`, write the rule, and prove it stays quiet on every other job.

- package: [spark-sentinel on pypi](https://pypi.org/project/spark-sentinel/)
- code and issues: [github.com/r4otxrhs3/spark-sentinel](https://github.com/r4otxrhs3/spark-sentinel)
- rules and the spark docs behind them: [rule catalog](https://github.com/r4otxrhs3/spark-sentinel/blob/main/docs/rule-catalog.md)
- license: apache 2.0
