AI SQL Optimization Can Make Ledgers Wrong

SQL Correctness
Published on
Written byMayank Singh
AI SQL Optimization Can Make Ledgers Wrong

TL;DR: AI SQL optimization can speed up a ledger query while changing join grain, null handling, or period boundaries. Treat each rewrite as unproven until it passes an executable correctness contract, independent reconciliation, and staged CI/CD controls.

Key Takeaways: - Faster execution and preserved financial meaning are separate claims. - Ledger correctness needs machine-readable invariants tested against an independent source. - Shadow runs, canaries, rollback paths, and human approval make optimization governable.

The Rewrite Got Faster. Did It Get Right?

Illustration for The Rewrite Got Faster. Did It Get Right?

A SQL rewrite can cut execution time and still change what a ledger means. For finance, a duplicated posting, shifted cutoff, or broken debit-credit balance is an integrity incident, not a slow-query ticket.

Execution benchmarks are useful, but they are narrower than ledger teams need.

The AI SQL optimization benchmark methodology should separate three claims often collapsed into one: - Faster execution: The query completes sooner. - Lower resource consumption: The query scans, computes, or transfers less. - Identical business meaning: The query still represents the same financial event.

A benchmark can establish the first two claims under controlled conditions. It does not establish identical business meaning, because that claim requires domain context.

Which leaves a harder question: does an equal result set prove equal ledger meaning?

Three Optimization Paths, Three Risk Profiles

Built-in cost-based plan selection chooses among plans intended to preserve declarative semantics. AI-generated rewrites and index recommendations change or surround SQL, so each proposal needs its own review. Natural-language-to-SQL adds an intent-inference step before the database sees any SQL.

A shifted filter can distort an analytical report. A ledger query with changed row grain can duplicate postings, drop unmatched entries, or move them across close periods.

That is why SQL correctness for regulated systems must precede performance review.

Performance earns consideration. It does not earn deployment. The gap between returning the same rows and preserving the same financial meaning is where the risk hides.

Does a result-set diff close that gap?

Why Equivalent Results Are Not Ledger Integrity

That gap is larger than a result-set diff.

Result-set equivalence is narrow: the same columns, values, and row multiset, under one dataset and one point in time. Ledger correctness also depends on posting grain, temporal boundaries, exact arithmetic, and accounting invariants.

These differences turn matching outputs into different ledger obligations. The first risk appears before execution.

Generative Rewrites Change Meaning Before Execution

Consider two queries that appear interchangeable:

1SELECT p.posting_id
2FROM ledger_postings AS p
3WHERE p.customer_id NOT IN (
4 SELECT customer_id
5 FROM blocked_customers
6);
1SELECT p.posting_id
2FROM ledger_postings AS p
3WHERE NOT EXISTS (
4 SELECT 1
5 FROM blocked_customers AS b
6 WHERE b.customer_id = p.customer_id
7);

If `blocked_customers.customer_id` contains nulls, these queries can produce different results. This is not a database bug. It is SQL semantics doing what the rewritten text now says.

A `LEFT JOIN` changed to `INNER JOIN` removes unmatched postings. Moving a predicate can change row eligibility. Collapsing a subquery or changing `GROUP BY` grain can multiply or merge postings.

Each rewrite can preserve columns while changing the event represented.

That can duplicate a debit, assign a posting to the wrong close period, shift a timezone boundary, or introduce floating-point rounding. Any of these can break reconciliation, even when execution looks better.

The deeper analysis belongs in semantic equivalence for SQL rewrites. Traditional optimizers are intended to preserve declarative semantics. An AI-generated candidate must infer intent before the optimizer receives it, so errors can enter before plan selection begins.

Index recommendations need a separate review. Ordinary indexes preserve query results, but they change write cost, locking, storage, and maintenance. A unique index can expose duplicate posting keys by rejecting writes.

Equivalence testing can faithfully preserve a mistake already present in the original query. This is why why fintech AI failures start at refactor generalizes beyond SQL.

Correctness must be checked against an independent accounting source, not source SQL alone. Those named failure modes can become an explicit contract, rather than a reviewer’s intuition. But a contract no pipeline executes is still only prose.

So how do you turn that prose into a gate that fails before a rewrite reaches production?

Turn Ledger Semantics Into an Executable Contract

An executable ledger contract turns finance intent into assertions that can fail.

Inventory every ledger-critical query before allowing optimization: - Its authoritative source of truth. - Its intended posting grain. - Its period boundary and timestamp basis. - Its downstream reconciliation consumers. - Its accountable business owner.

Ownership helps, but it does not show whether a rewrite preserves the ledger's arithmetic and timing rules. Can those rules become machine-readable?

Make Invariants Machine-Readable

A ledger contract should look more like this:

