Spark Static Analyzer: the technical guardian that reviews Spark code before merge
TL;DR — Spark Static Analyzer is a code review agent integrated into CI/CD that analyzes Pull Request diffs and publishes a technical comment with a quality score (0–100), detected violations, and correction suggestions.
It applies 18 Spark rules covering critical anti-patterns in cost, stability, and security across Python, SQL, Scala, Java, and R.
Critical rules have the capability to block merges via pipeline — activation per repository is managed by the Platform team.
The most important outcome was not automatic blocking — it was continuous feedback in the context of real code, which accelerated collective learning across the team.
The agent operates 100% outside the Databricks cluster — pure static analysis, without executing code or accessing data.
CERC operates the infrastructure of the Brazilian financial market for receivables registration, processing a high volume of data with strict requirements for reliability, governance, and traceability. Every data engineering decision has a direct impact on cost, operational stability, and service quality — which makes quality control in Spark code an operational concern, not merely a matter of good practices.
The problem that motivated building the Spark Static Analyzer was easy to describe but difficult to solve without a systemic approach: the cost of a Spark error in production was high, and the error almost always looked small in the Pull Request. An action in the wrong place. A join without a filter. A collect() without .limit(). None of this stands out in a quick review — all of it can cause real impact within hours.
The problem became more acute when two phenomena combined: teams delivering faster, and AI accelerating code generation. When that happens, isolated manual review does not scale. Change volume grows, available attention per PR shrinks, and anti-patterns that should be blocked reach production silently.
This is the context in which Spark Static Analyzer was built — not as an AI showcase, but as an operational response to a concrete data engineering risk at scale.
The risks no one spots in the Pull Request
To understand why the tool exists, it helps to see what happens without it. The table below is not theoretical — these are anti-patterns that appear in real environments when teams grow and velocity increases:
| Anti-pattern | Observed consequence |
|---|---|
.collect() on a 500 GB table | OOM on the driver, cluster restarted, DBU billed during crash |
.write inside a loop over 30 dates | 30 sequential Spark jobs instead of 1 — 30× the expected cost |
| Accidental cross join between two 1M-row tables | 1 trillion rows — cluster stuck indefinitely |
| Python UDF where a native equivalent exists | 10–100× slower due to JVM↔Python serialization per row |
display(df) without .limit() on a PII table | CPF, CNPJ, and financial values leaked in cluster logs |
inferSchema=True in production | CNPJ inferred as LongType loses leading zeros — silent data corruption |
eval()/exec() with external input | Code injection via orchestration parameters — OWASP A03:2021 |
| Hardcoded credentials | Token permanently in Git history even after removal — OWASP A02:2021 |
The question is not whether these patterns appear in code. It is when and how often — and whether there is a mechanism capable of signaling them before the merge.
What the agent does
The Spark Static Analyzer automatically reviews the diff of each Pull Request and publishes a single technical comment with four sections: a quality score from 0 to 100, a list of violated rules with line number and calculated impact, an objective explanation of the risk for each violation, and a practical correction suggestion. For each analysis, the agent also generates a prompt block ready to paste into any LLM, allowing the author to apply assisted corrections within the same PR.
What the agent does not do is equally important for understanding its architecture: it does not execute code, run queries, access data, or modify files. All analysis is static, performed on the diff text via the Azure DevOps API, with processing running on the CI/CD machine — completely outside the Databricks cluster. This ensures security, predictability, and low latency: under 5 seconds per notebook, regardless of file size.
The scope is restricted to the diff. Only new or modified code in the PR receives analysis. Legacy code outside the PR scope is not penalized.
How it works in the pipeline
The execution flow follows five steps integrated into Shift, CERC’s autonomous agents platform:
- The Pull Request is opened or updated in Azure DevOps.
- The agent collects only new or modified files with supported extensions:
.py,.ipynb,.scala,.java,.r,.R, and.sql. - The engine applies static analysis combining three techniques: AST (Abstract Syntax Tree) for Python semantic constructs, lexical analysis and regex for embedded SQL and credential patterns, and heuristics for cases where the evidence is already deterministic.
- The score is calculated based on the 18 rules and their corresponding penalties.
- The consolidated comment is published to the PR — always as a new comment per execution, preserving the complete history of analyses in the thread.
Configuration files (.yaml, .json, .toml), Markdown, and files under tests/ are automatically ignored.
The scoring model
The calculation formula is:
Score = max(0, 100 − ΣPᵢ)
Where Pᵢ = Wᵢ × min(1, nᵢ × kᵢ) — Wᵢ is the rule’s base weight, nᵢ is the number of occurrences, and kᵢ is the aggravation factor per additional occurrence. The
min(1, ...)ensures no single rule can exceed its base weight.
To make this concrete: a notebook with a single .collect() without .limit() (W=30), plus a hardcoded credential (W=25), plus two missing filters before join() (W=15, k=0.3, n=2) accumulates 30 + 25 + 9 = 64 penalty points, arriving at a score of 36 — rejected. What would previously have been a subjective discussion in a PR comment becomes objective evidence with rule and calculated impact.
The five score bands organize the technical conversation and determine the recommended action:
| Score | Label | Recommended action |
|---|---|---|
| 95–100 | ✅ Excellent | Automatic approval recommended |
| 85–94 | ✅ Approved | Approved with recommendations report in the PR |
| 70–84 | ⚠️ Attention | Approved, but author must explicitly acknowledge in the PR body |
| 50–69 | 🚫 Mandatory review | Requires Staff Engineer approval |
| < 50 | 🔴 Rejected | Tech debt ticket recommended |
For the seven rules classified as critical, the agent goes beyond the comment: it terminates the pipeline step with exit code 2, turning the step red in Azure DevOps. The capability to effectively block the merge — via required check in the branch policy — exists in the platform, but activation per repository is done gradually by the Platform team in coordination with each team.
What the agent checks
The catalog covers four axes: FinOps (compute waste before merge), stability (patterns that bring down shared clusters), security (sensitive data leakage and injection vectors), and governance (auditable score per notebook, PR, and author).
The 18 rules are organized across three severity levels. The seven critical ones terminate the pipeline step when detected, regardless of the total score — they cover the patterns with the greatest immediate impact on cost, stability, and security. The nine high-severity rules penalize the score and generate detailed recommendations with correction suggestions. The two medium-severity rules flag suboptimal patterns that accumulate impact over time.
The agent analyzes code in Python, SQL, Scala, Java, and R, combining AST for Python semantic constructs, regex for embedded SQL and credential patterns, and heuristics for cases where the evidence is deterministic. When a violation is detected, it points to the exact line, explains the risk in the context of that specific code, and suggests the fix — not a generic quality report, but a technical conversation about the specific code in the PR.
The effect that was never in the plan
The most important part of V1 of the Spark Static Analyzer was not the score, nor the automatic blocking.
It was the feedback cycle.
Before the tool, an anti-pattern violation reached the author in two ways: in production, after the cost had already been paid, or in a PR comment that depended on the reviewer having the necessary technical context to identify it. With the agent, the cycle changed completely: the violation is flagged in the context of the real code, still in the Pull Request, with an explanation of the risk and a correction suggestion. The author fixes it in the same PR, a new run validates the adjustment, and the evolution history remains recorded in the thread.
This has a pedagogical effect that compounds. The engineer who fixes an unconstrained collect() in the second PR will not write the same thing in the third. The team that discusses a Non-SARGable violation is building collective understanding of partition pruning. Consistency grows not because someone imposes a standard from outside, but because the standard becomes visible and comprehensible at the right moment — during development, not after the incident.
This is not AI replacing engineering. It is AI raising the engineering bar — alongside policy that reduces variation in judgment across teams.
What it does not do alone
The Spark Static Analyzer does not guarantee results in isolation. For it to function as a control system, four pieces must be in place:
- Clear and calibrated technical rules — without continuous calibration, penalties lose relevance as the environment and workloads evolve.
- Merge policy applied in the repository — effective merge blocking depends on the required check enabled in the Azure DevOps branch policy; activation is done gradually by the Platform team, per repository.
- Effective correction of reported violations — the agent’s comment only has value if the author acts on it.
- Continuous measurement of score, incidents, and cost — without this correlation, there is no way to know whether the tool is fulfilling its purpose.
Without all four, the agent becomes just another Pull Request comment.
Next steps
The planned evolution covers five fronts: better coverage for .ipynb notebooks with structured cell extraction, continuous weight calibration by workload context, adoption expansion with merge policies graded by repository maturity, score trend metrics by repository and team, and correlation between score and reduction in operational incidents and cost.
That last front is the definitive validation that the tool is solving the problem it was built for. Our goal is to keep that relationship measurable — without empty promises of magical automation. AI at CERC is not a productivity add-on: it is part of the engineering system.
This post was written by: Marcel Duarte.