Manuscript Offprint
arXiv:2610.41472Post-SQLFix: Property-Guided Repair of LLM-Generated SQL with Runtime Verification
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Large Language Models (LLMs) for Text-to-SQL frequently generate queries with syntax errors, invalid identifier references, or violations of SQL scoping and typing rules. Repairing these errors is a program correctness problem, yet existing approaches rely on Execution Feedback (EF), whose symptom-level, dialect-specific error messages force the LLM to speculate on root causes. We identify an Arbitration Paradox in this paradigm: the system relies on unverified models both to propose repairs and to make the final judgment on whether those repairs satisfy the required properties. We resolve this paradox by reformulating Text-to-SQL repair as property-guided program repair. Our framework, Post-SQLFix, canonicalizes SQL into a dialect-aware Canonical Query Structure (CQS) and validates it through a hierarchical static analyzer with three stratified property layers (Syntactic, Context-Free Structural, Context-Sensitive Semantic). The analyzer produces precise, schema-aware violation diagnostics to guide the LLM's repair proposals. A Verify-Before-Apply Temporal Monitor then accepts only repairs that reduce the violation count, do not reintroduce resolved violations, and satisfy the operator contracts. These runtime invariants are bounded by the declared rule family and operator contracts, while a finite retry budget ensures halting. On three established benchmarks (BIRD, Spider, Mini-Dev) spanning over 3,000 evaluation instances, three SQL dialects (SQLite, MySQL, PostgreSQL), and six model configurations, Post-SQLFix resolves 77.8% of the execution errors that EF leaves unrepaired, while requiring less than half as many repair iterations and 30% fewer tokens. Crucially, accepted transitions under the monitor introduce no statically detectable structural regressions in our evaluation, translating checked repair fidelity into absolute accuracy improvements of up to +11.6 percentage points.
1 Introduction
Large language models (LLMs) can translate natural-language questions into executable SQL [17, 49, 53], yet the resulting queries frequently contain syntactic flaws, schema-entity type mismatches, and structural scoping errors [49, 53]. Unlike compiled languages, SQL offers no static type-checking compilation step between generation and execution: an ill-formed query is discovered only when the database engine rejects it at runtime or, worse, when it silently returns incorrect results. Repairing these errors is therefore a program correctness problem, orthogonal to the choice of generator: any LLM-based Text-to-SQL pipeline can benefit from a principled post-generation repair layer. Such a layer demands the kind of formal intermediate representations, property specifications, and bounded runtime checks that are central to the programming-languages tradition.
The dominant repair paradigm relies exclusively on the database engine for runtime verification. Execution-Feedback (EF) pipelines [6, 45, 51] run the candidate query, capture the engine's error message, and prompt the LLM to fix it. Although these runtime signals are faithful, they are also symptom-level: messages such as Syntax error near WHERE lack schema- and intent-level context, vary across dialects, and
*These authors contributed equally to this work.
†Corresponding authors: Xiao Cheng and Huan Huo.