1contract_version: 3
2source_of_truth: core_ledger
3posting_grain: transaction_id
4accountable_owner: finance_controls
5
6time_basis:
7 timezone: UTC
8 field: posted_at
9 period_end: exclusive
10
11money:
12 type: decimal
13 precision_scale_source: currency_reference_table
14
15invariants: - posting_id_unique - debits_equal_credits_by_transaction_and_currency - posted_entries_immutable - corrections_are_compensating_entries - idempotency_key_unique

Operational rules belong beside arithmetic rules. Posted entries must stay immutable under an append-only policy. Corrections must use approved compensating entries.

Idempotency keys must prevent duplicate submissions. Period close must use an explicit timezone and timestamp basis. Money needs defined precision, scale, rounding, and currency representation.

Binary floating-point arithmetic is unsuitable for contractual balances. Apply the debit-credit invariant only where double-entry applies.

Build a representative corpus that contains: - Null values and unmatched joins. - Duplicate dimensions and multiple currencies. - Rounding boundaries and late postings. - Period edges and concurrent transactions.

Keep the standard separate from the implementation. Use an independently written reconciliation query or source-of-truth check. Otherwise, the original and candidate can fail in the same correlated way.

The ledger invariant test library can make these assertions reusable. Double-entry reconciliation patterns can provide the independent balance check.

A written contract only helps if the pipeline enforces it on every proposed rewrite. The next control must compare meaning before it compares speed. Can a CI gate make that comparison without letting a fast but wrong rewrite pass?

Build a CI Gate for Semantic Equivalence

Illustration for Build a CI Gate for Semantic Equivalence

Version the original SQL, candidate rewrite, schema, optimizer or model, prompt configuration, index changes, and execution plans together. Store their hashes with the change request so any deployment can be reproduced.

Use a fixed gate order: - Parse and lint both queries. - Execute both against the fixture corpus. - Compare canonicalized results. - Run independent ledger invariants. - Compare execution plans and observed behavior. - Evaluate the performance budget last.

Compare schema, column order, nullability, precision, row multiset, and ordering where ordering is contractual. Raw text diffs and one sampled output cannot prove equivalence.

Add rare production cases to fixtures as monitoring finds them. Keep invariant checks separate from the optimized query implementation. An incorrect candidate must never define its own standard.

A GitHub Actions pipeline can name each failure mode directly:

1name: ledger-sql-gate
2
3on:
4 pull_request:
5 paths: - "sql/**" - "ledger/**" - ".github/workflows/ledger-sql-gate.yml"
6
7permissions:
8 contents: read
9
10jobs:
11 correctness-and-performance:
12 runs-on: ubuntu-latest
13 steps: - uses: actions/checkout@v4 - name: semantic-diff-failed
14 id: semantic_diff
15 continue-on-error: true
16 run: ./ci/gates/semantic-diff-failed --original sql/original.sql --candidate sql/candidate.sql - name: ledger-invariant-failed
17 id: ledger_invariant
18 continue-on-error: true
19 run: ./ci/gates/ledger-invariant-failed --candidate sql/candidate.sql --contract ledger/contract.yaml - name: plan-regression
20 id: plan_regression
21 continue-on-error: true
22 run: ./ci/gates/plan-regression --original sql/original.sql --candidate sql/candidate.sql - name: performance-threshold
23 id: performance_threshold
24 continue-on-error: true
25 run: ./ci/gates/performance-threshold --original sql/original.sql --candidate sql/candidate.sql --budget ledger/performance.yaml - name: Enforce gate results
26 if: always()
27 env:
28 SEMANTIC_DIFF: ${{ steps.semantic_diff.outcome }}
29 LEDGER_INVARIANT: ${{ steps.ledger_invariant.outcome }}
30 PLAN_REGRESSION: ${{ steps.plan_regression.outcome }}
31 PERFORMANCE: ${{ steps.performance_threshold.outcome }}
32 run: |
33 test "$SEMANTIC_DIFF" = success
34 test "$LEDGER_INVARIANT" = success
35 test "$PLAN_REGRESSION" = success
36 test "$PERFORMANCE" = success
37
38 protected-ledger-paths:
39 if: contains(github.event.pull_request.labels.*.name, 'ledger-critical')
40 needs: correctness-and-performance
41 runs-on: ubuntu-latest
42 environment:
43 name: ledger-production
44 steps: - run: echo "Ledger-critical change approved for controlled deployment."

Configure the `ledger-production` environment with required reviewers for posting, close, and reconciliation changes.

Use `EXPLAIN` and runtime tools to compare estimated and observed rows, join strategies, scans, spills, memory use, and lock behavior. Block the merge when correctness passes but performance regresses.

This extends CI/CD automation for database changes into a semantic control. The SQL correctness gates should fail closed.

