DiagSQL: A Diagnostic Validator for Text-to-SQL with Reward Allocation and Co-occurrence Shaping

Weibin Liao, Bowen Cao, Dong Fang, Wai LamNeurIPS 2026

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.

Learning dynamics showing standard sequence-level rewards increasing false positives alongside true positives, whereas token-allocated rewards separate them.

Methods

DiagSQL upgrades the standard SFT-then-GRPO training pipeline with two surgical modifications tailored for structured SQL diagnostics:

Figure 3: The overall framework of DIAGSQL. The upstream SQL generator produces a preliminary SQL query, which is parsed into a formatted JSON output to conduct structural validation. During the training phase, the model is first warmed up using SFT and then further optimized via an improved GRPO that integrates Fine-grained Token-level Reward Allocation (FTRA) and Co-occurrence-aware Reward Shaping (CORS).
  • 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 FROM clause, your JOIN condition 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).
Figure 2: Co-occurrence matrix of error types within the NL2SQL-Bugs [8] dataset. Both axes represent the actual error types identified in the dataset. Cell colors indicate the log2(lift) value between pairs of error types. Grey cells denote pairs that either lack a significant co-occurrence rela- tionship (| log2(lift)| < 1) or have insufficient data to support such a conclusion. The curved lines in the upper-right area visualize these co-occurrence relationships, with line thick- ness corresponding to the relationship strength (log2(lift)). To optimize presentation, rows and columns containing only grey cells have been excluded.
  • 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 beating GPT-4o (76.81% / 33.02%) and DeepSeek-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%—outperforming GPT-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-4o on a few rare or structurally isolated error categories (such as ASC/DESC mix-ups or Logical 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

Abstract

While large language models have significantly advanced Text-to-SQL generation, it remains largely an open-loop paradigm due to the absence of a reliable validator capable of systematically diagnosing generated queries. Training a dedicated diagnostic validator to provide targeted, reflective feedback is crucial for closing this loop. However, employing standard Reinforcement Learning paradigms, particularly Group Relative Policy Optimization (GRPO), reveals fundamental structural misalignments. Through exploratory analysis, we identify a critical limitation of standard GRPO in this context: a severe credit assignment failure, where uniform sequence-level rewards inadvertently reinforce hallucinated reasoning alongside correct sub-answers in complex structured outputs. Concurrently, we discover profound structural dependencies among SQL errors, revealing inherent co-occurrence semantics dictating that certain errors frequently appear together. To address the limitation and leverage this insight, we propose DiagSQL, a novel framework that utilizes an improved GRPO algorithm tailored for diagnostic Text-to-SQL validation. DiagSQL introduces Fine-grained Token-level Reward Allocation (FTRA), which parses structured responses to precisely distribute rewards at the token level, effectively isolating and penalizing erroneous reasoning. Furthermore, it incorporates Co-occurrence-aware Reward Shaping (CORS), which leverages our discovered pre-computed error co-occurrence matrix to dynamically adjust optimization objectives, encouraging logical error combinations while penalizing structural violations. Extensive experiments demonstrate that DiagSQL significantly enhances the robustness and accuracy of SQL error diagnosis, providing actionable, high-quality feedback that effectively transforms Text-to-SQL into a closed-loop paradigm.
BibTeX
@inproceedings{liao2026diagsql,
  author = {Weibin Liao and Bowen Cao and Dong Fang and Wai Lam},
  title = {{DiagSQL: A Diagnostic Validator for Text-to-SQL with Reward Allocation and Co-occurrence Shaping}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=5TcCMJta3q},
}
Figure