Project 03 · Applied AI for data engineering
AI-Assisted SQL Optimizer
A CLI that parses Spark and Snowflake SQL with sqlglot, flags anti-patterns with six heuristic rules, and sends the SQL plus structured findings to Claude for a rewrite. Everything below is the real corpus and real analyzer output — no simulated results.
$ make benchmark
Benchmark over 5 queries (dry_run=True)
┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
┃ Category ┃ Queries ┃ Avg keyword overlap ┃ Findings hit rate ┃
┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩
│ join_optimization │ 1 │ 1.00 │ 1.00 │
│ aggregation_rewrite │ 1 │ 0.33 │ 1.00 │
│ cte_flattening │ 1 │ 0.00 │ 1.00 │
│ partition_pruning │ 1 │ 0.00 │ 0.00 │
│ broadcast_join │ 1 │ 0.33 │ 1.00 │
└─────────────────────┴─────────┴─────────────────────┴───────────────────┘
EXPLAIN step not run: no engine (pass --explain spark|snowflake). At a glance
At a glance
- Problem
- Closes the gap between 'a query that runs' and 'a query a senior would ship' for Spark SQL and Snowflake workloads.
- Approach
- sqlglot AST + six heuristic rules produce structured findings; a versioned prompt sends them to Claude; a 5-query corpus with ground truth scores the analyzer.
- Run it
-
cd project-ai-sql-optimizer && make install && make benchmark - Tests
- 45 passing · CI on every push
- Docs
- README (opens in new tab) Methodology (opens in new tab)
What exists — honestly
Status key →- Measured
sqlglot parse + 6 heuristic rules
4 of 6 rules fire on the corpus
- Measured
5-query corpus with ground truth
make benchmark (dry run)
- Implemented
Claude rewrite via versioned prompt
needs ANTHROPIC_API_KEY; not benchmarked
- Stub
Cloudflare Worker proxy for live mode
wrangler.toml placeholders
- Implemented
Claude in the benchmark (--no-dry-run)
needs ANTHROPIC_API_KEY; no live run recorded
- Needs infra
EXPLAIN cost verification
--explain spark|snowflake; needs an engine with the corpus tables
- Planned
Human acceptance study
4 / 5
queries with ≥1 analyzer finding
real corpus · heuristics only, no API
How this was measured
- Method
- make benchmark (dry run)
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
Caveat · Any finding counts as a hit; whether the finding is the right one is not scored.
Evidence ledger0.33
benchmark keyword overlap
analyzer findings only · heuristics, no API
How this was measured
- Method
- make benchmark (dry run)
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
0.9 ms
analyzer latency per query
in-process median, warm · n=200
How this was measured
- Method
- scripts/artifacts/sqlopt.py times analyze() over the 5 corpus queries ×40
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
45
unit tests passing
analyzer, benchmark, CLI, client, EXPLAIN
How this was measured
- Method
- make test
- Date
- 2026-10-05
- Env
- 4 vCPU · Python 3.11.15 · seed 42
Re-measured Oct 2026 from the project's own make targets on synthetic data (seed 42) — full ledger and transcripts.
Query workbench
Five real queries, one anti-pattern each
Pick a query to see what the analyzer actually reports, which ground-truth
keywords it earns, a reference rewrite with its assumptions, and the exact
message the CLI would send to Claude. Tabs deep-link (#q1–#q5).
corpus/queries/01_join_optimization.sql
Join optimization
An order-line join against a small dim_product table. The query selects everything and joins without a broadcast hint - the optimizer may pick a shuffled hash join even though dim_product is well under the 8MB broadcast threshold.
- tables
- 2
- ctes
- 0
- joins
- 1
- lines
- 5
tagged: spark parsed as: spark
Original
SELECT *
FROM bronze.fct_order_lines fol
JOIN bronze.dim_product dp
ON fol.product_id = dp.product_id
WHERE fol.order_date >= '2026-01-01'; Analyzer findings · real output
-
warn
select_starSELECT * fans out columns and disables column pruning. List columns explicitly.
-
info
consider_broadcastJoin detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
4 rules didn't fire
- cross_join
- missing_partition_predicate
- correlated_subquery
- many_ctes
Ground truth · keyword matches
-
"broadcast"in findings -
"select"in findings
benchmark score 1.00 (2/2 keywords in findings)
Reference rewrite
Project the columns, broadcast the dimension
Replace SELECT * with the columns a consumer needs and hint the small dim_product side for a broadcast hash join instead of a shuffle.
Line diff, original to rewrite
SELECT *SELECT /*+ BROADCAST(dp) */ fol.order_id, fol.order_date, fol.product_id, fol.quantity, fol.amount_usd, dp.product_name, dp.categoryFROM bronze.fct_order_lines folJOIN bronze.dim_product dp ON fol.product_id = dp.product_idWHERE fol.order_date >= '2026-01-01';
- Parses (spark) yes
- Analyzer findings 2 → 0
- Ground-truth keywords in SQL 2/2
Assumptions
- The column list is illustrative; the real consumer's needs decide it.
- dim_product stays under the broadcast threshold. With AQE on Spark 3.x the planner may already convert this join at runtime when statistics are fresh.
What Claude would receive for this query client._build_user_message()
## Dialect spark ## SQL ```sql -- engine: spark -- category: join_optimization -- An order-line join against a small dim_product table. The query selects -- everything and joins without a broadcast hint - the optimizer may pick a -- shuffled hash join even though dim_product is well under the 8MB -- broadcast threshold. SELECT * FROM bronze.fct_order_lines fol JOIN bronze.dim_product dp ON fol.product_id = dp.product_id WHERE fol.order_date >= '2026-01-01'; ``` ## Heuristic findings - (warn) select_star: SELECT * fans out columns and disables column pruning. List columns explicitly. - (info) consider_broadcast: Join detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it. Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`.
corpus/queries/02_aggregation_rewrite.sql
Aggregation rewrite
Counts and sums computed via correlated subqueries instead of a single GROUP BY. Each subquery scans the fact table again; in Snowflake this defeats result-set caching and inflates credits.
- tables
- 2
- ctes
- 0
- joins
- 0
- lines
- 8
tagged: snowflake parsed as: spark The benchmark ignores the engine header.
Original
SELECT
c.customer_id,
c.customer_name,
(SELECT COUNT(*) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS order_count,
(SELECT SUM(amount_usd) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS total_spend_usd,
(SELECT MAX(order_date) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS last_order_at
FROM gold.dim_customer c
WHERE c.is_active = TRUE; Analyzer findings · real output
-
warn
correlated_subqueryCorrelated subquery detected. Consider rewriting as a JOIN or windowed expression.
5 rules didn't fire
- select_star
- cross_join
- missing_partition_predicate
- consider_broadcast
- many_ctes
Ground truth · keyword matches
-
"group by"query text only -
"left join"missed -
"subquery"in findings
benchmark score 0.33 (1/3 keywords in findings)
Reference rewrite
One GROUP BY instead of three correlated scans
Aggregate gold.fct_orders once per customer in a CTE and LEFT JOIN it to the active customers, so the fact table is scanned once instead of three times.
Line diff, original to rewrite
WITH order_stats AS ( SELECT customer_id, COUNT(*) AS order_count, SUM(amount_usd) AS total_spend_usd, MAX(order_date) AS last_order_at FROM gold.fct_orders GROUP BY customer_id)SELECT c.customer_id, c.customer_name, (SELECT COUNT(*) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS order_count, (SELECT SUM(amount_usd) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS total_spend_usd, (SELECT MAX(order_date) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS last_order_at COALESCE(s.order_count, 0) AS order_count, s.total_spend_usd, s.last_order_atFROM gold.dim_customer cLEFT JOIN order_stats s ON s.customer_id = c.customer_idWHERE c.is_active = TRUE;
- Parses (spark) yes
- Analyzer findings 1 → 1
- Ground-truth keywords in SQL 2/3
still flagged: consider_broadcast
Assumptions
- COALESCE(order_count, 0) keeps the zero that a correlated COUNT(*) returns for customers without orders; SUM and MAX stay NULL, as before.
- The LEFT JOIN preserves every active customer, matching the original row count.
What Claude would receive for this query client._build_user_message()
## Dialect
spark
## SQL
```sql
-- engine: snowflake
-- category: aggregation_rewrite
-- Counts and sums computed via correlated subqueries instead of a single
-- GROUP BY. Each subquery scans the fact table again; in Snowflake this
-- defeats result-set caching and inflates credits.
SELECT
c.customer_id,
c.customer_name,
(SELECT COUNT(*) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS order_count,
(SELECT SUM(amount_usd) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS total_spend_usd,
(SELECT MAX(order_date) FROM gold.fct_orders o WHERE o.customer_id = c.customer_id) AS last_order_at
FROM gold.dim_customer c
WHERE c.is_active = TRUE;
```
## Heuristic findings
- (warn) correlated_subquery: Correlated subquery detected. Consider rewriting as a JOIN or windowed expression.
Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`. corpus/queries/03_cte_flattening.sql
CTE flattening
Several CTEs that each read the same source table and apply near-identical filters. Spark's Catalyst will not always combine these automatically, so the underlying scan can run multiple times.
- tables
- 7
- ctes
- 6
- joins
- 2
- lines
- 34
tagged: spark parsed as: spark
Original
WITH voice_calls AS (
SELECT caller_msisdn, start_time, duration_sec, market
FROM silver.cdr WHERE call_type = 'VOICE'
),
sms_msgs AS (
SELECT caller_msisdn, start_time, market
FROM silver.cdr WHERE call_type = 'SMS'
),
data_sessions AS (
SELECT caller_msisdn, start_time, bytes_used, market
FROM silver.cdr WHERE call_type = 'DATA'
),
voice_agg AS (
SELECT market, COUNT(*) AS voice_count, SUM(duration_sec) AS voice_seconds
FROM voice_calls GROUP BY market
),
sms_agg AS (
SELECT market, COUNT(*) AS sms_count
FROM sms_msgs GROUP BY market
),
data_agg AS (
SELECT market, COUNT(*) AS data_count, SUM(bytes_used) AS bytes_total
FROM data_sessions GROUP BY market
)
SELECT
v.market,
v.voice_count,
v.voice_seconds,
s.sms_count,
d.data_count,
d.bytes_total
FROM voice_agg v
LEFT JOIN sms_agg s USING (market)
LEFT JOIN data_agg d USING (market); Analyzer findings · real output
-
info
consider_broadcastJoin detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
-
info
many_ctes6 CTEs found; some Spark plans benefit from flattening.
4 rules didn't fire
- select_star
- cross_join
- missing_partition_predicate
- correlated_subquery
Ground truth · keyword matches
-
"single scan"missed -
"filter(call_type"missed -
"case when"missed
benchmark score 0.00 (0/3 keywords in findings)
Reference rewrite
Six CTEs → one scan with conditional aggregates
Read silver.cdr once and compute each call-type metric with conditional aggregation instead of three filtered CTEs, three GROUP BYs and two joins.
Line diff, original to rewrite
WITH voice_calls AS ( SELECT caller_msisdn, start_time, duration_sec, market FROM silver.cdr WHERE call_type = 'VOICE'),sms_msgs AS ( SELECT caller_msisdn, start_time, market FROM silver.cdr WHERE call_type = 'SMS'),data_sessions AS ( SELECT caller_msisdn, start_time, bytes_used, market FROM silver.cdr WHERE call_type = 'DATA'),voice_agg AS ( SELECT market, COUNT(*) AS voice_count, SUM(duration_sec) AS voice_seconds FROM voice_calls GROUP BY market),sms_agg AS ( SELECT market, COUNT(*) AS sms_count FROM sms_msgs GROUP BY market),data_agg AS ( SELECT market, COUNT(*) AS data_count, SUM(bytes_used) AS bytes_total FROM data_sessions GROUP BY market)SELECT v.market, market, v.voice_count, v.voice_seconds, s.sms_count, d.data_count, d.bytes_totalFROM voice_agg vLEFT JOIN sms_agg s USING (market)LEFT JOIN data_agg d USING (market); COUNT(CASE WHEN call_type = 'VOICE' THEN 1 END) AS voice_count, SUM(CASE WHEN call_type = 'VOICE' THEN duration_sec END) AS voice_seconds, NULLIF(COUNT(CASE WHEN call_type = 'SMS' THEN 1 END), 0) AS sms_count, NULLIF(COUNT(CASE WHEN call_type = 'DATA' THEN 1 END), 0) AS data_count, SUM(CASE WHEN call_type = 'DATA' THEN bytes_used END) AS bytes_totalFROM silver.cdrWHERE call_type IN ('VOICE', 'SMS', 'DATA')GROUP BY marketHAVING COUNT(CASE WHEN call_type = 'VOICE' THEN 1 END) > 0;
- Parses (spark) yes
- Analyzer findings 2 → 0
- Ground-truth keywords in SQL 1/3
Assumptions
- HAVING voice_count > 0 keeps the original driving set (markets with at least one voice call).
- NULLIF(…, 0) reproduces the NULLs the original LEFT JOINs produce for markets with no SMS or data rows.
What Claude would receive for this query client._build_user_message()
## Dialect
spark
## SQL
```sql
-- engine: spark
-- category: cte_flattening
-- Several CTEs that each read the same source table and apply
-- near-identical filters. Spark's Catalyst will not always combine these
-- automatically, so the underlying scan can run multiple times.
WITH voice_calls AS (
SELECT caller_msisdn, start_time, duration_sec, market
FROM silver.cdr WHERE call_type = 'VOICE'
),
sms_msgs AS (
SELECT caller_msisdn, start_time, market
FROM silver.cdr WHERE call_type = 'SMS'
),
data_sessions AS (
SELECT caller_msisdn, start_time, bytes_used, market
FROM silver.cdr WHERE call_type = 'DATA'
),
voice_agg AS (
SELECT market, COUNT(*) AS voice_count, SUM(duration_sec) AS voice_seconds
FROM voice_calls GROUP BY market
),
sms_agg AS (
SELECT market, COUNT(*) AS sms_count
FROM sms_msgs GROUP BY market
),
data_agg AS (
SELECT market, COUNT(*) AS data_count, SUM(bytes_used) AS bytes_total
FROM data_sessions GROUP BY market
)
SELECT
v.market,
v.voice_count,
v.voice_seconds,
s.sms_count,
d.data_count,
d.bytes_total
FROM voice_agg v
LEFT JOIN sms_agg s USING (market)
LEFT JOIN data_agg d USING (market);
```
## Heuristic findings
- (info) consider_broadcast: Join detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
- (info) many_ctes: 6 CTEs found; some Spark plans benefit from flattening.
Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`. corpus/queries/04_partition_pruning.sql
Partition pruning
The events table is partitioned by ingest_date but the query filters on a derived date_format expression, which Spark cannot push down to the partition predicate.
- tables
- 1
- ctes
- 0
- joins
- 0
- lines
- 7
tagged: spark parsed as: spark
Original
SELECT
market,
COUNT(*) AS event_count
FROM silver.cdr_events
WHERE date_format(start_time, 'yyyy-MM') = '2026-04'
AND market = 'WEST'
GROUP BY market; Analyzer findings · real output
No findings.
The partition rule only runs when partition columns are passed; the benchmark passes none.
With --partition-columns ingest_date:
high missing_partition_predicate No WHERE predicate filters by a partition column; full table scan likely.
6 rules didn't fire
- select_star
- cross_join
- missing_partition_predicate
- consider_broadcast
- correlated_subquery
- many_ctes
Ground truth · keyword matches
-
"ingest_date"query text only -
"between"missed -
"partition"query text only
benchmark score 0.00 (0/3 keywords in findings)
Reference rewrite
Give the planner a partition predicate
Bound ingest_date directly so Spark can prune partitions, and keep an exact start_time range so the result is unchanged.
Line diff, original to rewrite
SELECT market, COUNT(*) AS event_countFROM silver.cdr_eventsWHERE date_format(start_time, 'yyyy-MM') = '2026-04'WHERE ingest_date BETWEEN DATE '2026-04-01' AND DATE '2026-05-01' AND start_time >= TIMESTAMP '2026-04-01 00:00:00' AND start_time < TIMESTAMP '2026-05-01 00:00:00' AND market = 'WEST'GROUP BY market;
- Parses (spark) yes
- Analyzer findings 0 → 0
- Ground-truth keywords in SQL 2/3
Assumptions
- Events land in an ingest_date partition no later than one day after start_time; the upper bound would need widening for later arrivals.
- start_time is a timestamp. The original date_format() filter is replaced by a sargable range rather than kept alongside it.
What Claude would receive for this query client._build_user_message()
## Dialect
spark
## SQL
```sql
-- engine: spark
-- category: partition_pruning
-- The events table is partitioned by ingest_date but the query filters on
-- a derived date_format expression, which Spark cannot push down to the
-- partition predicate.
SELECT
market,
COUNT(*) AS event_count
FROM silver.cdr_events
WHERE date_format(start_time, 'yyyy-MM') = '2026-04'
AND market = 'WEST'
GROUP BY market;
```
Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`. corpus/queries/05_broadcast_join.sql
Broadcast join
Three-table join where dim_market is small (~5 rows) but is being shuffled because the planner does not see size statistics. The fix is engine-specific: a broadcast hint in Spark, or a result-set cache plus search-optimization in Snowflake.
- tables
- 3
- ctes
- 0
- joins
- 2
- lines
- 12
tagged: snowflake parsed as: spark The benchmark ignores the engine header.
Original
SELECT
f.customer_id,
f.order_date,
m.market_name,
p.product_name,
f.amount_usd
FROM gold.fct_orders f
JOIN gold.dim_market m
ON f.market_id = m.market_id
JOIN gold.dim_product p
ON f.product_id = p.product_id
WHERE f.order_date >= '2026-01-01'; Analyzer findings · real output
-
info
consider_broadcastJoin detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
5 rules didn't fire
- select_star
- cross_join
- missing_partition_predicate
- correlated_subquery
- many_ctes
Ground truth · keyword matches
-
"broadcast"in findings -
"dim_market"query text only -
"dim_product"query text only
benchmark score 0.33 (1/3 keywords in findings)
Reference rewrite
Broadcast both small dimensions (Spark form)
On Spark, hint dim_market (~5 rows) and dim_product for broadcast so the large fact table never shuffles.
Line diff, original to rewrite
SELECTSELECT /*+ BROADCAST(m, p) */ f.customer_id, f.order_date, m.market_name, p.product_name, f.amount_usdFROM gold.fct_orders fJOIN gold.dim_market m ON f.market_id = m.market_idJOIN gold.dim_product p ON f.product_id = p.product_idWHERE f.order_date >= '2026-01-01';
- Parses (spark) yes
- Analyzer findings 1 → 0
- Ground-truth keywords in SQL 3/3
Assumptions
- This query is tagged Snowflake, which has no join hints: there the planner broadcasts small build sides on its own once statistics exist, so the remaining levers are clustering and search optimization, not SQL.
- The benchmark parses this file as Spark because it ignores the engine header — the rewrite follows the parser.
What Claude would receive for this query client._build_user_message()
## Dialect
spark
## SQL
```sql
-- engine: snowflake
-- category: broadcast_join
-- Three-table join where dim_market is small (~5 rows) but is being
-- shuffled because the planner does not see size statistics. The fix is
-- engine-specific: a broadcast hint in Spark, or a result-set cache plus
-- search-optimization in Snowflake.
SELECT
f.customer_id,
f.order_date,
m.market_name,
p.product_name,
f.amount_usd
FROM gold.fct_orders f
JOIN gold.dim_market m
ON f.market_id = m.market_id
JOIN gold.dim_product p
ON f.product_id = p.product_id
WHERE f.order_date >= '2026-01-01';
```
## Heuristic findings
- (info) consider_broadcast: Join detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`. Benchmark
What the score does and doesn't measure
The dry-run benchmark scores keyword overlap with ground truth and whether any finding fired. Both charts below come straight from the analyzer's output over the corpus, so the score's blind spots are visible rather than footnoted.
Ground-truth keywords: earned by findings vs. already in the query
Each bar is one corpus query; segments count its expected keywords.
| Query | In findings | Query text only | Missed |
|---|---|---|---|
| 01 join optimization | 2 | 0 | 0 |
| 02 aggregation rewrite | 1 | 1 | 1 |
| 03 cte flattening | 0 | 0 | 3 |
| 04 partition pruning | 0 | 2 | 1 |
| 05 broadcast join | 1 | 2 | 0 |
Which heuristic fires on which query, from analyze() run exactly as the benchmark runs it.
| Rule | 01 Join optimization | 02 Aggregation rewrite | 03 CTE flattening | 04 Partition pruning | 05 Broadcast join | Fires |
|---|---|---|---|---|---|---|
warn select_star | · | · | · | · | 1 | |
high cross_join | · | · | · | · | · | never |
high missing_partition_predicate | · | · | · | · | · | never |
info consider_broadcast | · | · | 3 | |||
warn correlated_subquery | · | · | · | · | 1 | |
info many_ctes | · | · | · | · | 1 |
Takeaway cross_join and missing_partition_predicate never fire here — the corpus needs a cross-join case, and the benchmark needs to pass partition columns.
Evaluation status · not measured
- Built · not run
Claude rewrite quality
--no-dry-runscores Claude's rewrites with the same scorer, but it needs an API key and no live run is recorded yet. - Needs an engine
EXPLAIN cost delta
--explain spark|snowflakerecords estimated bytes scanned before and after; it needs an engine holding the corpus tables. - Planned
Human acceptance
Reviewer accept/reject with rationale per suggestion, as the corpus grows.
Architecture
What runs where
Each lane is a path through the system, colour-coded by status. Every node names the file that implements it — click through to the source.
Analyze
Measuredsql-optimizer analyze --dry-run — no API key needed
-
Query file
Spark SQL or Snowflake
queries/ — corpus/queries/ (opens in new tab) -
sqlglot parse
dialect-aware AST
analyzer.py — src/sql_optimizer/analyzer.py (opens in new tab) -
6 heuristic rules
select *, cross join, partition, broadcast, correlated, CTEs
analyzer.py — src/sql_optimizer/analyzer.py (opens in new tab) -
Findings
rule · severity · message
Suggest
Implementedneeds ANTHROPIC_API_KEY — benchmark --no-dry-run scores it; no live run recorded
-
SQL + findings
structured user message
client.py — src/sql_optimizer/client.py (opens in new tab) -
Optimizer prompt
versioned in the repo
optimizer_prompt.md — src/sql_optimizer/prompts/optimizer_prompt.md (opens in new tab) -
Claude
Messages API, retries on 429/5xx
client.py — src/sql_optimizer/client.py (opens in new tab) -
Rewrite + reasoning
JSON: rewrite · reasoning · confidence
Benchmark
Measuredmake benchmark — dry run over the corpus
-
5-query corpus
one per category
queries/ — corpus/queries/ (opens in new tab) -
Ground truth
expected keywords + cost direction
ground_truth.yaml — corpus/ground_truth.yaml (opens in new tab) -
Scorer
keyword overlap · findings hit
benchmark.py — src/sql_optimizer/benchmark.py (opens in new tab)
Verify
Needs infrabenchmark --explain spark|snowflake — needs an engine holding the corpus tables
-
EXPLAIN original
Spark EXPLAIN COST · Snowflake EXPLAIN USING JSON
explain.py — src/sql_optimizer/explain.py (opens in new tab) -
EXPLAIN rewrite
same engine, same statistics
explain.py — src/sql_optimizer/explain.py (opens in new tab) -
Cost delta
estimated bytes scanned, before → after
benchmark.py — src/sql_optimizer/benchmark.py (opens in new tab)
Engineering narrative
Problem, judgment calls, and results
Problem
There is a real gap between “a query that runs” and “a query a senior would ship”: knowing when to broadcast, prune partitions, flatten repeated scans, or replace correlated subqueries. This tool parses Spark SQL and Snowflake queries with sqlglot, runs a small set of heuristic rules over the AST, and sends the SQL plus structured findings to Claude with a versioned optimizer prompt. Without an API key it runs in a heuristics-only dry-run mode, which is what the published benchmark measures.
Judgment calls
Heuristics + LLM, not LLM only. Sent raw SQL, a model spends its budget re-deriving facts a parser already knows: which columns are projected, which joins lack hints, whether a subquery is correlated. A sqlglot pass extracts those cheaply and ships them as structured findings, leaving the model to decide what to do about them.
EXPLAIN is a tiebreaker, not ground truth. benchmark --explain spark|snowflake
explains the original and the rewritten query and records the engine’s
estimated bytes scanned before and after. Those estimates reflect the
planner’s statistics, so the runner refuses Spark’s 8.0 EiB “unknown”
default and leaves a side blank when the engine cannot estimate it. It also
has blind spots: on a local Spark session a broadcast hint or an explicit
column list leaves the estimate unchanged. No EXPLAIN run is recorded yet,
so the site shows no cost numbers.
Prompt sensitivity is a real risk. Small prompt edits change suggestion
quality, so the prompt lives in version control
(prompts/optimizer_prompt.md) next to the code that sends it. Regression
tests that pin model output against the corpus are the next step.
A corpus designed to grow. Five categories, one fully specified query
each, with expected keywords and cost direction in corpus/ground_truth.yaml.
Adding a case is one .sql file plus one ground-truth entry.
Measured results
make benchmark (dry run) finds at least one issue in
4 / 5 queries and averages 0.33
keyword overlap against ground truth, with the analyzer taking
0.9 ms per query in process. The score counts only what the
findings say, never the query text, so partition_pruning, which gets no finding, scores
0.00. The partition rule never fires
in the benchmark because it needs partition columns passed in; with
--partition-columns ingest_date it flags query 04 at high severity. Two of six
rules (cross_join and missing_partition_predicate) are never
exercised by the corpus — the obvious next corpus additions.
Honest limitations
benchmark --no-dry-runasks Claude for every rewrite, but no live run is recorded, so model rewrite quality is still unmeasured.- Claude can hallucinate plausible column or table names that are not in the schema.
- The benchmark ignores each query’s
-- engine:header, so Snowflake queries are parsed as Spark. - EXPLAIN cost deltas are implemented but not run here (they need an engine holding the corpus tables); human acceptance rate is planned.
Stack
What it uses, and why
- Python 3.11
- CLI runtime; typed dataclasses for findings and results.
- sqlglot
- Dialect-aware SQL parser — the heuristics walk its AST instead of regexes.
- Typer + Rich
- Ergonomic CLI with readable findings tables.
- Anthropic SDK
- Claude Messages API with retry/backoff on rate limits and 5xx.
- PyYAML
- Ground truth for the benchmark lives in reviewable YAML.
- pytest
- 45 tests across analyzer, benchmark, CLI, client and EXPLAIN (API and engines mocked).