Passing this gate proves fitness for a controlled rollout. It does not tell you how to contain the first bad plan. The missing ingredient is a rollout that makes the first bad plan cheap to contain.

Ship AI Rewrites Behind a Shadow-to-Canary Rollout

Containment starts by making a wrong candidate harmless.

Run the candidate in shadow mode against a production-like snapshot or read replica. Disable every side effect while collecting evidence.

1rollout:
2 shadow:
3 source: production_like_snapshot
4 side_effects: disabled
5
6 canary:
7 first: read_only_analytics_and_reconciliation
8 protected_paths: - posting - period_close - reconciliation
9
10 promotion:
11 require: - semantic_diff_pass - ledger_invariants_pass - performance_budget_pass
12
13 rollback:
14 target: versioned_original_sql

Begin canaries with read-only analytics and reconciliation views. Do not expose posting, period-close, or other write-sensitive paths first. Treat index deployment as a separate change set, with a different build cost, write amplification, lock duration, and unique-constraint behavior.

Static equivalence does not prove that isolation, locking, ordering, and visibility survive concurrent posting and reconciliation. Test those races explicitly.

Monitor: - p50, p95, and p99 latency. - Rows scanned, CPU, I/O, and cloud cost. - Lock waits and write amplification. - Output-count differences and invariant failures. - Rollback frequency.

Keep the original versioned SQL available for immediate rollback. Trigger revalidation when the model, prompt, optimizer, schema, or workload changes materially. A streaming SQL view can lie about freshness when observation points drift.

The same problem applies to generated SQL and changing execution context. Define promotion criteria before rollout. A candidate advances only when correctness stays clean and measured improvement clears the approved performance budget.

The rollout becomes durable only when speed and ledger fidelity share one scorecard. Without that shared standard, leadership sees two good-news stories instead of one safe decision. The final decision must combine those stories with ownership, evidence, and a clear adoption rule.

The CTO Decision: Speed With a Proof Trail

A fast query can still be a failed control.

Measure success across four dimensions: - Latency: How quickly does the query complete? - Infrastructure cost: What compute, I/O, and storage does it consume? - Semantic fidelity: Does it preserve the intended financial event? - Operational control: Can you reproduce, monitor, approve, and reverse the change?

Never collapse them into a vendor’s latency claim.

Use a decision memo that separates vendor benchmarks, candidate evidence, invariant results, deployment observations, rollback history, and remaining risk.

Operational track record is due diligence. It is not proof that a particular generated query preserves ledger semantics.

Use the enterprise AI evaluation checklist to structure that evidence. Ask for regulated-industry deployment evidence that separates general track records from candidate-specific results.

The adoption rule is non-negotiable. No speedup ships without independent ledger invariants. No posting, close, or reconciliation candidate ships without accountable human approval.

Trustworthy AI SQL optimization reduces latency and cost while making correctness visible, repeatable, and enforceable. That scorecard turns the adoption debate into an auditable CTO decision. The rule must now survive a more practical test: edge cases, reviews, and deployment gates.

Frequently Asked Questions

Q: Can AI SQL optimization change query results?

A: Yes. A generative rewrite can change join grain, null handling, predicates, aggregation, or temporal boundaries. Traditional cost-based optimizers intend to preserve declarative semantics. A generated candidate still needs separate validation, as explained in the AI SQL optimization overview.

The next question is how to test that validation on a financial ledger.

Q: How do you test AI-generated SQL for a financial ledger?

A: Run the original and candidate queries against edge-case fixtures and a production-like snapshot. Compare canonicalized outputs. Then execute independently written ledger invariants and reconciliation checks.

Include nulls, duplicate dimensions, currency precision, timezone cutoffs, late postings, and concurrent writes. Equality on one sampled result set is insufficient. The financial ledger integrity guide provides the broader control model.

That leaves one more risk: whether index advice can change write behavior.

A: A normal index leaves query results unchanged, but it changes write cost, locking behavior, and storage usage. A unique index can expose duplicate postings by rejecting writes.

Review index proposals separately. Test them under write concurrency and include rollback in the deployment plan. The final question is how to stage such a change without exposing the ledger.

Q: How should AI SQL optimization fail safely?

A: Run the candidate in shadow mode against a production-like snapshot or read replica. Then use a read-only canary before protected posting, close, or reconciliation paths. Define promotion and rollback rules before rollout, and require accountable human approval for ledger-critical changes.

Make that proof a release requirement before any speedup reaches production. The next deployment review should show the evidence, not merely promise it.

About the author

MS
Mayank Singh
Software Developer, Levitation Infotech

Mayank Singh is a software developer at Levitation Infotech, where he builds web and AI-powered applications across the company’s fintech, healthcare, and enterprise projects.

Supercharge Your Success with Our Expertise

Amplify Your Business with Our Expertise. Explore Services Tailored for Your Success.

Get In Touch