AIEP
Loop EngineeringEmergingUpdated 2026-12

Execution-Verified Rewrite

Let a model propose a faster or cheaper version of something you can run, and keep a candidate only if running it gives the same output and a measured gain beyond noise.

Runnable example, tested in CISourceTestsJump to code
$cd examples && pytest loop_engineering/test_execution_verified_rewrite.py
optimizationverificationcode-generationsqlloops

What It Is

An improvement loop with a hard oracle. The model proposes a rewrite of something executable: a SQL query, a function, a data transformation, a prompt with a test set. Each candidate is run. It's accepted only if its output is identical to the original's on the same input, and if it's measurably better than the current best by more than measurement noise. Every attempt, including the wrong ones, goes back to the model as history for the next proposal. When the budget runs out, the best verified candidate wins. If there isn't one, the original stands.

It's the Maker–Verifier Split with the strongest possible verifier: execution plus a baseline. FunSearch and AlphaEvolve are large-scale research versions of the same loop.

The Problem It Solves

Models are good at proposing optimizations: turn the correlated subquery into a join, pre-aggregate, vectorize the loop. They're also confidently wrong in ways that look right. An inner join that silently drops customers with no orders is faster and returns different results. A "cleaner" function changes an edge case. Reviewing every suggestion by hand defeats the purpose, and accepting the model's own claim that "this is equivalent" is how a performance fix becomes a data bug.

Speed claims have the same problem. One lucky timing run makes a slower query look faster.

How It Works