Figure 1: Overview of Post-SQLFix. (a) Canonicalization into CQS. (b) Hierarchical Validation & Repair. (c) Deterministic Alignment for empty-result queries.
conflate multiple root causes into a single opaque trace. More fundamentally, EF provides no signal at all for queries that execute successfully yet return wrong results (e.g., scoping violations, invalid aggregations, or empty-result cases). The LLM must still diagnose root causes and synthesize repairs based on the ambiguous evidence from EF, routinely introducing new errors, a well-documented fix-and-regress cycle [15, 19].
This failure is not incidental. It reflects a structural limitation we term the Arbitration Paradox: the system relies on unverified models both to propose repairs and to make the final judgment on whether those repairs satisfy the required properties. Whether the architecture is self-correction [8, 28, 36], retrieval-augmented generation [23, 41, 46], or multi-agent coordination [1, 3, 34, 50], successful execution alone does not verify that a repair preserves previously correct query structure. If the final judgment of repair compliance is delegated to probabilistic LLM reasoning [11], the unverified mechanism proposing the repair also becomes the authority on whether it should be accepted.
The paradox exposes two concrete gaps. First, a diagnostic gap: no deterministic mechanism exists to lift the ambiguous, engine-specific runtime symptoms of EF pipelines into precise, schema-aware property violations; the LLM must map an opaque error trace, or for silently wrong queries no trace at all, to a structured root cause, and does so unreliably. Second, a repair gap: even given an accurate diagnosis, no principled mechanism constrains the repair search space or enforces monotonic progress; existing pipelines check neither that a proposed fix preserves previously correct structure (soundness) nor that the process converges within bounded iterations (termination), and the LLM may freely introduce new violations while patching old ones.
A natural response is to turn to existing SQL static analysis. However, industry linters such as SQLFluff [44] enforce only syntactic formatting rules without schema-aware semantic validation. Prior work on statically analyzing dynamically generated SQL [10] targets human-written application code and does not account for the distinctive error distribution of LLM generators (e.g., hallucinated table names, foreign-key-agnostic joins). Formal equivalence checkers [13] require a ground-truth reference query, which is unavailable at inference time. All of these tools are passive validators: they may detect errors but provide no mechanism to synthesize repairs or to check that a proposed fix does not introduce new violations. To bridge this gap, we draw inspiration from the broader programming languages community, where property-guided program repair [2, 43] has proven highly successful in bypassing ambiguous runtime errors to synthesize checked fixes. The efficacy of these formal methods in traditional software development suggests that a similar paradigm is highly viable for the Text-to-SQL problem.
Our Solution. We resolve the Arbitration Paradox by reformulating Text-to-SQL repair as a property-guided program repair problem [2, 43], replacing speculative execution feedback with verifiable static analysis and formally bounded synthesis. Our framework, Post-SQLFix, is a generator-agnostic post-processing layer: it takes the SQL output of any existing Text-to-SQL pipeline and strengthens it through formal analysis and repair. The direct comparison target is the EF repair paradigm that such pipelines currently rely on.
To close the repair gap, we formalize the repair process as a state-transition system governed by a verify-before-apply temporal monitor. For each detected violation, the monitor first computes a bounded candidate subspace from the schema and dialect configuration, constraining the LLM to propose patches within that subspace. A candidate transition is accepted only if the violation set strictly decreases; otherwise it is rejected and the LLM is re-prompted. This monotonicity invariant directly checks bounded soundness (no previously resolved violation recurs) and bounded halting (the loop terminates under the finite retry budget, returning either a zero-violation CQS or the last accepted state).
Figure 1 illustrates the end-to-end pipeline. (a) The raw SQL is parsed into a dialect-aware Abstract Syntax Tree and lifted into a Canonical Query Structure (CQS), a normalized intermediate representation that decouples relational semantics from dialect-specific surface syntax. (b) The hierarchical validation and repair stage combines the static analyzer with a checked repair loop. The analyzer reports violations of the declared rules, closing the diagnostic gap. These violations guide candidate construction, LLM repair proposals, and validation before updating the CQS. (c) Queries that pass all static layers but return empty results are routed to a data-driven alignment stage that conservatively adjusts filter predicates using empirical evidence from the database. We illustrate this paradox and our workflow through a concrete query repair in § 2. Post-SQLFix is the first framework to provide formally specified runtime invariant checks for LLM-generated SQL repair. Our contributions are summarized as follows:
- A property-guided formulation of Text-to-SQL repair, grounded in a dialect-aware intermediate representation (CQS) and a stratified static analyzer that replaces ambiguous execution feedback with precise, schema-aware property violations (§3).
- A verify-before-apply temporal monitor with runtime-enforced monotonicity: every accepted repair transition strictly decreases the violation count and satisfies the history and preservation checks (Runtime Invariant 1). A finite retry budget also bounds rejected proposals (§4).
- An empirical evaluation across three SQL dialects (SQLite, MySQL, PostgreSQL) and six models showing up to +11.6 percentage points of execution accuracy improvement, over 58% fewer repair iterations, and a 100% interception rate of LLM-induced regressions (§5).
2.1 Problem Setup
Consider a natural-language question posed to a Text-to-SQL system over a relational financial database:
"What is the district ID for the account associated with order 33333?"
An upstream LLM generator [33, 39, 41] produces the following candidate:
SELECT account.district_id FROM order WHERE order_id = 33333;
Two errors lurk in this query, each from a different semantic layer: (1) order is a SQL reserved keyword, so its unescaped use causes a syntax error; (2) account.district_id references a table absent from the FROM clause, a column-resolution failure that only surfaces once the first error is fixed.
Under EF, both errors produce undifferentiated engine messages. The LLM must disentangle them from ambiguous runtime output, and routinely fails: the EF pipeline takes three repair iterations (4,217 tokens), each round fixing one error while reintroducing the other. Post-SQLFix resolves both in a single accepted transition (799 tokens) by decomposing them across distinct analysis layers. We also use this example to show how the Verify-Before-Apply Temporal Monitor catches a silent regression that EF would miss entirely.
2.2 Canonicalization into CQS
After deterministic keyword escaping, Post-SQLFix parses the input into a dialect-aware AST and lifts it into a Canonical Query Structure (CQS), the intermediate representation that all subsequent analysis operates on. The resulting structure records:
The CQS strips away dialect-specific syntax (quoting conventions, reserved-keyword sets, function aliases) while preserving the relational structure that diagnosis needs. Because the representation is dialect-neutral, the analyzer is dialect-parametric: adding a dialect requires a fixed configuration rather than changes to the CQS rules (§3.1).
2.3 Hierarchical Static Analysis
The analyzer validates against the target schema through three stratified property layers (Algorithm 1). Each layer targets a distinct error class; evaluating them in dependency order avoids the tangled, all-at-once error reports that EF produces.
Layer (Syntactic). The parser identifies order as a SQL reserved keyword used as a bare table identifier. The -layer applies a deterministic rewrite: it walks the AST Identifier nodes, checks membership in the dialect's reserved-keyword set, and emits the escaped form order. No LLM is involved; the syntactic violation is resolved before any neural component runs.
Layer (Context-Free Structural). Clause dependencies are well-formed: no aggregation-scoping or cross-clause reference violations arise.
Layer (Context-Sensitive Semantic). The Identifier Binding check iterates over every attribute in . For the projected column account.district_id, it tests whether any table in the current relation scope declares a column district_id:
The predicate fails: no relation in scope has this column. A schema-wide search locates it in table account, which is absent from . The analyzer emits:
That is, records the unresolved column, the layer that flagged it, and the schema table where the column actually resides, giving the repair engine a precise, actionable diagnostic.
Comparison with EF. At this point Post-SQLFix has a complete, layered diagnosis without having executed the query. An EF pipeline would return only the first engine error (the parse failure on order). The column-resolution problem stays hidden until the keyword error is fixed, so the developer (or the LLM) discovers errors one at a time across multiple round trips.
2.4 Constrained Repair Synthesis
Since , the Plan Synthesis Engine (Algorithm 2) is invoked. The strategic mapping dispatches to the add_join operator, triggering a Foreign-Key (FK) Graph Traversal:
-
Connectivity analysis. A graph over , where
accountcomes from the binding diagnostic, is built from the existing join predicates. Breadth-first search finds two disconnected components, and , with no join bridging them. -
FK path search. Depth-first search over the foreign-key graph discovers:
order.account_id account.account_id.
- Candidate generation. The FK path is compiled into a JOIN predicate. Only tables not already in are introduced.
The engine yields a bounded Candidate Subspace:
The deterministic -escape and the FK-derived join candidate for are compiled into a constrained prompt that narrows the LLM's task from open-ended speculation to selection within a verified subspace.
2.5 Verify-Before-Apply Temporal Monitor: Regression Interception
The LLM receives the specification but over-corrects: it inserts the recommended join yet silently drops the WHERE clause:
SELECT account.district_id FROM 'order' JOIN account ON 'order'.account_id = account.account_id;
Under EF, this query runs without error, yet it returns the district ID for every account rather than the one associated with order 33333. EF has no way to detect this regression without an external oracle.
The monitor re-canonicalizes the output into and checks the transition against three structural invariants. The original violation is gone, but Invariant Preservation flags an unauthorized mutation:
The filter set was not authorized by any admissible repair plan, yet the LLM removed it. The transition is rejected, and the LLM is re-prompted with an explicit preservation constraint.
2.6 Convergence: Accepted Repair
On re-prompting, the LLM produces a repair that retains every existing clause:
SELECT account.district_id FROM 'order' JOIN account ON 'order'.account_id = account.account_id WHERE 'order'.order_id = 33333;
The Monitor re-validates: . The reserved keyword is escaped, the join follows the FK-derived path, every column resolves against its schema-declared table, and . The transition is accepted, and the repair completes without any database execution having occurred.
This walkthrough previews three properties formalized in §3–§4:
-
Regression blocking: the Monitor rejected a syntactically valid but structurally mutated candidate, catching a silent regression that EF would have passed through (§4.2).
-
Bounded halting: repair converged in two monitor rounds rather than spiralling through a fix-and-regress cycle; the monotonicity invariant caps accepted transitions at (§4).
-
Dialect-parametricity: the entire analysis ran on the CQS with zero database executions, requiring only the fixed dialect configuration (Remark 1).
3 Formal Framework: Property Specification via Analysis
This section details the formal foundations of Post-SQLFix, designed to address the Arbitration Paradox. We bridge the neuro-symbolic divide by replacing speculative Execution Feedback (EF) with strict, property-guided static analysis. As shown in Figure 1, our pipeline operates by lifting the raw SQL query into a Canonical Query Structure (CQS), upon which a hierarchical static analyzer enforces strict structural and semantic properties.
| Validation Layer | Error Categories |
|---|---|
| Syntactic () | This layer handles precursors to semantic analysis, such as typos |
| Context-Free Structural () | Clause-related: Clause RedundancyFunction-related: Aggregate FunctionsOperator-related: Logical Operator (precedence issues)Other: ASC/DESC, DISTINCT (structural usage) |
| Context-Sensitive Semantic () | Attribute-related: Attribute Mismatch/Missing/RedundancyTable-related: Table Mismatch/Missing/RedundancyJoin-related: Join Condition Mismatch, Join Type MismatchFunction-related: Date/Time, Conversion, Math, String, Conditional (type-/schema dependent usage)Value-related: Data Format Mismatch |
| Empty Result Warnings | Condition-related: Explicit Condition Mismatch/MissingValue-related: Value MismatchSubquery-related: Subquery Mismatch |
Table 1: Hierarchical Taxonomy of SQL Validation Errors
3.1 Abstracting the Domain
To establish a rigorous static analysis environment, we first formalize the target database schema as a 5-tuple context:
where is a set of base relation names and is the set of all fully qualified columns. The sets and capture primary and foreign key integrity constraints, respectively. Finally, maps each column to its strict data type signature. While abstracts the static schema environment, raw SQL instances exhibit significant syntactic variance across execution engines (e.g., SQLite, PostgreSQL). To perform sound property verification, we must decouple the query's core relational semantics from its dialect-specific surface syntax. We parse the input string into a dialect-aware Abstract Syntax Tree (AST), then lift the AST into the Canonical Query Structure (CQS), denoted . Recoverable diagnostics such as reserved-keyword escaping are normalized by deterministic -operators before analysis; if the parser returns rather than a CQS, Algorithm 1 emits an -layer violation and does not pass a malformed query to deeper layers. Only successfully parsed queries proceed to analysis, where ambiguous or unresolved identifiers are handled by canonical binding checks. Despite divergences in lexical symbols or grammatical constructs among SQL dialects, the CQS records the query's relational dependencies in a uniform representation. By normalizing the query representation after parsing, CQS substantially reduces the analytical discrepancies induced by dialect variance, providing a stable foundation for schema-independent structural verification (Layer , Section 3.2) while safely delegating execution-specific constraints to a decoupled dialect configuration (Remark 1).
Definition 1 (Core SQL Fragment ). The CQS extraction targets the SQL fragment with the following abstract query structure:
Here, Expr denotes a SQL expression, including aggregate expressions, and Cond denotes a condition used in WHERE, HAVING, or JOIN ON. The fragment includes non-recursive common table expressions (CTEs) and excludes window constructs.
Definition 2 (Canonical Query Structure). The CQS distills a query's essential operational logic into a 6-tuple intermediate representation:
-
: Projection Specification, a set of projected expressions.
-
: Data Source Specification, a tuple defining source relations (base tables and derived sources), join predicates , and filter conditions .
-
: Aggregation Specification, a tuple defining grouping attributes and HAVING conditions.
-
: Presentation Specification, capturing ordering, cardinality limits, and DISTINCT modifier.
-
: Alias Assignments, mapping relations or attributes for identifier resolution.
-
: Nested Scopes, containing non-recursive CTEs and subqueries. Each scope is defined as an independent CQS , enabling modular, recursive static analysis of arbitrary nesting.
3.2 Property Extraction and Hierarchical Validation
The core of our property-guided repair is the static analyzer, which inspects the CQS against a stratified hierarchy of integrity properties. As summarized in Table 1, we use the Text-to-SQL error classifications [26] to organize the rule family implemented by Post-SQLFix. The analyzer covers the statically checkable structural and schema-dependent subset; value-level failures are handled only when explicit data evidence is available, as in Deterministic Alignment (§4.4). Furthermore, we extend beyond standard empirical categorizations by incorporating rich, fault-tolerant parsing checks to capture early-stage generation anomalies. Structured as a stratified dependency order , the layers are evaluated in a dependency-respecting sequence: requires a parseable CQS from , and requires stabilized scope, alias, and export information from . This operational stratification determines validation and repair priority without imposing an abstract order over arbitrary rules. Foundational violations are therefore addressed before context-sensitive constraints, enabling the analyzer to report all statically detectable violations for a parsed CQS in a single pass. Algorithm 1 formalizes this extraction process. To state validation rules concisely, let denote the set of all operator applications (e.g., aggregations, type casts, arithmetic functions) in .
Syntactic Analysis (Layer ). Let denote the fault-tolerant parser, where signals irrecoverable parse failure. Recoverable token-local diagnostics, such as reserved-keyword escaping, are first normalized by deterministic -operators. A remaining result constitutes an -violation (e.g., severe token malformation). Only queries satisfying proceed to deeper layers.
Context-Free Structural Properties (Layer ). This layer verifies the intrinsic logical integrity of , independent of the external . We formalize Structural Correctness via a predicate that enforces relational dependencies. For ORDER BY, the structural layer only enforces output-scope exposure in dialect/query contexts that require visible ordering keys; ordinary ORDER BY identifier binding is deferred to the context-sensitive identifier-resolution rule .
Context-Sensitive Semantic Properties (Layer ). This layer validates against a unified environment that merges the base schema with each nested scope's exports, where exposes a scope as a named relation (via its alias in ) over the output attributes determined by and , so that supplies both the relation names and the resolvable attributes (see Algorithm 1). The contextual correctness predicate verifies four aspects: (i) every referenced table and column resolves against (identifier binding), (ii) every operator application is type-safe under the dialect (type correctness), (iii) the queried tables form a connected component in the foreign key graph (structural integrity), and (iv) all nested scopes in are recursively valid. The concrete rules are formalized in Table 2.
Remark 1 (Complexity of Dialect Configuration ). In our formalism, is a lightweight, stateless dialect configuration. It defines AST node equivalences (e.g., MySQL's backticks vs. standard quotes), operator signature bounds, and repair templates. Transferring Post-SQLFix to a novel SQL dialect incurs only a constant-size static configuration cost. Formally, is not an independent validation layer in the stratified dependency order . It is a global parameterized context injected into dialect-guarded structural predicates such as , into the -layer verification predicates , and into the [S-Type]
Algorithm 1 Hierarchical Property Analysis ()
Require: SQL string , Schema , Dialect
Ensure: Canonical violation set
1:
2:
3:
4: if then
5:
6: return
7: end if
8:
▷ Layer : Syntactic Well-Formedness
▷ Recoverable keyword/quote normalization
▷ Lift SQL into CQS; return on parse failure
▷ Malformed SQL never proceeds to
▷ Unified environment; Layer , §3.2
▷ Layer : Context-Free Structural Properties
9:
10: if then
11: for all do
12: if then
13:
14:
15: end if
16: end for
17: end if
18: for all do
19:
20:
21: end for
▷ Layer : Context-Sensitive Semantic Properties
▷ Identifier binding
22: for all do
23:
24: if then
25:
26: end if
27: end for
28: for all do
29:
30: if then
31:
32: end if
33: end for
34: if then
35:
36:
37: end if
38: for all do
39:
40: end for
41: return
▷ : internal check on parsed nested scopes
| ID | Rule Definition | Layer |
|---|---|---|
| where .(In an aggregation context, every non-aggregate attribute in SELECT or HAVING must appear in GROUP BY.) | ||
| (ORDER BY attributes must be output-visible only in dialect/query contexts that require visible ordering keys; ordinary ORDER BY identifier binding is handled by .) | ||
| (Aggregate functions must not be nested, e.g., is prohibited.) | ||
| (All referenced tables and columns must resolve against the unified environment , i.e., the schema or an enclosing CTE/subquery scope.) | ||
| (Tables in FROM/JOIN must be connected via foreign keys.) | ||
| (Strict dialect-aware type checking for all operators.) |
Table 2: Representative hierarchical validation rules. unifies aggregation scoping for both SELECT and HAVING clauses. unifies table existence and column binding into a single identifier resolution check. is annotated as its predicates are parameterized by the dialect configuration. Here denotes the guard that is true only when the target dialect/query context requires ORDER BY keys to be output-visible.
candidate subspace construction . The same configuration therefore guides both validation and repair.
A CQS is valid under the declared rule family when both structural () and contextual () predicates hold: . The Violation Set collects all atomic predicates that fail.
3.3 Concrete Validation Rules
We now specify representative rules that concretize the predicates and . These rules are critical: they define the exact boundary of bounded runtime invariants.
Validation Rules. Table 2 formalizes a representative subset of the rules. We use a single guarded predicate for ORDER BY exposure: is true only when the target dialect/query context requires ORDER BY keys to be output-visible, such as DISTINCT or derived-scope export boundaries. The predicate uses the DISTINCT setting recorded in . The structural predicate is defined as the conjunction , and the contextual predicate as . This rule-based formalization is inherently extensible: adding support for a new SQL construct or a novel error category requires only defining a new rule and assigning it to the appropriate layer.
3.4 Verification-Guided Search Space Reduction
Unlike traditional deductive program repair [43], which operates in a deterministic semantic space to synthesize exact patches, our framework addresses the non-deterministic, generative nature of LLM repair. The core contribution of Post-SQLFix is therefore not a strict deductive synthesis engine, but rather a Search Space Reduction mechanism.
When the hierarchical analyzer detects a violation , it does not automatically deduce a single correct fix. Instead, it computes a bounded Candidate Subspace whose elements are drawn from the schema, dialect, and repair-operator contracts. This narrows the LLM's job from open-ended SQL rewriting to proposing a patch inside an explicit, verifier-checked space. The Strategic Mapping formally translates violations into these constrained subspaces:
[S-Bind] Identifier Subspace Construction. When a column is unresolvable (), the analyzer restricts the LLM's vocabulary strictly to the set of valid identifiers existing in the target schema context:
[S-Type] Dialect Repair Subspace. For a dialect violation at op(a), instantiated repair templates supplied by :
Here, REPAIRS returns the finite set of applicable operators instantiated from the configured templates, including type casts and function substitutions. Each operator declares its writable scope and a check that the local edit matches the instantiated template, following Definition 4.
[S-Join] Topology Bridging Subspace. When the FROM clause tables are topologically disconnected (), the analyzer traverses the foreign key graph to emit legal bridging paths:
When a binding diagnostic identifies a schema table missing from the query's sources, we apply the same construction to .
[S-Group/S-Order] Structural Scoping Subspaces. The two clause-scoping repairs induce singleton subspaces: yields for each , and (under ) yields . Their edit boundaries are declared in Table 4; all non-target CQS components are frame-preserved.
[S-LiftAgg] Nested-Aggregate Lifting Subspace. For from , decompose . Let and let be a fresh alias for . Then
These bounding equations formalize our neuro-symbolic integration: the candidate operators are rigorously defined by the static environment , drastically pruning the search space. The LLM's role is thus confined to proposing SQL consistent with these candidate operators; the monitor decides whether the resulting CQS transition is accepted.
Remark 2 (Completeness and Extensibility Bounds). The operations are bounded by the declared property violations and the dialect configuration. Adding a new repair class requires three local extensions: a validation rule, a candidate-subspace constructor, and an operator contract describing its allowed CQS edits. These rules are declarative YAML configurations, allowing quick extensibility to new error classes and dialect idiosyncrasies without altering the monitor itself.
Table 3 provides the concrete instantiation of this search space reduction across the three error categories, showing the full pipeline from error detection (What?), to bounding evidence (Why?), to the constrained prompt specification delivered to the LLM (How?).
4 Operational Semantics of Property-Guided Repair
Given an invalid CQS with , our framework transforms the unstructured string manipulation of EF into a state-transition system. A verify-before-apply temporal monitor governs each LLM-generated patch: it re-canonicalizes the candidate, re-runs the analyzer, and accepts the transition only if the violation count strictly decreases, no previously resolved violation recurs, and an admissible operator plan satisfies the edit-boundary and preservation checks.
| Error Taxonomy & Example (What?) | Evidence & Repair Reasoning (Why?) | Repair Specification (How?) |
|---|---|---|
| SyntacticCondition: Example: SELECT order_id FROM orderError: near "order"; syntax error | Grammar-Driven Hypothesis: Use fault-tolerant parsing to identify token-level errors (spelling, escaping). Apply string similarity (Levenshtein distance) to find the intended SQL keyword from grammar rules. | Apply direct token replacement based on fault-tolerant parsing and string similarity.Example: Replace 'order' with 'order' based on SQLite grammar matching |
| Context-Free StructuralCondition: Example: SELECT DISTINCT account_id FROM account ORDER BY order_id ...Error: no such column: order_id | Intra-Query Structural Analysis: Detect violations of SQL's built-in semantic rules (e.g., aggregation scope, alias conflicts, cross-clause references) by analyzing query structure. Generate specific prompts telling LLM which rule is violated and how to fix. | Prompts: Generate structured prompts detailing the violation and required action.Example: "ORDER-BY EXPOSURE VIOLATION: The target dialect requires an output-visible ORDER BY key under DISTINCT. Use an existing projected expression or alias as the ordering key. Keep the projection unchanged." |
| Context-Sensitive SemanticCondition: Example: SELECT Patient_ID FROM LaboratoryError: no such column: Laboratory.Patient ID | Schema-Grounded Entity Search: Search database schema for valid alternatives to non-existent tables/columns. Use foreign key relationships and string similarity as evidence to provide LLM with ranked replacement suggestions. | Prompts: Generate schema-grounded prompts with ranked replacement suggestions.Example: "COLUMN NOT FOUND: Column 'Patient_ID' does not exist in table 'Laboratory'. Hint: REPLACE 'Laboratory.Patient_ID' WITH 'Laboratory.ID' based on schema" |
Table 3: Repair Paradigms by Formal Error Category
4.1 The Repair Loop
The repair process proceeds iteratively over CQS instances. Algorithm 1 presents the complete analysis from a raw SQL string, including parsing and failure reporting. For an already parsed CQS, ANALYZE() denotes its validation portion, starting with construction of the environment . Repair-loop and nested-scope calls use this portion directly. We omit the iteration index when describing a single repair transition. The system is defined as follows:
-
ANALYZE() , the hierarchical static analyzer (Algorithm 1), where is the space of detectable property violations.
-
, the strategic mapping from violations to candidate subspaces (§ 3.4).
Definition 3 (Canonical Violation Identity). The analyzer emits each violation as a tuple:
where identifies the failed rule (Table 2), is the canonical identity used for equality testing across repair iterations, and is the diagnostic payload used for prompting. For -layer parse violations, is derived from the canonical parser diagnostic because no resolved identifier or expression may exist. For violations, is computed over CQS objects after dialect normalization, alias resolution, and CTE/subquery export resolution; Algorithm 1 implements this normalization with CANRESOLVE. For identifier-binding violations, records the resolved scope, relation, and attribute identity; for type violations, it records the canonical operator signature; for -layer structural violations, it records the canonical clause/expression identity after alias expansion. Two violations are equal iff both and match. This prevents false recurrence or false progress caused only by alias renaming, CTE rewriting, or dialect quoting.
Let denote the resolved-violation history available before iteration , a set of resolved violations compared by their canonical identity (Definition 3). It is initialized as and updated after an accepted transition by
where . Thus contains the violations that were present in an earlier accepted state and have since been removed. When the index is omitted, denotes the current history.
At each iteration, the engine analyzes the current CQS to obtain its violation set and derives the bounded candidate subspace induced by these diagnostics. Treating the LLM as an untrusted repair proposer, the engine compiles the current violations, the candidate operators with their declared edit boundaries, and the resolved-violation history into a constrained specification, from which the proposer returns a candidate CQS . The monitor accepts the transition only when the four runtime checks below hold, consolidated into the three conjuncts of the acceptance condition (10); otherwise it rejects the candidate, leaves unchanged, and re-prompts the proposer within a finite retry budget:
-
Monotonic Progress. The candidate violation count must strictly decrease: .
-
Regression Safety. No previously resolved violation may recur: , where is the history of Eq. (8); because it accumulates over the whole trajectory rather than relative to the initial set, it also blocks reintroducing a violation that was resolved mid-repair.
-
Edit-Boundary Check. The observed CQS delta may touch only fields authorized by some operator plan .
-
Frame Preservation. Every CQS component outside those authorized fields must be preserved, except for explicitly checked rewrites such as CTE lifting that preserve tables and filters by subsumption.
Definition 4 (Operator Edit Boundary). Let be the set of protected CQS components monitored by the repair loop (written to avoid clashing with the schema columns of ). Each instantiated repair operator declares the rule it targets, , the CQS components it may modify, , and an executable local predicate . The local predicate captures operator-specific applicability and preservation obligations, such as projection preservation for BY repair or relational-support preservation for CTE lifting. For node-local repairs, contains the CQS components enclosing the targets fixed at instantiation, while constrains the local rewrites at those targets. At iteration , the current violation set determines the candidate operator subspace ; a repair plan records the operators that can authorize the observed transition. The monitor checks:
where the first conjunct enforces the local predicate declared by each selected operator, and the second conjunct preserves every CQS component outside the selected operators' scopes. Here is equality for ordinary fields and provenance-preserving subsumption for scoped rewrites such as CTE lifting. The witness plan ranges over subsets of the current candidate subspace : a transition is accepted only if some admissible plan drawn from explains the observed edit, so any mutation that no declared operator scope can account for is rejected.
Concretely, for the representative -layer rules in Table 2, edit boundaries are declared directly from the structural rule that fired. For , applies only in an aggregation context and has scope . For , has scope over and aliases. It rewrites to use expressions in or their aliases in , while preserving and the DISTINCT modifier. For , may scope over , , , , and to lower a nested aggregate into a CTE or subquery; the outer and stay frame-preserved, and any rewrite must go through a derived scope that preserves the original relational support needed by the aggregate and must pass full re-analysis.
A transition is accepted only when monitored checks hold; otherwise, the candidate is rejected and the LLM is re-prompted with refined diagnostics. Here, rej stores the diagnostics of failed monitor checks for the next BUILDSPEC call. Algorithm 2 proceeds in three phases and maintains the history : Phase 1 (Symbolic Search Space Reduction): The engine runs and instantiated for every violation , producing the bounded candidate subspace and the edit boundaries declared by its operators. Phase 2 (Constrained Neural Execution): BUILDSPEC compiles the current CQS, violation diagnostics, candidate subspace, operator edit boundaries, , and rej into a constrained specification. The LLM (LLM.GENERATE) proposes a candidate CQS . Phase 3 (Verify-Before-Apply): The Verify-Before-Apply Temporal Monitor re-validates via the static analyzer and accepts the transition only if the acceptance condition (10) holds, including the existence of an admissible operator plan witnessing the edit boundary; on acceptance, the newly resolved violations are added to the resolved-violation history .
4.2 Progress and Preservation
The monitor enforces bounded soundness over accepted transitions. We consolidate the checks from §4.1 into a single acceptance condition. A candidate transition from to is accepted if:
Algorithm 2 Violation-Driven Repair Plan Synthesis with a Verify-Before-Apply Temporal Monitor
Require: Initial CQS , Schema , Dialect , Retry budget
Ensure: Current CQS
1: 2: if then 3: return 4: end if 5: 6: while do 7: 8: 9: for to do 10: 11: 12: 13: 14: 15: if then 16: 17: 18: break 19: else 20: diagnostics of failed monitor checks 21: end if 22: end for 23: if no candidate was accepted then 24: return 25: end if 26: end while 27: return
Definition 5 (Bounded Soundness). Given a rule family and the operator contracts of Definition 4, a repair trace is bounded-sound if every accepted transition , with , satisfies
This property is bounded to violations detectable by and does not imply semantic equivalence to the gold SQL or preservation of user intent.
Runtime Invariant 1 (Monotonic Progress and Preservation). Let be an initial invalid CQS. Every accepted repair transition in the sequence satisfies the acceptance condition (10). Consequently, accepted transitions strictly decrease the violation count, reintroduce no previously resolved violation, respect an edit boundary witnessed by operators in the current candidate subspace, and preserve every non-target CQS component.
Proof. Progress and Regression Safety: By construction of , each candidate subspace enumerates edits drawn from the validated schema and dialect (e.g., for [S-Bind]). However, the LLM may deviate from the constrained specification. The monitor therefore re-diagnoses the entire CQS via Algorithm 1 and accepts only if and . Since records every violation removed by an earlier accepted transition, this rejects candidates that fix one violation while reintroducing a resolved one, even if that violation was absent from the immediately preceding state.
Edit and Frame Preservation: Algorithm 2 accepts the candidate only if there exists such that INVARIANTOK() holds. Its operator-check conjunct rejects violations of the witness operators' local obligations, and its frame conjunct rejects mutations to non-target CQS fields.
The proof of Runtime Invariant 1 relies on two complementary mechanisms: the design-time construction of , which narrows what the LLM should produce, and the temporal monitor in Algorithm 2, which enforces what the system actually accepts.
| Rule | Operator | Scope() | Check() |
|---|---|---|---|
| adds to ; other components preserved. | |||
| rewrites to use expressions in or their aliases in , while preserving and the DISTINCT modifier. | |||
| lifts the inner aggregate into a CTE/subquery as specified in [S-LiftAgg], then uses its exported result in the original outer expression. Preserves the original joins and filters, including those moved into the derived scope, and the visible output schema. Requires full re-analysis. | |||
| components containing target references | rebinds targeted references , with ; query structure unchanged. | ||
| adds an FK-path bridge; preserved. | |||
| components containing the targeted operator node | wraps the offending operand at the target operator in a cast to a target type allowed by ; operand expressions preserved. |
Table 4: Edit boundary contracts for the repair operators. Each operator declares its writable scope SCOPE() and check predicate CHECK() (Def. 4).
4.3 Bounded Halting
By enforcing a strictly decreasing violation count, the monitor bounds the number of accepted transitions, while the finite retry budget bounds the rejected proposals tried at each state; once a state exhausts its budget, the algorithm returns the current CQS without overwriting it. We make this precise with the potential function .
Definition 6 (Bounded Halting). A repair loop has bounded halting under retry budget if, for any initial CQS and any LLM behavior, it terminates after finitely many accepted transitions and finitely many LLM invocations, returning either a zero-violation CQS or the last accepted one. This is a halting property; it does not guarantee successful repair.
Runtime Invariant 2 (Bounded Halting of the Repair Loop). For any initial CQS and any finite , Algorithm 2 performs at most accepted transitions and at most LLM invocations.
Proof. By Runtime Invariant 1, each accepted transition strictly decreases the nonnegative integer , allowing at most accepted transitions. Only states with invoke the LLM, each at most times, giving at most invocations.
4.4 Deterministic Alignment for Empty Results
While the preceding layers form a static analysis hierarchy, some failure modes require data-level evidence. We explicitly isolate Deterministic Alignment as a distinct post-validation step to preserve the static purity of the core analysis.
When a query is valid under the declared static rule family () but returns an empty result, the failure is outside the static rule family. For such cases (Figure 1c), we apply Deterministic Alignment, a conservative post-validation heuristic using data-level evidence. If a filter predicate yields no tuples, the Alignment Operator constructs attribute-substitution candidates while keeping and fixed. A candidate is admissible only if , , and ANALYZE(, . Algorithm 3 then selects the first admissible candidate in canonical scope order, or returns if none exists. Thus Deterministic Alignment is reproducible and regression-blocking, but does not certify agreement with the user's unstated intent.
Algorithm 3 Deterministic Alignment for Empty Results
Require: Valid CQS with , Database , Schema , Dialect Ensure: Aligned CQS or
1:
▷ Step 1: Identify failing filter predicates
2:
▷ Step 2: Classify by correctability
3:
▷ Column mismatch
4: if then
▷ Value boundary: uncorrectable
5: return
▷ Conservative abstention
6: end if
▷ Step 3: Deterministic column alignment
7:
▷ Scope-visible environment
8:
9: for all do
10:
11: if then
12: return
▷ No data-supported column candidate
13: end if
14:
▷ Canonical scope-order selection
15:
▷ Substitute attribute
16: end for
17: if then
18: return
▷ Reject invalid or still-empty alignment
19: end if
20: return
4.5 Case Studies
To concretely illustrate the operation of Post-SQLFix we examine a real-world, highly complex context-sensitive failure from the BIRD SQLite Standard and PostgreSQL Mini-dev benchmark.
4.5.1 Case 1:
Consider the following intermediate LLM generation that structurally parses (passing ) but harbors subtle PostgreSQL-specific dialect incompatibilities and identifier binding errors:
SELECT ROUND( (CAST(COUNT(DISTINCT CASE WHEN y.consumption > 46.73 THEN y.customerid END) AS FLOAT) / CAST(COUNT(DISTINCT y.customerid) AS FLOAT)) * 100, 2) FROM yearmonth y JOIN customers c ON y.customerid = c.customerid;
Under standard execution feedback, this query immediately crashes the PostgreSQL engine, emitting a dense type-casting stack trace (e.g., function round(double precision, integer) does not exist). The error message conflates the type incompatibility with the function signature, providing no indication that a separate identifier binding error also exists. The LLM, prompted only with this opaque trace, must guess both the root cause and whether additional errors are lurking—a combinatorial guessing game that frequently leads to partial fixes and regressions. In Algorithm 1, the query is canonicalized into and validated layer-by-layer. The and -layers pass. The -layer semantic analysis discovers two orthogonal violations that EF conflates into a single crash:
-
Identifier Binding (): . The schema requires precise case sensitivity (CustomerID). A schema-wide search locates the correct identifier and emits a targeted replacement suggestion.
-
Dialect Conformance (): The dialect parameter strictly forbids the ROUND() function from accepting an AS FLOAT double-precision cast, requiring an exact AS NUMERIC parameter signature. This is detected purely from the dialect configuration, without executing the query.
Synthesis with the Temporal Monitor. The Symbolic Engine isolates both violations , bypasses the database entirely, and transitions to Algorithm 2. For , it constructs the candidate subspace ; for , the type-cast subspace . The composite specification is passed to the LLM, which applies the exact AST patches. The temporal monitor confirms that the canonical violation set strictly shrinks to and that non-target CQS fields are preserved. In exactly one accepted transition and with zero database executions, the query reaches zero statically detectable violations. An EF pipeline would require at least two round-trips (one per error discovered sequentially), with no monitor-checked boundary against regressions between rounds.
4.5.2 Case 2:
Consider a SQLite query generated for the question “What is the annual average number of sets released between 2012–2015, and the most common card language?”:
SELECT AVG(sets.id) AS average_sets, MAX(COUNT(set_translations.language)) AS common_language FROM sets JOIN set_translations ON sets.code = set_translations.setCode WHERE sets.releaseDate BETWEEN '2012-01-01' AND '2015-12-31' GROUP BY set_translations.language ORDER BY COUNT(set_translations.language) DESC LIMIT 1;
The -layer passes (no syntax errors). The -layer detects a structural scoping violation ( ): the expression nests one aggregate inside another, which is prohibited in standard SQL. This is a context-free structural error ( , layer ) that requires restructuring the query into subqueries or CTEs. Under EF, the engine reports only misuse of aggregate function —an opaque message that gives no indication of the required restructuring strategy. The LLM must independently infer that the fix involves CTE decomposition, a non-trivial architectural transformation. Moreover, EF cannot foresee the dialect issue that will surface after the restructuring; it discovers errors one at a time through sequential executions.
Edit Boundary Checks. Because requires aggregate lifting, the monitor allows to edit the projection, data-source, aggregation, and nested-scope fields declared in SCOPE( ). This edit boundary permits introducing CTE-derived scopes but still checks that the original tables and filters are subsumed by the inner scope. In the first LLM attempt, the model aggressively removes all original tables without introducing replacements—effectively discarding the query's relational foundation. The temporal monitor rejects: the table set shrank without any corresponding CTE or subquery definitions. On retry (temperature adjusted to 0.3 for more conservative generation), the LLM restructures the query using two well-defined CTEs (yearly_sets, language_counts), each internally referencing the original tables. The monitor accepts the frame check: the original tables are subsumed within CTE definitions, not discarded.
Cross-Layer Convergence. However, this CTE restructure uses YEAR(), a function absent from SQLite's dialect configuration ( ), introducing two new -layer violations. Although the frame-preservation check passed, the temporal monitor detects that the violation count increased ( ), violating monotonic progress. The transition is therefore rejected.
Re-prompted with both the structural restructuring guidance and the dialect constraint (replacing YEAR() with the SQLite-compatible strftime('-%Y', ...)), the LLM produces a CTE restructure that resolves the -scoping violation and avoids introducing any dialect-incompatible functions. The temporal monitor re-validates: . The progress, edit-boundary, and frame checks are satisfied, and the transition is accepted. The repair converges in a single accepted transition spanning both error classes ( and ). An EF pipeline, lacking hierarchical error separation and checked restructuring, would risk oscillation between structural and dialect fixes.
4.5.3 Case 3: The Illusion of Execution Feedback
Consider a SQLite query generated for the question “What is the monthly average number of schools that opened in Alameda County under the jurisdiction of the Elementary School District in 1980?”:
SELECT AVG(COUNT(schools.School)) AS MonthlyAverage FROM schools WHERE schools.DOC = 52 AND schools.OpenDate LIKE '1980%', GROUP BY MONTH(schools.OpenDate);
The -layer passes (no syntax errors). However, the query suffers from two orthogonal violations. The -layer detects a nested aggregation violation (): the expression AVG(COUNT(...)) nests one aggregate inside another, which must be unpacked into a subquery. The -layer (under ) detects a dialect conformance violation: the MONTH() function is unsupported in SQLite and must be rewritten to strtime('/%m', ...).
Under EF, the SQLite engine aborts at the first structural error, emitting only misuse of aggregate function COUNT()—an opaque message that completely masks the dialect issue. In our empirical test with Qwen2.5-Coder, the EF agent fell into a destructive error-handling cycle: to force compilation against the obscure aggregation error, the LLM blindly removed the required outer AVG operation entirely, converging on SELECT COUNT(School) AS MonthlyCount ... GROUP BY strtime(...). This highlights a severe semantic degradation: execution succeeded, but the requested quantity changed from an average of counts to a count.
Single-Pass Convergence. Post-SQLFix extracts both violations simultaneously via a single non-executing static pass. By compiling a bounded candidate subspace , it explicitly guides the LLM to lower the COUNT into a valid subquery while preserving the outer AVG, and concurrently apply the template in that replaces MONTH() with strtime. The Verify-Before-Apply Temporal Monitor rejects candidates that delete the protected AVG aggregation instead of repairing the detected violations. The output is:
SELECT AVG(school_count) AS MonthlyAverage FROM ( SELECT COUNT(schools.School) AS school_count FROM schools WHERE schools.DOC = 52 AND schools.OpenDate LIKE '1980%' GROUP BY strtime('/%m', schools.OpenDate) ) AS subquery
The accepted repair preserves the statically protected aggregation and filter structure while resolving both the -layer nested-aggregate violation and the -layer dialect violation simultaneously. An EF pipeline, discovering errors sequentially through execution, risks destructive semantic regression to achieve superficial compilation success.
5 Experimental Evaluation
The experimental evaluation is designed to evaluate the enforcement of the runtime invariants by our neuro-symbolic monitor and their practical impact on SQL generation. We investigate the empirical behavior of Post-SQLFix by answering four Research Questions (RQs):
- RQ1 (End-to-End Efficacy & Universality): Does the framework universally improve repair execution accuracy across diverse datasets and generation pipelines?
- RQ2 (Baseline Comparisons and Runtime Invariants): How do baselines compare with ours, and how does the monitor behave under monotonic progress, regression safety, and bounded retries?
- RQ3 (Multi-Dialect Portability): Can a fixed symbolic dialect configuration maintain convergence stability across diverse SQL engines (SQLite, MySQL, PostgreSQL) without re-training?
- RQ4 (Component Necessity & Proposer Universality): What are the individual contributions of the framework's components, and does the monitor reliably control SQL repair proposals across diverse foundation model architectures?
5.1 Experimental Setup
Environment and Dataset. All experiments are conducted on an Ubuntu 22.04 server equipped with 32-core Intel 5.0GHz CPUs using BF16 precision. We evaluate our framework across three established benchmarks:
| Method | Inference Model | Zero-shot Setting | Retrieval | Execution Accuracy (%) | |||
|---|---|---|---|---|---|---|---|
| Simple | Moderate | Challenging | All | ||||
| Gen-SQL [41] | Qwen2.5-Coder-7B | × | ✓ | 53.4 | 34.9 | 26.9 | 45.3 |
| Gen-SQL [41] | Qwen2.5-Coder-32B | × | ✓ | 61.6 | 42.2 | 35.9 | 53.3 |
| TA-SQL [39] | Qwen2.5-Coder-7B | ✓ | × | 54.70 | 33.41 | 29.66 | 45.89 |
| TA-SQL [39] | Qwen2.5-Coder-32B | ✓ | × | 66.70 | 49.14 | 46.21 | 59.45 |
| Gen-SQL + Post-SQLFix | Qwen2.5-Coder-7B | × | ✓ | 63.5↑+10.1 | 44.0↑+9.1 | 35.2↑+8.3 | 54.9↑+9.6 |
| Gen-SQL + Post-SQLFix | Qwen2.5-Coder-32B | × | ✓ | 70.8↑+9.2 | 57.1↑+14.9 | 51.7↑+15.8 | 64.9↑+11.6 |
| TA-SQL + Post-SQLFix | Qwen2.5-Coder-7B | ✓ | × | 64.00↑+9.3 | 46.98↑+13.57 | 38.62↑+8.96 | 56.45↑+10.56 |
| TA-SQL + Post-SQLFix | Qwen2.5-Coder-32B | ✓ | × | 70.49↑+3.8 | 56.03↑+6.9 | 50.34↑+4.1 | 64.21↑+4.8 |
Table 5: Execution Accuracy on BIRD Development Dataset (full-pipeline integration).
| Method | Inference Model | Zero-shot Setting | Retrieval | Execution Accuracy (%) | |||
|---|---|---|---|---|---|---|---|
| Simple | Moderate | Challenging | All | ||||
| Gen-SQL [41] | Qwen2.5-Coder-7B | × | ✓ | 82.6 | 57.5 | 50.0 | 72.1 |
| Gen-SQL [41] | Qwen2.5-Coder-32B | × | ✓ | 82.7 | 58.0 | 50.6 | 72.4 |
| TA-SQL [39] | Qwen2.5-Coder-7B | ✓ | × | 78.0 | 59.8 | 34.7 | 65.1 |
| TA-SQL [39] | Qwen2.5-Coder-32B | ✓ | × | 81.3 | 71.8 | 47.1 | 72.1 |
| Gen-SQL + Post-SQLFix | Qwen2.5-Coder-7B | × | ✓ | 83.8↑+1.2 | 60.9↑+3.4 | 52.4↑+2.4 | 73.9↑+1.8 |
| Gen-SQL + Post-SQLFix | Qwen2.5-Coder-32B | × | ✓ | 87.2↑+4.5 | 67.2↑+9.2 | 57.1↑+6.5 | 77.6↑+5.2 |
| TA-SQL + Post-SQLFix | Qwen2.5-Coder-7B | ✓ | × | 79.5↑+1.5 | 65.5↑+5.7 | 47.1↑+12.4 | 69.5↑+4.4 |
| TA-SQL + Post-SQLFix | Qwen2.5-Coder-32B | ✓ | × | 83.2↑+1.9 | 72.4↑+0.6 | 54.7↑+7.6 | 75.0↑+2.9 |
Table 6: Execution Accuracy on Spider Development Dataset (full-pipeline integration).
BIRD [25] (1,534 dev questions across 11 databases covering domains such as education, healthcare, and sports) for real-world schema complexity with simple-to-challenging difficulty levels; Spider [53] (1,034 dev questions across 20 databases spanning 138 domains) for cross-domain diversity with syntactically varied SQL patterns; and BIRD Mini-Dev [25] (500 questions selected from BIRD-Dev across 11 databases), which we deploy on both PostgreSQL and MySQL in addition to the default SQLite to test multi-dialect portability. Together, these benchmarks span three SQL dialects and over 3,000 evaluation instances.
Implementation. The temporal monitor and Hierarchical Analyzer are implemented in roughly 10k lines of code. The Monitor enforces the runtime checks described in § 4.1, with the per-state retry bound set to (Def. 6). We deploy multiple open-weight models and the Qwen2.5-Coder suite (7B and 32B) as our primary LLM and set the default temperature to 1. We emphasize that our objective is not to brute-force the State-of-the-Art (SOTA) execution accuracy through massive scaling or ensembling, but to demonstrate the relative improvements in repair fidelity and bounded halting that a Property-Guided framework brings uniformly to established pipelines (Gen-SQL [41] and TA-SQL [39]). Finally, we evaluate with 6 diverse LLM repair proposers to validate the framework's robustness and universality. Since EF constitutes the post-generation correction mechanism in current Text-to-SQL systems (as discussed in §1 and §7), we adopt
| Metric | Strategy | Generation | Method |
|---|---|---|---|
| Gen-SQL | TA-SQL | ||
| Accuracy (%) | Base | 45.31 | 45.89 |
| Reflection | 47.07 | 46.54 | |
| EF | 49.88 | 51.30 | |
| Our | 53.32 | 52.87 | |
| Left Errors | Base | 340 | 306 |
| Reflection | 291 | 280 | |
| EF | 84 | 72 | |
| Our | 44 | 16 |
Table 7: Performance Comparison of SOTA Methods on BIRD [25] using Qwen2.5-Coder-7B (repair-only integration). Post-SQLFix achieves the highest accuracy and fewest residual errors for both pipelines.
| Metric | Strategy | Generation | Method |
|---|---|---|---|
| Gen-SQL | TA-SQL | ||
| Tokens (avg) | EF | 1,867 | 2,409 |
| Our | 1,506 | 1,679 | |
| Time (s) | EF | 19.53 | 17.68 |
| Our | 10.58 | 8.18 | |
| Rounds (avg) | EF | 2.00 | 2.81 |
| Our | 1.37 | 1.18 |
Table 8: Repair Efficiency on BIRD using Qwen2.5-Coder-7B. Post-SQLFix uses fewer tokens and repair rounds than EF for both pipelines.
| Strategy | Source | Acc. (%) | Accepted | Residual | Empty |
|---|---|---|---|---|---|
| Constrained decoding | Gen-SQL | 50.78 | 204 | 136 | 108 |
| Constrained decoding | TA-SQL | 51.43 | 210 | 96 | 100 |
| EF+Rule-Skill | Gen-SQL | 51.89 | 193 | 147 | 108 |
| EF+Rule-Skill | TA-SQL | 51.30 | 184 | 122 | 94 |
| Post-SQLFix | Gen-SQL | 53.32 | 296 | 44 | 115 |
| Post-SQLFix | TA-SQL | 52.87 | 290 | 16 | 82 |
Table 9: Comparison with constrained decoding and EF+Rule-Skill on BIRD. Post-SQLFix achieves higher accuracy and fewer residual errors than both baselines for both pipelines.
it as our primary baseline throughout. Our framework is independent of the upstream generation strategy. We evaluate full-pipeline integration, which includes schema-linking checks before SQL generation (Table 5), and repair-only integration, which replaces the EF loop on generated SQL while preserving all other pipeline components (Table 7).
5.2 RQ1: End-to-End Efficacy & Universality
Setup. A defining strength of Post-SQLFix is its architectural universality: the analyzer can also check intermediate pipeline outputs against the formalized schema . In the full-pipeline setting, it checks table and column references in SQL generation workflow, in addition to repairing generated SQL. This allows invalid references to be corrected before they propagate into the final query.
The results are in Tables 5 (BIRD) and 6 (Spider), which demonstrate that our framework delivers substantial, consistent accuracy improvements across a wide array of configurations. This improvement holds true regardless of the foundation model scale (7B vs. 32B) or the inference methodology (zero-shot, few-shot, with or without retrieval). Specifically, when augmenting Gen-SQL [41] and TA-SQL [39] on the uniquely challenging BIRD dataset, Post-SQLFix drives accuracy gains of up to +11.6 and +10.56 percentage points, respectively. We observe similarly robust gains on the Spider dataset. This performance gap between baseline execution feedback and our method yields a critical insight: integrated hierarchical validation can outperform terminal correction. By preventing error propagation rather than merely reacting to execution failures, Post-SQLFix translates monitor-checked repair fidelity into measurable execution accuracy gains.
Remark 3 (On the Relationship Between Repair and Accuracy). Execution accuracy requires two independent conditions: (1) the SQL must be structurally executable, and (2) the result must match the gold answer. Our framework targets condition (1): we reduce execution failures from 72 to just 16 (a 77.8% reduction over EF), but these 56 additionally repaired queries are a small fraction of the full benchmark, so the absolute accuracy gain appears moderate. This is by design, an unexecutable query is always wrong, but an executable one is not necessarily correct. Our contribution is repair fidelity: fixing strictly more bugs while preserving monitor-protected structure.
5.3 RQ2: Baseline Comparisons and Runtime Invariants
Post-SQLFix rests on two monitored runtime invariants: bounded soundness with respect to the declared rule family and bounded halting under the finite retry budget. These invariants are narrower than semantic correctness.
Baseline Comparisons. Table 9 compares Post-SQLFix with EF+Rule-Skill and a constrained-decoding baseline using SQL syntax and schema checks, which follow Poesia et al. [35], Scholak et al. [40] works. The constrained-decoding baseline validates complete SQL candidates and accepts them only after successful SQL execution. All methods operate on outputs from unchanged Gen-SQL and TA-SQL pipelines. Post-SQLFix achieves higher accuracy and fewer residual errors for both pipelines.
Canonical Error Resolution. Table 10 tracks the residual errors across all layers, totaling 16 and 7 for the 7B and 32B models, respectively. While basic Execution Feedback (EF) struggles with Context-Sensitive
| Error Type | Reflection | EF | Our-7B | Our-32B |
|---|---|---|---|---|
| Syntactic | 61 | 0 | 0 | 0 |
| Context-Free | 19 | 8 | 4 | 2 |
| Context-Sensitive | 200 | 64 | 12 | 5 |
Table 10: Residual Error Analysis (TA-SQL on BIRD): both model sizes leave fewer context-free and context-sensitive errors than EF.
| Metric | TA-SQL | EF | Align-LLM | Align+Reject | Align-only |
|---|---|---|---|---|---|
| Accuracy (%) | 45.89 | 46.09 | 45.96 | 46.41 | 46.09 |
| Empty Results | 85 | 73 | 57 | 69 | 82 |
| New Violations | – | 6 | 21 | 0 | 0 |
| Time (s) | – | 1500 | 1046 | 1090 | 45 |
Table 11: Soundness when handling empty results. Both EF and Alignment-LLM suffer regressions on BIRD dataset. Align is Deterministic Alignment and Align+Reject is Alignment-LLM+rejection.
() errors—leaving 64 unresolved violations—our property extraction reduces these by 81.25% with the 7B model. As summarized in Table 7, this determinism minimizes the total number of unresolved errors and blocks accepted fix-and-regress transitions. A concrete illustration is given in Case 3 (§4.5), where EF silently corrupts the user's aggregation structure to achieve superficial compilation success—precisely the kind of protected structural degradation that our monitor rejects.
Accepted Regression Blocking. The empty-result study (Table 11) isolates where safety comes from: the unconstrained Alignment-LLM introduces new static violations, but gating the same LLM with monitor-style rejection yields no new violations in this experiment, supporting the use of an acceptance gate rather than relying on the generator alone. The deterministic operator preserves this gate-enforced safety at near-identical accuracy while invoking no LLM; given the latency-accuracy balance we adopt it in the framework rather than the LLM variant, which buys marginal accuracy at an order-of-magnitude latency cost and reintroduces the nondeterminism our analysis eliminates. In the core loop, across 308 repaired queries, the Verify-Before-Apply Temporal Monitor intercepted up to 77 invariant violations and enforced 9 finite-budget stops.
Enforcing Bounded Halting. By strictly pruning cyclic fixes via the monitor, we observe dramatic efficiency gains. As detailed in Table 8, Post-SQLFix reduces average repair rounds by 58.0% for TA-SQL. Convergence is highly concentrated: 98.3% of TA-SQL and 93.79% of Gen-SQL repaired queries converge within the first two rounds; the remaining queries either hit the retry cap or are conservatively abandoned by the Monitor. Across 237 LLM-invoked repair sessions, Post-SQLFix maintained an average consumption of just 1,679 tokens per query (totaling ~398k tokens), reducing average token consumption by approximately 30% over EF. This highlights an architectural advantage: Post-SQLFix localizes token consumption around rule-indexed operator schemas rather than asking the LLM to rediscover root causes from execution traces. Case 3 (§4.5) demonstrates this concretely: while the EF agent requires multiple rounds and ultimately degrades protected aggregation structure to achieve compilation, Post-SQLFix resolves both the and violations in a single unexecuted accepted transition.
5.4 RQ3: Multi-Dialect Portability
Dialect-Aware Convergence Strategy. Despite the amplified complexity of stricter dialects, the dialect-aware configuration effectively adapts the static analyzer's -layer validation rules to handle dialect-specific constraints before neural invocation. As depicted in Figure 2(c-d), the EF baseline struggles profoundly under PostgreSQL's strictness, consuming approximately 2.3M tokens across 239 repair iterations as it attempts to blindly guess type casts and division guards. In contrast, Post-SQLFix achieves a higher successful repair rate (fixing 85.5% of execution errors) while consuming approximately 1.9M tokens. On MySQL, the

Figure 2: Multi-dialect Convergence. (a) Performance across dialects, (b) Remaining errors after repair, (c) Token consumption comparison, (d) Execution time comparison.
| Configuration | Accuracy (%) | Errors Left | Tokens (avg) |
|---|---|---|---|
| Baseline (TA-SQL-7B Generated) | 45.89 | 306 | – |
| Post-SQLFix (Full System) | 52.87 | 16 | 1,679 |
| - w/o Deterministic Alignment | 52.67 | 16 | 1,679 |
| - w/o Verify-Before-Apply Temporal Monitor | 52.00 | 25 | 1,902 |
| - w/o Hierarchical Validation | 52.26 | 39 | 2,426 |
| - w/o Plan Synthesis | 50.24 | 52 | 2,916 |
Table 12: Ablation Study: Component Contributions to Post-SQLFix Performance.
advantage is equally clear: Post-SQLFix resolves 82.4% of execution failures at roughly half the token cost of EF (556k to 1.08M tokens). Crucially, while EF relies on autoregressive generation loops that can spiral when faced with cascading type errors, Post-SQLFix deterministically guards against these violations via static analysis. By preemptively isolating schema mismatches and syntactic incompatibilities at the -layer, our framework truncates the deep cascading error chains that defeat pure execution feedback, maintaining structural convergence across both permissive and strict database configurations.
Dialect-Specific Challenges. Our cross-dialect experiment reveals a deeper challenge rooted in type-system strictness. When executing identical queries generated by the same model, MySQL produces 68 execution exceptions, whereas PostgreSQL yields 117 errors, representing a 72% increase on the same natural-language workload (Figure 2a-b). We analyze three mechanistic drivers for this disparity. First, PostgreSQL enforces strict typing and rejects the implicit coercions that MySQL routinely tolerates. For example, applying the ROUND function to a double precision first argument triggers 70 explicit-cast and type-incompatibility diagnostics in PostgreSQL that are entirely absent in MySQL. Second, the engines differ fundamentally in error handling for undefined operations. While MySQL returns NULL upon division by zero, PostgreSQL terminates execution, contributing to 91 division-related diagnostics compared to only 16 in MySQL. Finally, identifier resolution rules exacerbate schema mismatches. PostgreSQL's automatic case-folding of unquoted identifiers causes LLM-generated CamelCase references to fail static resolution. Cumulatively, these constraints generate a cascading effect where a single query on PostgreSQL triggers complex multi-error failures, demanding significantly more intricate repair trajectories. Case 1 ( ) provides a concrete illustration: a single PostgreSQL query simultaneously triggers both a type-cast violation (ROUND applied to FLOAT instead of NUMERIC) and an identifier binding failure (customerid vs. the schema-required CustomerID), neither of which would surface on MySQL.
5.5 RQ4: Component Necessity and Proposer Universality
Component Necessity. Table 12 isolates the contributions of the core components. Removing the temporal monitor increases residual errors from 16 to 25 and slightly raises token usage (1,679→1,902), confirming its role in preventing regressive patches that would otherwise undo prior fixes. Removing Hierarchical Validation is more damaging: errors climb to 39 and tokens rise to 2,426, as the LLM must compensate for the absent
| Rule | Property | SQLite | LOO Δ |
|---|---|---|---|
| parse/syntax | 21 | ↓ 1.2 | |
| GROUP BY scope | 1 | ↓ 0.2 | |
| ORDER BY scope | 1 | ↓ 0.2 | |
| nested aggregate | 4 | ↓ 0.6 | |
| identifier resolution | 239 | ↓ 5.1 | |
| FK connectivity | 71 | ↓ 2.6 | |
| dialect type | 18 | ↓ 0.5 |
Table 13: Rule triggers and leave-one-rule-out performance drops (LOO Δ) on BIRD (SQLite). Identifier resolution has the largest drop.
| Metric | Qwen2.5-7B | Qwen2.5-32B | Codestral-7B | gpt-oss-120B | Llama-3.1-70B | Mistral-24B |
|---|---|---|---|---|---|---|
| EF Accuracy (%) | 51.30 | 52.00 | 51.37 | 48.04 | 48.37 | 48.24 |
| Our Accuracy (%) | 52.87 | 53.59 | 52.80 | 53.19 | 53.89 | 54.37 |
| Non-compliance | 2 | 1 | 2 | 15 | 15 | 1 |
| Capture Rate | 100% | 100% | 100% | 100% | 100% | 100% |
Table 14: Robustness to Instruction Non-Compliance: across all six proposers, Post-SQLFix improves accuracy over EF and the monitor intercepts all observed non-compliant proposals.
structural decomposition with broader speculation. Removing Plan Synthesis has the most severe impact: errors surge to 52 and tokens to 2,916, confirming that formal constraints actively truncate the LLM's hypothesis space, yielding measurable efficiency gains. Removing Deterministic Alignment costs 0.2 accuracy points (52.87 →52.67) with residual execution errors unchanged (16), matching its isolated behavior in Table 11.
Per-Rule Generality. The rule family is open and extensible (Remark 2), so rather than enumerate it we report how often each representative rule of Table 2 fires. As shown in Table 13, every rule fires on real violations and the family collectively covers all logged errors—detection coverage, not accuracy magnitude, is the contribution we claim. A leave-one-out check confirms each rule contributes, but because one query typically triggers several interacting rules, the accuracy deltas are entangled and should not be summed.
Proposer Universality and Non-Compliance Robustness. The monitor's acceptance checks are independent of the repair proposer's architecture. Table 14 evaluates repair performance and non-compliance interception across six model configurations spanning State Space Models (Codestral), Mixture of Experts (gpt-oss-120B), and dense Transformers of varying scale (Qwen-7B/32B, Llama-70B, Mistral-24B). Every model shows consistent accuracy gains over EF, ranging from +1.43 to +6.13 percentage points. This variance reflects differences in how cleanly each upstream generator produces SQL—models that already generate fewer structural errors leave less room for our repair layer to improve absolute accuracy (see Remark 3). Critically, the Non-compliance row shows that LLMs routinely violate repair specifications (up to 15 out-of-bounds patches for larger models), yet Post-SQLFix intercepts 100% of these observed non-compliant proposals. These results support the monitor's ability to enforce the declared repair contracts across different proposers.
6 Discussion
Scope of Formal Guarantees. Our soundness and bounded halting guarantees are formally bounded by the properties defined in our hierarchy. A query that passes all three layers may still be semantically incorrect (e.g., selecting the wrong aggregation function). Our guarantees prevent resolved violations from recurring and ensure bounded halting; they do not replace oracle-guided semantic verification. The Deterministic Alignment operator (§4.4) is explicitly heuristic: it queries data-level evidence rather than static properties, and may conservatively alter filter predicates to resolve empty results. We isolate it as an optional post-validation step.
Generalization and Dialect Extension. Our experiments cover SQLite, MySQL, and PostgreSQL. Extending to additional dialects requires only adding a constant-size declarative YAML configuration that specifies dialect-specific operator signatures and AST node equivalences (Remark 1), with no retraining or modification of the core verification engine.
Evaluation Methodology. We adopt execution accuracy following standard BIRD and Spider protocols, complemented by residual error counts across all three semantic layers as a direct structural quality measure (see Remark 3).
Residual Limitations. Repairing structurally complex SQL remains an open challenge: SQL's own design deficiencies [42] give rise to entangled constructs that resist modular decomposition. As formalized in Remark 2, our repair completeness is bounded by the rule coverage; constructs outside this boundary are conservatively left untouched rather than speculatively modified. Among the 16 residual BIRD errors, approximately 6–8 require constructs outside (a fundamental scope boundary), 3–4 are within but uncovered by the current declared rules (an extensible rule gap), and 4–6 are LLM instruction non-compliance cases that are intercepted by the monitor rather than accepted as regressions. Beyond rule coverage, the capability of the underlying LLM proposer is a limiting factor: scaling from Qwen2.5-Coder-7B to 32B reduces residual errors from 16 to 7 (see Table 10), indicating that stronger models better follow the constrained repair specifications.
7 Related Work
Program Repair and Static Analysis. Automated program repair [16, 21] spans search-based [20], constraint-based [14, 29, 32, 48], and template-driven [30] approaches, and a growing line of work couples LLMs with static analyzers, compilers, and linters as deterministic feedback channels for generated code, such as integrating analyzer knowledge into code review [18]. Narrowing to SQL, early rule-based repair [38] corrects only limited syntactic errors, while SQL static analysis ranges from verifying generated query strings [10] to proving query equivalence [13] and industrial linting [44]; property-guided repair [43] further checks repair transitions against explicit properties. These approaches, however, treat analyzers as external feedback providers rather than defining a canonical intermediate representation, rule-indexed violation identities, and a bounded monitor over accepted LLM repair transitions. Post-SQLFix is, to our knowledge, the first Text-to-SQL repair framework to combine canonicalization, rule-indexed violation identities, candidate-space repair, and monitor-checked accepted transitions.
Neuro-Symbolic Generation and Constrained Decoding. Constrained decoding methods [31, 35, 40] enforce correctness by restricting the LLM's output at the token level during generation. PICARD [40], for instance, filters infeasible tokens against a partial SQL grammar and can validate table and column names, effectively handling syntactic errors (our -layer) and partial identifier binding. However, these methods cannot address context-sensitive consistency errors (e.g., cross-table join integrity, dialect-specific type constraints) whose root causes are structurally distant from their token-level manifestation. Moreover, constrained decoding requires white-box access to the model's logit stream, tying it to a specific architecture. In contrast, our Verify-Before-Apply Temporal Monitor is fully model-agnostic: the LLM proposes candidate patches as a black box, which our engine deterministically verifies against the extracted properties. This decoupling enables universal deployment across diverse LLM architectures.
Text-to-SQL Generation and Post-Processing. LLM-based Text-to-SQL systems [1, 3, 5, 8, 9, 12, 22, 24, 27, 36, 37, 39–41, 45, 50] have achieved increasingly strong performance on standard benchmarks through advances in schema linking, reasoning, and scaling. Nevertheless, any generation-based approach inevitably produces structural and schema-level errors due to the non-deterministic nature of LLM decoding. The dominant post-processing paradigm relies on Database Execution Feedback (EF) [3, 7, 27, 36, 41, 45, 47, 51], which provides only coarse-grained dynamic symptoms rather than precise root-cause analysis, forcing LLMs to speculate on fixes and often leading to cyclic failures [6, 15]. Multi-agent frameworks [1, 3, 4, 52] and self-correction strategies [1, 28] attempt to mitigate this through iterative refinement, but lack formal convergence guarantees: without explicit property specifications, each correction step may introduce new regressions. Our framework replaces speculative EF with strict property analysis, providing bounded runtime-invariant checks and bounded halting over the repair loop.
8 Conclusion
We presented Post-SQLFix, a neuro-symbolic framework that recasts Text-to-SQL repair as property-guided program repair. By interposing a formal layer—dialect-aware canonicalization, hierarchical static analysis under the stratified dependency order , and a verify-before-apply temporal monitor with bounded runtime invariants—between the neural generator and the accepted output, Post-SQLFix breaks the Arbitration Paradox without sacrificing the flexibility of LLM-based synthesis. Empirically, Post-SQLFix resolves 77.8% of the execution errors that EF leaves unrepaired, reduces repair rounds by over 58%, and accepts no statically detectable structural regressions in our evaluation across three SQL dialects and six LLMs. As a generator-agnostic post-processing layer, it integrates into any upstream pipeline as a drop-in replacement for the EF paradigm. These runtime invariants are bounded by the declared rules and operator edit-boundary checks. Enriching the hierarchy with data-aware properties such as cardinality bounds or functional-dependency constraints is a natural next step.
References
[1] Arian Askari, Christian Poelitz, and Xinye Tang. Magic: Generating self-correction guideline for in-context text-to-sql. Proceedings of the AAAI Conference on Artificial Intelligence, 39(22):23433–23441, Apr. 2025. doi: 10.1609/aaai.v39i22.34511.
[2] Alexandra Bugariu. Automatically Identifying Soundness and Completeness Errors in Program Analysis Tools. PhD thesis, ETH Zurich, 2022.
[3] Jipeng Cen, Jiaxin Liu, Zhixu Li, and Jingjing Wang. Sqlfixagent: Towards semantic-accurate text-to-sql parsing via consistency-enhanced multi-agent collaboration. Proceedings of the AAAI Conference on Artificial Intelligence, 39(1):49–57, Apr. 2025. doi: 10.1609/aaai.v39i1.31979.
[4] Saumya Chaturvedi, Aman Chadha, and Laurent Bindschaedler. Sql-of-thought: Multi-agentic text-to-sql with guided error correction, 2025.
[5] Xiaojun Chen, Tianle Wang, Tianhao Qiu, Jianbin Qin, and Min Yang. Open-sql framework: Enhancing text-to-sql on open-source large language models, 2024.
[6] Xinyun Chen, Maxwell Lin, Nathanael Schärli, and Denny Zhou. Teaching large language models to self-debug. In The Twelfth International Conference on Learning Representations, ICLR 2024, Vienna, Austria, May 7-11, 2024. OpenReview.net, 2024.
[7] Ziru Chen, Shijie Chen, Michael White, Raymond Mooney, Ali Payani, Jayanth Srinivasa, Yu Su, and Huan Sun. Text-to-SQL error correction with language models of code. In Anna Rogers, Jordan Boyd-Graber, and Naoaki Okazaki, editors, Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers), pages 1359–1372, Toronto, Canada, July 2023. Association for Computational Linguistics. doi: 10.18653/v1/2023.acl-short.117.
[8] Dawei Gao, Haibin Wang, Yaliang Li, Xiuyu Sun, Yichen Qian, Bolin Ding, and Jingren Zhou. Text-to-sql empowered by large language models: A benchmark evaluation, 2024.
[9] Yingqi Gao, Yifu Liu, Xiaoxia Li, Xiaorong Shi, Yin Zhu, Yiming Wang, Shiqi Li, Wei Li, Yuntao Hong, Zhiling Luo, Jinyang Gao, Liyu Mou, and Yu Li. A preview of xiyan-sql: A multi-generator ensemble framework for text-to-sql, 2025.
[10] Carl Gould, Zhendong Su, and Premkumar Devanbu. Static checking of dynamically generated queries in database applications. In Proceedings. 26th International Conference on Software Engineering, pages 645–654. IEEE, 2004.
[11] Jiawei Gu, Xuhui Jiang, Zhichao Shi, Hexiang Tan, Xuehao Zhai, Chengjin Xu, Wei Li, Yinghan Shen, Shengjie Ma, Honghao Liu, Saizhuo Wang, Kun Zhang, Yuanzhuo Wang, Wen Gao, Lionel Ni, and Jian Guo. A survey on llm-as-a-judge, 2025.
[12] Jiaqi Guo, Zecheng Zhan, Yan Gao, Yan Xiao, Jian-Guang Lou, Ting Liu, and Dongmei Zhang. Towards complex text-to-SQL in cross-domain database with intermediate representation. In Anna Korhonen, David Traum, and Lluís Márquez, editors, Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 4524–4535, Florence, Italy, July 2019. Association for Computational Linguistics. doi: 10.18653/v1/P19-1444.
[13] Yang He, Pinhan Zhao, Xinyu Wang, and Yuepeng Wang. Verieql: Bounded equivalence verification for complex SQL queries with integrity constraints. Proc. ACM Program. Lang., 8(OOPSLA1):1071–1099, 2024. doi: 10.1145/3649849.
[14] Seongjoon Hong, Junhee Lee, Jeongsoo Lee, and Hakjoo Oh. Saver: scalable, precise, and safe memory-error repair. In Proceedings of the ACM/IEEE 42nd International Conference on Software Engineering, ICSE '20. ACM, 2020.
[15] Jie Huang, Xinyun Chen, Swaroop Mishra, Huaixiu Steven Zheng, Adams Yu, Xinying Song, and Denny Zhou. Large language models cannot self-correct reasoning yet. In B. Kim, Y. Yue, S. Chaudhuri, K. Fragkiadaki, M. Khan, and Y. Sun, editors, International Conference on Learning Representations, volume 2024, pages 32808–32824, 2024.
[16] Kai Huang, Zhengzi Xu, Su Yang, Hongyu Sun, Xuejun Li, Zheng Yan, and Yuqing Zhang. A survey on automated program repair techniques, 2023.
[17] Wonseok Hwang, Jinyeung Yim, Seunghyun Park, and Minjoon Seo. A comprehensive exploration on wikisql with table-aware word contextualization. CoRR, abs/1902.01069, 2019.
[18] Imen Jaoua, Oussama Ben Sghaier, and Houari Sahraoui. Combining large language models with static analyzers for code review generation, 2025.
[19] Ryo Kamoi, Yusen Zhang, Nan Zhang, Jiawei Han, and Rui Zhang. When can llms Actually correct their own mistakes? A critical survey of self-correction of llms. Trans. Assoc. Comput. Linguistics, 12:1417–1440, 2024. doi: 10.1162/TACL_\A_\00713.
[20] Claire Le Goues, Michael Dewey-Vogt, Stephanie Forrest, and Westley Weimer. A systematic study of automated program repair: Fixing 55 out of 105 bugs for $8 each. In 2012 34th International Conference on Software Engineering (ICSE), pages 3–13, 2012. doi: 10.1109/ICSE.2012.6227211.
[21] Claire Le Goues, Michael Pradel, and Abhik Roychoudhury. Automated program repair. Commun. ACM, 62(12):56–65, November 2019. ISSN 0001-0782. doi: 10.1145/3318162.
[22] Boyan Li, Jiayi Zhang, Ju Fan, Yanwei Xu, Chong Chen, Nan Tang, and Yuyu Luo. Alpha-sql: Zero-shot text-to-sql using monte carlo tree search, 2025.
[23] Haoyang Li, Jing Zhang, Cuiping Li, and Hong Chen. RESDSQL: decoupling schema linking and skeleton parsing for text-to-sql. In Brian Williams, Yiling Chen, and Jennifer Neville, editors, Thirty-Seventh AAAI Conference on Artificial Intelligence, AAAI 2023, Thirty-Fifth Conference on Innovative Applications of Artificial Intelligence, IAAI 2023, Thirteenth Symposium on Educational Advances in Artificial Intelligence, EAAI 2023, Washington, DC, USA, February 7-14, 2023, pages 13067–13075. AAAI Press, 2023. doi: 10.1609/AAAI.V37I11.26535.
[24] Jinyang Li, Binyuan Hui, Reynold Cheng, Bowen Qin, Chenhao Ma, Nan Huo, Fei Huang, Wenyu Du, Luo Si, and Yongbin Li. Graphix-t5: Mixing pre-trained transformers with graph-aware layers for text-to-sql parsing, 2023.
[25] Jinyang Li, Binyuan Hui, Ge Qu, Jiaxi Yang, Binhua Li, Bowen Li, Bailin Wang, Bowen Qin, Ruiying Geng, Nan Huo, et al. Can llm already serve as a database interface? a big bench for large-scale database grounded text-to-sqls. Advances in Neural Information Processing Systems, 36, 2024.
[26] Xinyu Liu, Shuyu Shen, Boyan Li, Nan Tang, and Yuyu Luo. Nl2sql-bugs: A benchmark for detecting semantic errors in nl2sql translation, 2025.
[27] Shuai Lyu, Haoran Luo, Ripeng Li, Zhonghong Ou, Jiangfeng Sun, Yang Qin, Xiaoran Shang, Meina Song, and Yifan Zhu. Sql-o1: A self-reward heuristic dynamic search method for text-to-sql, 2025.
[28] Aman Madaan, Niket Tandon, Prakhar Gupta, Skyler Hallinan, Luyu Gao, Sarah Wiegreffe, Uri Alon, Nouha Dziri, Shrimai Prabhumoye, Yiming Yang, et al. Self-refine: Iterative refinement with self-feedback. Advances in Neural Information Processing Systems, 36, 2023.
[29] Sergey Mechtaev, Jooyong Yi, and Abhik Roychoudhury. Angelix: Scalable multiline program patch synthesis via symbolic analysis. In Proceedings of the 38th International Conference on Software Engineering, pages 691–701. ACM, 2016.
[30] Xiangxin Meng, Xu Wang, Hongyu Zhang, Hailong Sun, Xudong Liu, and Chunming Hu. Template-based neural program repair. In 2023 IEEE/ACM 45th International Conference on Software Engineering (ICSE), pages 1456–1468, 2023. doi: 10.1109/ICSE48619.2023.00127.
[31] Niels Mündler, Jingxuan He, Hao Wang, Koushik Sen, Dawn Song, and Martin Vechev. Type-constrained code generation with language models. arXiv preprint arXiv:2504.09246, 2025.
[32] Hoang Duong Thien Nguyen, Dawei Qi, Abhik Roychoudhury, and Satish Chandra. Semfix: Program repair via semantic analysis. In 2013 35th International Conference on Software Engineering (ICSE), pages 772–781, 2013. doi: 10.1109/ICSE.2013.6606623.
[33] OpenAI. Gpt-4 technical report, 2024.
[34] Melissa Z Pan, Mert Cemri, Lakshya A Agrawal, Shuyi Yang, Bhavya Chopra, Rishabh Tiwari, Kurt Keutzer, Aditya Parameswaran, Kannan Ramchandran, Dan Klein, Joseph E. Gonzalez, Matei Zaharia, and Ion Stoica. Why do multiagent systems fail? In ICLR 2025 Workshop on Building Trust in Language Models and Applications, 2025.
[35] Gabriel Poesia, Alex Polozov, Vu Le, Ashish Tiwari, Gustavo Soares, Christopher Meek, and Sumit Gulwani. Synchromesh: Reliable code generation from pre-trained language models. In International Conference on Learning Representations, 2022.
[36] Mohammadreza Pourreza and Davood Rafiei. DIN-SQL: decomposed in-context learning of text-to-sql with self-correction. In Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023, 2023.
[37] Mohammadreza Pourreza, Hailong Li, Ruoxi Sun, Yeounoh Chung, Shayan Talaei, Gaurav Tarlok Kakkar, Yu Gan, Amin Saberi, Fatma Ozcan, and Sercan Ö. Arik. CHASE-SQL: multi-path reasoning and preference optimized candidate selection in text-to-sql. In The Thirteenth International Conference on Learning Representations, ICLR 2025, Singapore, April 24-28, 2025. OpenReview.net, 2025.
[38] Kai Presler-Marshall, Sarah Heckman, and Kathryn T Stolee. Sqlrepair: Identifying and repairing mistakes in student-authored sql queries. arXiv preprint arXiv:2102.05729, 2021.
[39] Ge Qu, Jinyang Li, Bowen Li, Bowen Qin, Nan Huo, Chenhao Ma, and Reynold Cheng. Before generation, align it! A novel and effective strategy for mitigating hallucinations in text-to-sql generation, 2024.
[40] Torsten Scholak, Nathan Schucher, and Dzmitry Bahdanau. PICARD: Parsing incrementally for constrained auto-regressive decoding from language models. In Marie-Francine Moens, Xuanjing Huang, Lucia Specia, and Scott Wen-tau Yih, editors, Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pages 9895–9901, Online and Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics. doi: 10.18653/v1/2021.emnlp-main.779.
[41] Jie Shi, Bo Xu, Jiaqing Liang, Yanghua Xiao, Jia Chen, Chenhao Xie, Peng Wang, and Wei Wang. Gen-SQL: Efficient text-to-SQL by bridging natural language question and database schema with pseudo-schema. In Owen Rambow, Leo Wanner, Marianna Apidianaki, Hend Al-Khalifa, Barbara Di Eugenio, and Steven Schockaert, editors, Proceedings of the 31st International Conference on Computational Linguistics, pages 3794–3807, Abu Dhabi, UAE, January 2025. Association for Computational Linguistics.
[42] Jeff Shute, Shannon Bales, Matthew Brown, Jean-Daniel Browne, Brandon Dolphin, Romit Kudtarkar, Andrey Litvinov, Jingchi Ma, John Morcos, Michael Shen, David Wilhite, Xi Wu, and Lulan Yu. Sql has problems. we can fix them: Pipe syntax in sql. In Proceedings of the VLDB Endowment, volume 17, pages 4051–4063, 2024.
[43] Yahui Song, Xiang Gao, Wenhua Li, Wei-Ngan Chin, and Abhik Roychoudhury. Provenfix: Temporal property-guided program repair. Proc. ACM Softw. Eng., (FSE), 2024.
[44] SQLFluff Contributors. Sqlfluff: The sql linter for humans, 2025.
[45] Ruoxi Sun, Sercan O Arik, Alexandre Muzio, Lesly Miculicich, Satya Kesav Gundabathula, Pengcheng Yin, Hanjun Dai, Hootan Nakhost, Rajarishi Sinha, Zifeng Wang, and Tomas Pfister. SQL-PaLM: Improved Large Language Model Adaptation for Text-to-SQL. Transactions on Machine Learning Research, 2024.
[46] Shayan Talaei, Mohammadreza Pourreza, Yu-Chen Chang, Azalia Mirhoseini, and Amin Saberi. Chess: Contextual harnessing for efficient sql synthesis, 2024.
[47] Stephen Thomas and Laurie Williams. Using automated fix generation to secure sql statements. In Third International Workshop on Software Engineering for Secure Systems (SESS'07: ICSE Workshops 2007), pages 9–9, 2007. doi: 10.1109/SESS.2007.12.
[48] Rijnard van Tonder and Claire Le Goues. Static automated program repair for heap properties. In Proceedings of the 40th International Conference on Software Engineering, ICSE '18. ACM, 2018.
[49] Bailin Wang, Richard Shin, Xiaodong Liu, Oleksandr Polozov, and Matthew Richardson. RAT-SQL: Relation-aware schema encoding and linking for text-to-SQL parsers. In Dan Jurafsky, Joyce Chai, Natalie Schluter, and Joel Tetreault, editors, Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 7567–7578, Online, July 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020.acl-main.677.
[50] Bing Wang, Changyu Ren, Jian Yang, Xinnian Liang, Jiaqi Bai, Linzheng Chai, Zhao Yan, Qian-Wen Zhang, Di Yin, Xing Sun, et al. Mac-sql: A multi-agent collaborative framework for text-to-sql. In Proceedings of the 31st International Conference on Computational Linguistics, pages 540–557, 2025.
[51] Hanchen Xia, Feng Jiang, Naihao Deng, Cunxiang Wang, Guojiang Zhao, Rada Mihalcea, and Yue Zhang. Sql-craft: Text-to-sql through interactive refinement and enhanced reasoning. CoRR, abs/2402.14851, 2024. doi: 10.48550/ARXIV.2402.14851.
[52] Wenxuan Xie, Gaochen Wu, and Bowen Zhou. Mag-sql: Multi-agent generative approach with soft schema linking and iterative sub-sql refinement for text-to-sql, 2024.
[53] Tao Yu, Rui Zhang, Kai Yang, Michihiro Yasunaga, Dongxu Wang, Zifan Li, James Ma, Irene Li, Qingning Yao, Shanelle Roman, Zilin Zhang, and Dragomir Radev. Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-sql task. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, Brussels, Belgium, 2018. Association for Computational Linguistics.
A Repair Prompts and Case Study
This case expands the motivating example in § 2, showing the system and user prompts, SQL candidates, and decisions of the Post-SQLFix.
A.1 Case setup
Query:
What is the district ID for the account associated with order 33333?
The generator produces:
SELECT account.district_id FROM order WHERE order_id = 33333;
The table name order needs escaping, and account.district_id references a table absent from the query's sources. Deterministic keyword escaping first changes order to 'order'. The two LLM rounds below start from this normalized query, with one remaining binding violation.
System prompts
You are an experienced SQLite database expert. Repair SQL using the supplied database schema, error diagnostics, and repair instructions. Follow the provided constraints and return a complete SQL query in SQLite syntax.
Repair boundary in this case
The JOIN repair may add a source table and its join predicate, corresponding to and in the CQS. It must preserve the projected attribute account.district_id and the filter order_id = 33333. Qualifying that filter as 'order'.order_id = 33333 preserves its canonical reference.
A.2 Round 1
The binding diagnostic identifies account as the missing source table. The prompt supplies a concrete JOIN path and states which existing query parts must be preserved.
Representative user message
Database dialect
SQLite
Schema excerpt
account(account_id, district_id) order(order_id, account_id) Foreign key: order.account_id -> account.account_id
Question
What is the district ID for the account associated with order 33333?
Current SQL
SELECT account.district_id
FROM order
WHERE order_id = 33333;
Focused diagnosis
Error type: COLUMN_NOT_FOUND_NEEDS_JOIN Target: account.district_id The column exists in account, but account is not a query source. Required action: ADD_JOIN
Suggested JOIN path
JOIN account ON order.account_id = account.account_id
Repair instructions
- Add account to the query using the suggested JOIN path.
- Use only tables and columns present in the supplied schema.
- Keep account.district_id as the projected attribute.
- Preserve the filter order_id = 33333 and its constant value.
- Do not add unrelated predicates or remove existing query clauses.
- Keep the reserved table name
orderescaped.
Apply the repair and output the complete corrected SQL in a SQL code block.
Candidate from the motivating example
SELECT account.district_id
FROM order
JOIN account
ON order.account_id = account.account_id;
Monitor decision: rejected.
A.3 Round 2
The schema, current SQL, diagnosis, and JOIN path remain available. The new information is the rejection reason and an explicit instruction to retain the filter that the first candidate removed.
Representative user message
Database dialect
SQLite
Schema excerpt
account(account_id, district_id) order(order_id, account_id) Foreign key: order.account_id -> account.account_id
Current SQL -- the rejected candidate was not applied
SELECT account.district_id
FROM order
WHERE order_id = 33333;
Focused diagnosis
Error type: COLUMN_NOT_FOUND_NEEDS_JOIN
Target: account.district_id
Add the missing source table account using this JOIN path:
JOIN account ON order.account_id = account.account_id
Previous verification result
Your last repair was REJECTED because it removed the WHERE clause. Failed check: preservation of the existing filter. The permitted JOIN repair does not authorize removing this condition: order_id = 33333
Instructions for this retry
- Start from the current SQL above and add the suggested JOIN.
- Keep account.district_id in SELECT.
- Keep WHERE order_id = 33333. Do not change 33333.
You may qualify the column as
order.order_id. - Keep the original source table and use only schema-valid identifiers.
- Do not remove clauses or introduce unrelated filters.
- Keep the reserved table name
orderescaped.
Do not repeat the rejected edit. Output the complete corrected SQL in a SQL code block, including the preserved WHERE clause.
Candidate from the motivating example
SELECT account.district_id
FROM order
JOIN account
ON order.account_id = account.account_id
WHERE order.order_id = 33333;
Monitor decision: accepted.
A.4 System prompt templates
The templates below summarize the information supplied to the repair proposer. Angle-bracket placeholders, such as <CURRENT_SQL>, are filled with the current query, schema, diagnostics, or candidate operators. Optional fields are omitted when unavailable. The diagnostic blocks specialize the common request to the active repair operators. The Verify-Before-Apply Temporal Monitor checks the returned candidate before applying it.
System prompts
You are an experienced <SQL_DIALECT> database expert. Repair SQL using the supplied schema, diagnostics, and candidates. Follow the permitted edits and preservation requirements. Use only schema-valid identifiers and <SQL_DIALECT> syntax. Return one complete SQL query in a SQL code block.
P1. Common repair request
This request collects the inputs to BUILDSPEC in Algorithm 2. P2–P7 specialize its diagnostic and repair-instruction fields, P8 adds rejection feedback, and P9 illustrates a request with multiple diagnostics.
Database dialect
<SQL_DIALECT>
Database schema
<TABLES_COLUMNS_TYPES_PRIMARY_keys_AND_FOREIGN_keys>
Question, when available
<NATURAL_LANGUAGE QUESTION>
Current SQL
<CURRENT_SQL>
Diagnostics and admissible repair candidates
<FOCUSED_DIAGNOSTICS_AND OPERATOR_SPECIFIC_INSTRUCTIONS>
Operator edit boundary
<PERMITTED_EDITS_FOR_THE_ACTIVE OPERATORS>
Preservation requirements
<QUERY_COMPONENTS_AND_EXPRESSIONS_TO_PRESERVE>
Resolved-violation history
<PREVIOUSLY_RESOLVED_VIOLATIONS_OR_NONE>
Rejection feedback, when present
<FAILED_MONITOR_CHECKS_AND_REPAIR_GUIDANCE>
Task
Repair the reported violations using the supplied candidates. Respect the edit boundary and preservation requirements. Do not reintroduce a previously resolved violation. Output the complete corrected SQL in a SQL code block.
P2. Identifier binding
This block instantiated the replacement operator when an existing query source provides an admissible replacement for an unresolved column reference. For missing source tables, use P3.
Binding diagnostic
Reference: <INVALID_REFERENCE> Scope: <TARGET_QUERY_SCOPE> Reason: <BINDING_DIAGNOSTIC>
Admissible replacements
<REFERENCES_FROM_CURRENT_SOURCES_OR_SCOPE_EXPORTS>
Required edit
Replace <INVALID_REFERENCE> with <SELECTED_REPLACEMENT>. Apply the replacement within <TARGET_QUERY_SCOPE>. Follow the dialect's identifier naming and quoting requirements.
Preserve
Keep the existing query sources, JOIN predicates, filters, aggregations, ordering, and non-target expressions unchanged. Do not add a table or restructure the query for this replacement. Do not invent a reference outside the supplied candidates.
P3. Missing source table or FK connection
The prompt supplies candidate paths derived from the schema's FK graph. The authorized changes are the source-table and JOIN fields of the affected query scope.
JOIN diagnostic
Scope: <TARGET_QUERY_SCOPE> Missing source or disconnected tables: <REPORTED_TABLES> Affected reference, if any: <UNRESOLVED_REFERENCE> Reason: <JOIN_OR_BINDING_DIAGNOSTIC>
Candidate FK paths
- <FK_JOIN_PATH_1>
- <FK_JOIN_PATH_2_IF_AVAILABLE>
Required edit
Use <SELECTED_FK_JOIN_PATH> to connect the required tables. Add only the source or bridge tables and JOIN conditions authorized by that path, within <TARGET_QUERY_SCOPE>. Use the supplied schema-valid key columns.
Preserve
Keep the projection, filters and their literal values, GROUP BY, HAVING, ORDER BY, and LIMIT unchanged. Retain the original query sources. Do not delete the affected reference to hide the binding error.
P4. Dialect-specific type repair
For the cast operator, the diagnostic identifies the offending operand and the dialect-valid target types. The prompt asks for a local cast rather than replacement of the surrounding computation.
Type diagnostic
Dialect: <SQL_DIALECT> Operator and argument position: <OPERATOR_AND_ARGUMENT_POSITION> Operand: <OFFENDING Operand EXPRESSION> Observed type: <OBSERVED_TYPE> Required signature: <DIALECT_VALID OPERATOR SIGNATURE>
Admissible casts
<ALLOWED_TARGET_TYPES_AND_CAST_CANDIDATES>
Required edit
Apply <SELECTED_CAST> to <OFFENDING Operand EXPRESSION>. Keep the operand expression inside the cast unchanged. Use the cast syntax prescribed for <SQL_DIALECT>.
Preserve
Keep the enclosing computation and non-target arguments. Preserve the query's tables, joins, filters, grouping, and ordering. Do not remove the failing expression or change its aggregate function merely to avoid the reported type error.
P5. GROUP BY scope repair
This block follows the declared add_group operator: it adds missing grouping attributes while preserving the other CQS components.
Grouping diagnostic
Scope: <TARGET_QUERY_SCOPE> Aggregation context: <AGGREGATION_CONTEXT> Ungrouped non-aggregate references: <REPORTED REFERENCES> Current GROUP BY: <CURRENT_GROUPING_ATTRIBUTES>
Admissible additions
<GROUPING_ATTRIBUTES_SELECTED_BY_THE_REPAIR_PLAN>
Required edit
Add <SELECTED_GROUPING_ATTRIBUTES> to GROUP BY. Retain the existing grouping attributes. Restrict this edit to the reported query scope.
Preserve
Keep the SELECT expressions and aggregate functions unchanged. Preserve FROM, JOIN, WHERE, HAVING, ORDER BY, and LIMIT. Do not remove a projected expression or wrap it in an unrelated aggregate to bypass the grouping diagnostic.
P6. ORDER BY scope repair
For contexts requiring ordering expressions to be exposed in the output, this block follows expose_order. Its candidates refer to the existing projection or its aliases, and the projection Π is preserved.
Ordering diagnostic
Dialect and query context: <ORDERING_requirement_CONTEXT> Scope: <TARGET_QUERY SCOPE> Reported ORDER BY expression: <INVALID_ORDERING_expression>
Existing projection and aliases
<CURRENT_PROJECTEDExpressions_AND_ALIASES>
Admissible ordering references
<CANDIDATES_USING_EXISTING_PROJECTEDExpressions_OR_ALIASES>
Required edit
Rewrite <INVALID_ORDERING_expression> using <SELECTED_CANDIDATE>. Use only the ordering and alias edits authorized by the plan.
Preserve
Keep all projected expressions and the visible output schema. Retain the original sort direction and LIMIT. Preserve the query sources, joins, filters, and aggregation. Do not add a SELECT expression or remove DISTINCT to hide the error.
P7. Nested aggregate lifting
This block describes the lift_agg rewrite into a CTE or subquery. Original tables and filters may move into the derived scope, but their relational support must be retained as required by the operator contract.
Nested-aggregate diagnostic
Scope: <TARGET_QUERY SCOPE> Invalid expression: <NESTED_AGGREGATE_expression> Inner aggregate: <INNER_AGGREGATE_TO_LIFT> Outer aggregate: <OUTER_AGGREGATE_TO_RETAIN>
Supplied lifting plan
Derived scope: <CTE_OR_SUBQUERY_NAME> Grouping and exported keys: <GROUPING_AND_EXPORT_KEYS> Exported aggregate alias: <INNER_RESULTAlias> Permitted CQS edits: <AUTHORIZED_FIELDS_AND_REWRITE>
Required edit
Compute <INNER_AGGREGATE_TO_LIFT> in the supplied derived scope. Export its result as <INNER_RESULTAlias>. Use that result in the original outer aggregate.
Preserve
Retain the original tables, joins, and filters in the appropriate scope. Keep their column dependencies and literal values. Preserve the visible output schema and all non-target components. Do not discard the outer aggregate or replace it with the inner one. Use only functions supported by <SQL_DIALECT>.
P8. Retry after monitor rejection
The failed checks are passed back as rej. The current SQL and resolved-violation history stay unchanged after rejection. Only the relevant feedback fields are included in the next request.
Current SQL -- the rejected candidate was not applied
<CURRENT_ACCEPTED_SQL>
Previous verification result
Your last repair was REJECTED. Failed checks: <FAILED_MONITOR_CHECKS> Reason: <CONCRETE_FAILURE_DIAGNOSTICS> Edit that caused rejection: <REJECTED_EDIT_SUMMARY>
Guidance for this retry
Start from the current SQL above. Keep <PROTECTED_CLAUSES_EXPRESSIONS_AND_VALUES>. Do not reintroduce <RESOLVED_VIOLATIONS_IDENTIFIED_IN_FEEDBACK>. Use only <ADMISSIBLE_REPAIR_CANDIDATES>. Stay within <PERMITTED_EDIT_FIELDS>. Correct the reported issue without repeating the rejected edit.
Output one complete corrected SQL query in a SQL code block.
P9. Multiple diagnostics in one request
The common request can contain several diagnostics and compatible candidate operators. The prompt supplies the permitted edits for each target; the monitor checks the resulting candidate as a whole.
Current diagnostics
- <VIOLATION_1_AND_TARGET SCOPE>
- <VIOLATION_2_AND_TARGET SCOPE> <ADDITIONAL_DIAGNOSTICS_IF_INCLUDED>
Admissible repair plan
For diagnostic 1: <OPERATOR_1_AND_CANDIDATES> For diagnostic 2: <OPERATOR_2_AND_CANDIDATES> Permitted combined edits: <COMBINED OPERATOR_EDIT_BOUNDARY>
Task
Repair the reported violations using the supplied candidates. Combine compatible fixes within the permitted edit boundary. Preserve <NON_TARGET_QUERY_COMPONENTS>. Do not reintroduce <PREVIOUSLY_RESOLVED_VIOLATIONS>. Do not remove an unrelated clause to make a diagnostic disappear. Output the complete corrected SQL in a SQL code block.