TL;DR
Translating natural language into database queries (Text-to-SQL) usually operates without a safety net—if an LLM writes a subtly wrong query, nothing catches it. DiagSQL closes this loop by training a lightweight 8B-parameter "diagnostic validator" using a customized reinforcement learning recipe that rewards exact sub-answers and respects the domino-effect nature of SQL bugs. Armed with DiagSQL’s feedback, compact open-weight models can spot complex query bugs and refine SQL better than massive proprietary models like GPT-4o.
What Problem Does This Paper Address?
Large Language Models (LLMs) have gotten remarkably good at writing SQL, yet Text-to-SQL remains an "open-loop" system: generate a query, cross your fingers, and run it. Existing ways to check these queries fall short. Database execution only catches syntax crashes, not semantic misunderstandings (like filtering for the wrong category). Asking a giant LLM to act as a judge is expensive, and asking a generator to "self-correct" without external guidance often makes the query worse.
To build a true closed-loop system, we need a small, dedicated diagnostic validator that outputs structured feedback: whether the query is right, the exact error types, and the reasoning behind each bug.
Today, the standard way to train reasoning models is Group Relative Policy Optimization (GRPO)—a lightweight reinforcement learning (RL) algorithm that scores a group of generated answers and reinforces the above-average ones without needing a separate, memory-heavy "critic" model. However, the authors found that standard GRPO breaks down on structured diagnostics. Because GRPO broadcasts a single score across every token in an answer, a response that gets the overall "wrong" label right—but hallucinates a fake bug alongside a real one—still gets a positive score overall. GRPO inadvertently reinforces the hallucinated reasoning right alongside the truth.
Methods
DiagSQL upgrades the standard SFT-then-GRPO training pipeline with two surgical modifications tailored for structured SQL diagnostics:
- Structured JSON Contract & SFT Warm-up: First, Supervised Fine-Tuning (SFT) teaches the model to strictly output a JSON schema containing a binary label and an array of
{error_type, reasoning}pairs. This gives the RL phase clean, deterministic boundaries to parse. - Fine-grained Token-level Reward Allocation (FTRA): Instead of handing one blended score to the entire output, FTRA parses the JSON into distinct token spans (formatting, overall label, and each individual error-reasoning pair). Each span gets evaluated and rewarded independently. If the model spots one real bug and hallucinates another, the valid span gets positive reinforcement while the hallucinated tokens get zero or negative reward.
- Co-occurrence-aware Reward Shaping (CORS): SQL bugs rarely travel alone; if you forget to include a table in a
FROMclause, yourJOINcondition is almost certainly broken too. Using a pre-computed matrix of how frequently error pairs appear together above random chance, CORS dynamically tweaks the reward—handing out bonuses for catching coupled errors, penalties for missing an obvious accomplice, and steep penalties for predicting structurally incompatible bug combinations.
Datasets
- Training Corpus (Synthesized from OmniSQL): 2,000 triples of
(question, buggy SQL, diagnostic label)created by applying grammatical mutations and schema perturbations to OmniSQL queries, aligned to real-world error distributions. - NL2SQL-Bugs: An in-domain benchmark featuring fine-grained, human-annotated error labels reflecting real LLM failure modes; used to compute the co-occurrence matrix and test diagnostic accuracy.
- BIRD & Spider: Standard, out-of-domain Text-to-SQL benchmarks used to test end-to-end SQL refinement accuracy.
Key Insights and Ideas
- Sequence-level RL breeds stealth hallucinations: In multi-part reasoning tasks, grading on a curve at the sequence level lets false positives "free-ride" on true positives. Token-level span attribution completely flips this dynamic, driving false positives down while true positives climb.
- SQL syntax creates an error "social network": Multi-label classification usually treats labels as independent, but strict SQL grammar forces errors into predictable cliques (e.g., Table Missing and Join Condition Mismatch).
- Structural shapes matter more than exact frequencies: Even when the authors stripped exact statistical probabilities out of their co-occurrence matrix (discretizing it to prevent in-domain data leakage, denoted as $\text{DiagSQL}^*$), the model still outperformed proprietary giants—proving it learned the underlying logic of SQL syntax rather than memorizing dataset quirks.
Key Results
Built on compact 8B backbones (Llama3.1-8B and Qwen3-8B), DiagSQL punches well above its weight class:
- Error Diagnosis (NL2SQL-Bugs): DiagSQL (
Llama3.1-8B) hits 88.70% on coarse semantic error detection and 41.01% on fine-grained error typing, decisively beatingGPT-4o(76.81% / 33.02%) andDeepSeek-V3(75.02% / 28.10%). - End-to-End SQL Refinement: Using a single pass of validator feedback to fix
GPT-4o's initial SQL queries on the challenging BIRD benchmark, DiagSQL (Qwen3-8B) boosts execution accuracy from 55.87% to 68.32%—outperformingGPT-4o-powered ErrorLLM (66.23%), whereas naive self-correction actually hurts accuracy (dropping to 55.02%). - Generator-Agnostic Stability: Even when paired with a specialized, high-performing generator (
OpenSearch-SQL), DiagSQL improves BIRD accuracy to 72.62%, whereas several existing repair agents degrade the strong baseline with unnecessary edits.
Limitations and Future Work
- Isolated & Rare Bugs: DiagSQL trails giant models like
GPT-4oon a few rare or structurally isolated error categories (such asASC/DESCmix-ups orLogical Operator Mismatches). Because these bugs don't reliably co-occur with other errors, CORS provides little signal, leaving larger models with a raw pattern-matching advantage. - Future Directions: The authors highlight that combining fine-grained token credit allocation with domain-specific structural priors is a general blueprint—opening the door to better RL alignment across other complex, structured reasoning tasks beyond SQL.
Summary updated