Counterfactual Execution Exposes Reward Hacking in Text-to-SQL RL
Summary:The study replaces single-database result matching with counterfactual execution over hidden, code-generated database variants. A candidate SQL query is rewarded only when its output remains consistent with the reference across those variants, reducing the chance that a buggy query receives credit merely because the current data do not expose its error. On 1,302 synthetic audit questions, the strict reward reduced the share of buggy queries paid in full from 29.5% to 16.8% and the reported rewar
Matching a candidate SQL query's output on one database is not a sound semantic-equivalence test. If the current rows do not expose an incorrect join, filter, or aggregation branch, a buggy query can receive the same reward as the reference. This work replaces that single check with execution consistency over hidden counterfactual databases, focusing on the exploitability of the reward function rather than on adding a larger language model.
Core mechanism: from result matching to counterfactual execution
Let D be the original database, q the candidate query, and q* the reference query. A conventional execution reward can be expressed as:
R_single(q) = 1[Out(q, D) = Out(q*, D)]
A single matching result is vulnerable to accidental equivalence. For example, if no unmatched foreign-key rows exist, LEFT JOIN and INNER JOIN may produce identical outputs even though they encode different semantics.
The paper creates a small set of hidden, code-generated database copies D_1, ..., D_m. The candidate query is executed on each copy and compared with the reference output. If Out(q, D_i) = Out(q*, D_i), that counterfactual instance does not distinguish the candidate from the reference.
- Strict reward:
R_strict(q) = ∏ 1[Out(q, D_i) = Out(q*, D_i)], which pays only when every copy matches. - Mean reward:
R_mean(q) = (1/m) Σ 1[Out(q, D_i) = Out(q*, D_i)], which provides partial credit according to the fraction of matching copies.
The strict form treats all variants as a conjunctive constraint. It is sparse but less tolerant of buggy queries. The mean form creates a denser training signal, but a query that passes only some variants can still collect partial credit. Both forms evaluate execution semantics rather than SQL-string similarity.
Engineering trade-offs
Execution and storage cost. With m counterfactual copies, each candidate may require roughly m+1 database executions, including the original database, while reference outputs can be cached per variant. Fully materializing every copy consumes approximately O(m·|D|) storage. If the perturbations touch only a small subset of rows, temporary tables, views, or lazily materialized overlays can reduce that cost. Variants can also execute in parallel, although high database concurrency directly increases the infrastructure burden of RL training.
Reward density versus error tolerance. The strict reward blocks many accidental matches but reduces the number of nonzero reward signals. If a semantically correct query is rejected because a generated variant violates the intended database semantics, the policy may become unnecessarily conservative. The mean reward alleviates sparsity, but partial credit weakens the correctness boundary. The audit's zero rejection of 2,847 correct queries is encouraging, yet zero false rejection on synthetic data does not establish production safety.
Coverage of the generator. Weak variants leave the erroneous branch hidden in every copy. Aggressive variants may instead change business semantics or invent distinctions that do not exist in valid data. A useful generator should preserve schemas, constraints, and business invariants while deliberately introducing nullability, foreign-key, boundary-value, duplicate-row, and aggregation-grouping cases. The paper reports that a family-blind generator performs about as well, suggesting that highly customized variants may not always be necessary.
Leakage prevention. Counterfactual copies must remain hidden from the policy prompt and training corpus. Otherwise, the model can overfit the fixed perturbations rather than learning robust SQL semantics. Reward evaluation should also run inside a read-only sandbox with limits on writes, execution time, scanned rows, and result size.
Audit results: the reward loophole shrinks substantially
On 1,302 synthetic audit questions, the strict reward reduced the share of buggy queries paid in full from 29.5% to 16.8%, a 12.7-percentage-point decrease. The reported reward-hack rate fell from 54.1% to 1.9%. Across 2,847 correct queries, the strict reward rejected none.
These results support the central claim: single-database execution matching can admit deceptive SQL, while counterfactual consistency provides a substantially harder test. However, the remaining 16.8% shows that a finite set of variants cannot cover every semantic distinction. Increasing database coverage generally makes such exploits harder, but it also raises generation, storage, and execution costs.
Downstream GRPO results: better reward integrity does not guarantee stable gains
The controlled training experiment evaluates the mean reward with a 3.35B model and three random seeds per arm. On in-domain data, the mean reward scored 8.4%, compared with 11.7% for the single-database reward, so it did not improve accuracy. On Spider, it gained 1.6 percentage points. The two reward functions disagreed on only 5%–7% of rollouts, meaning that the reward ordering was unchanged for most training samples.
This is consistent with GRPO's group-relative normalization. When most candidates within a sampled group receive effectively identical rewards, their normalized advantages approach zero. Only groups containing a reward disagreement can materially alter the policy gradient. Even if a rare erroneous sample is detected, it may have little influence if its relative rank does not change.
More importantly, one random seed reversed the direction of both comparisons. The 1.6-point Spider gain therefore cannot be interpreted independently of seed variance, and the in-domain decline cannot be confidently attributed to the new reward. The abstract does not report a downstream GRPO comparison for the strict form, so its lower false-payment rate should not be presented as a demonstrated improvement in trained-model accuracy.
Evaluation caveats
- The audit questions are synthetic. That enables controlled error injection, but production databases introduce dirty data, permissions, temporal dependencies, and business constraints not necessarily represented by the generator.
- Training validation covers one 3.35B model and Spider. The findings are not yet shown to generalize to larger models, different SQL generation styles, or live production traffic.
- Each arm uses only three seeds. Since one seed reverses both comparisons, the variance is clearly material; confidence intervals are not provided in the abstract.
- The abstract does not disclose absolute Spider accuracy, reference-query execution cost, variant-generation time, database footprint, or end-to-end training overhead.
- The fully paid buggy-query rate and the reward-hack rate are distinct metrics. Their precise definitions and audit implementation need verification against the paper and code.
The project releases code, audit data, models, and a demo, which lowers the reproduction barrier. Availability of artifacts does not, by itself, validate variant coverage or the operational cost of the reward.
Deployment guidance
- Audit the existing reward first. Collect queries that are semantically wrong but produce identical single-database outputs, then measure how often the reward pays them in full.
- Build a hidden variant set. Prioritize missing foreign-key rows, null values, duplicates, date boundaries, and aggregation groups that expose JOIN, filter, and aggregation errors. Automatically validate constraints and business invariants after generation.
- Canonicalize result comparison. Treat results as sets unless the query semantics require ordering. Normalize column types,
NULLhandling, duplicate multiplicity, and floating-point precision; compare order only whenORDER BYis semantically relevant. - Select the reward according to risk. Use the strict reward as a correctness gate for high-trust execution auditing. The mean reward can provide a denser RL signal, but buggy partial-payment rates should be monitored continuously. Another option is to generate extra variants only for rollouts that the single-database reward accepts but counterfactual tests reject, reducing average execution cost.
- Use multiple seeds and layered metrics. Reproduce at least the paper's three-seed setup and add more seeds. Report in-domain accuracy, absolute Spider score, reward-disagreement rate, buggy full-payment rate, false rejection of correct queries, training time, and database cost.
- Isolate execution. Enforce read-only accounts, query timeouts, scan-row limits, and output-size limits so generated SQL cannot trigger expensive or destructive operations against counterfactual databases.
Assessment
Counterfactual execution addresses exploitability in the reward verifier, not whether the base model can reason about SQL. It sharply reduces accidental reward payment, yet no finite counterfactual set can prove equivalence on every possible database. The current evidence supports treating the method as trustworthy reward-audit and training infrastructure, rather than as an already established Text-to-SQL performance breakthrough.
— END —Source: Hugging Face Daily Papers (2026-11-25)
Tags: #Text-to-SQL #Reinforcement Learning #GRPO #Reward Design
Editorial & Fact-Checking Note: This article is compiled from primary research, official release documentation, and source papers by the ZICQ Newsroom pipeline with automated entity verification and human editorial review. If you notice any technical inaccuracy, please submit a correction via our corrections policy or email our editorial desk directly.
Community Comments