flowchart TD
    O["Original"] --> B["Run: output fingerprint + median cost
(baseline)"] B --> P["Model proposes a candidate
(sees all previous attempts and why they failed)"] P --> X{"Runs?"} X -->|"error"| H["Record: error"] X -->|"yes"| S{"Same output as original?"} S -->|"no"| H2["Record: different result"] S -->|"yes"| G{"Better than current best
by more than min_gain?"} G -->|"no"| H3["Record: not faster"] G -->|"yes"| K["Keep as new best"] H & H2 & H3 & K --> N{"Budget left?"} N -->|"yes"| P N -->|"no"| R["Return best verified (or original)"]
  1. Fix the test input. Equivalence is only as good as the data it's checked on. Include edge cases: empty groups, nulls, duplicates, the customer with no orders.
  2. Fingerprint the output. Hash the result. Compare unordered unless order is part of the contract. SQL without ORDER BY may return rows in any order, and that's not a difference.
  3. Measure the median of several runs, and require a minimum relative gain over the current best, not just the original. Otherwise noise accepts regressions.
  4. Feed back every attempt with its verdict: error message, "different result", "not faster". The model's next proposal improves most from seeing what didn't work.
  5. Budget the loop, both in proposals and in total runtime, and keep a log of every attempt so a person can review what was accepted and why.

When to Use It

  • The artifact is executable and has a cheap, deterministic way to compare outputs: queries, pure functions, transformations, compiled kernels.
  • You can measure the thing you're improving (latency, cost, memory, token count) with noise you can bound.
  • You'd otherwise hand-review model optimizations one by one.

When NOT to Use It

  • No oracle. If "same output" can't be checked, as with prose rewrites, design changes or anything judged by taste, use a Maker–Verifier Split with a rubric.
  • The test input doesn't represent production. A rewrite verified on 100 rows of fixture data can still differ on a production edge case. Verify on realistic data, or on a sample from production.
  • Side effects. Never run candidates that write, send or delete against real systems. Use a sandbox, a replica or a transaction you roll back.

Trade-offs

  • Equivalence on a test set isn't proof. It catches most wrong rewrites, not all. For high-stakes code, follow up with differential testing on more data, or formal methods where they're available.
  • Execution cost. Every candidate runs several times. For slow queries that's real load, so run against a replica and cap concurrency.
  • Overfitting to the benchmark. The loop optimizes what you measure on the input you gave it. Re-check winners on a held-out input (Frozen Evaluation Set).

Failure Modes

Accepting on the model's word. The model says "this is semantically equivalent", and the loop believes it. Only execution counts.

Order-sensitive comparison. Results are compared as ordered lists, so every rewrite that changes the plan "differs", and nothing is ever accepted. Compare as multisets unless order is specified.

Single-run timing. A cold cache makes the original look slow, a warm one makes the candidate look fast, and a regression is accepted. Use the median of repeated runs and a minimum gain.

History withheld from the model. Each round sees only the original, so the model proposes the same broken join five times. Pass every attempt and its verdict back.

Implementation Example

A provider-neutral optimization loop with output fingerprinting, median-of-repeats cost, a minimum-gain threshold and history fed back to the proposer. The tests run real queries against an in-memory SQLite database. A faster join that drops a customer with no orders is rejected, a broken query is recorded and fed back, and the correct pre-aggregated rewrite is kept.

cd examples && pytest loop_engineering/test_execution_verified_rewrite.py
"""Execution-Verified Rewrite.
 
Let a model propose a better version of something you can run (a SQL query,
a function, a prompt with a test set) and accept a candidate only when two
measurements say so:
 
1. Equivalence: it produces the same output as the original on the same
   input. "Looks right" and "the model says it's equivalent" don't count.
2. Improvement: it is measurably better (faster, cheaper) than the current
   best, by more than measurement noise.
 
Every attempt, including the wrong and failing ones, goes back to the model
as history, so the next proposal can learn from them. The loop stops when the
budget is spent. If nothing verified wins, the original stands.
"""
 
from __future__ import annotations
 
import hashlib
import statistics
from collections.abc import Callable
from dataclasses import dataclass, field
 
 
@dataclass
class Attempt:
    candidate: str
    verdict: str  # "error" | "different result" | "not faster" | "improved"
    cost: float | None = None
    detail: str = ""
 
 
@dataclass
class Outcome:
    best: str
    baseline_cost: float
    best_cost: float
    attempts: list[Attempt] = field(default_factory=list)
 
    @property
    def speedup(self) -> float:
        return self.baseline_cost / self.best_cost if self.best_cost else 1.0
 
 
def fingerprint(rows: list[tuple], ordered: bool) -> str:
    """Hash of the output. Unordered by default: SQL without ORDER BY may return rows in any order."""
    canonical = rows if ordered else sorted(rows, key=repr)
    return hashlib.sha256(repr(canonical).encode()).hexdigest()
 
 
def optimize(
    original: str,
    execute: Callable[[str], list[tuple]],  # runs a candidate on the test input
    cost: Callable[[str], float],  # one measurement (ms, tokens, dollars); noisy is fine
    propose: Callable[[str, list[Attempt]], str],  # the model: (original, history) -> candidate
    budget: int = 5,
    repeats: int = 3,
    min_gain: float = 0.10,  # require 10% better than the current best, to beat noise
    ordered: bool = False,
) -> Outcome:
    def measure(q: str) -> float:
        return statistics.median(cost(q) for _ in range(repeats))
 
    expected = fingerprint(execute(original), ordered)
    baseline = measure(original)
    outcome = Outcome(original, baseline, baseline)
 
    for _ in range(budget):
        candidate = propose(original, outcome.attempts)
        try:
            same = fingerprint(execute(candidate), ordered) == expected
        except Exception as exc:  # a candidate that doesn't run is information, not a crash
            outcome.attempts.append(Attempt(candidate, "error", detail=str(exc)))
            continue
        if not same:
            outcome.attempts.append(Attempt(candidate, "different result", detail="output differs from the original"))
            continue
        c = measure(candidate)
        if c < outcome.best_cost * (1 - min_gain):
            outcome.best, outcome.best_cost = candidate, c
            outcome.attempts.append(Attempt(candidate, "improved", c))
        else:
            outcome.attempts.append(Attempt(candidate, "not faster", c, f"{c:.1f} vs best {outcome.best_cost:.1f}"))
    return outcome
 
 
def history_for_prompt(attempts: list[Attempt]) -> str:
    """What the model sees next round: what failed and why, not just what worked."""
    return "\n".join(
        f"#{i}: {a.verdict}" + (f" ({a.detail})" if a.detail else "") + f"\n{a.candidate}"
        for i, a in enumerate(attempts, start=1)
    )

Tool Landscape

ToolNotes
Database EXPLAIN ANALYZE, replicasMeasure query cost safely
pytest-benchmark, hyperfineRepeated timing with statistics
HypothesisProperty-based inputs for stronger equivalence checks
OpenEvolve and similar open-source evolve loopsPropose–evaluate–keep loops at larger scale

Further Reading

Spotted something wrong or have a production story? Edit this page on GitHub.