A Theoretical Analysis of Test-Driven Code Generation

Nicolas Menet, Michael Hersche, Andreas Krause, Abbas RahimiNeurIPS 2026

TL;DR

When AI coding assistants write and test software, we usually rely on ad-hoc tricks to pick their best draft or feed error messages back into the prompt. This paper builds the missing mathematical foundation for test-driven AI coding, proving why judging code by "fuzzy" behavioral similarity beats strict pass/fail rules—and revealing why no amount of self-debugging can ever overcome a vague prompt.

What Problem Does This Paper Address?

Imagine asking an LLM to write a function. To boost its chances of success, engineers rely on two main workflows: generating dozens of code/test drafts and picking a winner after running them (post-generation selection), or feeding error tracebacks back into the model so it can iteratively fix its mistakes (backprompting).

Figure 1: We consider environment interaction in two settings. The scope of our analysis is marked in yellow.

While these tricks power tools like Claude Code and Cursor, they have evolved as a "zoo of heuristics" without a unified theory. Adding to the chaos is program aliasing: because LLMs predict text token-by-token, probability gets shattered across dozens of syntactically different scripts that actually compute the exact same thing. How should we mathematically group and score these programs? And when an AI gets stuck in a debugging loop, is the model failing, or is the task fundamentally unsolvable from the prompt alone?

Methods

The authors cast test-driven code generation as a probabilistic causal process: a human has a hidden mental algorithm and an execution environment (like Python + NumPy), compresses them lossily into a text prompt, and asks the LLM to recover both an executable test suite and working code.

Figure 2: Generative process represented as a struc- tural causal model (arrows indicate causality). We observe an informal specification (description) corre- sponding to an algorithm in an execution context (en- vironment). We seek an executable specification (test suite) and an implementation that satisfies it (code).

Using this setup, they introduce two novel theoretical frameworks:

  • Fuzzy Similarity Estimators (Selection): Standard heuristics like AlphaCode or CodeT group programs by strict functional equivalence—two scripts are only "the same" if they agree on 100% of test cases. The authors generalize this to functional $s$-similarity, a "soft" measure based on the fraction of tests where outputs match. This smooths the probability landscape over code behaviors, leading to two new selection methods: MaxPass Soft and CodeT Soft.
  • In-Context Thompson Sampling (Backprompting): They prove that because LLMs are pre-trained on commit histories (buggy attempts followed by fixes), feeding test errors back into the context makes the LLM approximate Thompson sampling—a classic Bayesian algorithm that balances exploration and exploitation. Crucially, they derive a new regret bound where the reward splits into an observable part (syntax, library quirks) and an unobservable part (the user's true, unspoken algorithmic intent). They also build an online estimator to measure this ambiguity on the fly.

Datasets

The authors evaluate seven frontier open-weight models across four established benchmarks and two new quantum-computing variants:

  • Established Benchmarks: BigCodeBenchHard (148 tough tasks spanning 139 Python libraries), LeetCodeDataset (228 puzzle questions containing rich input-output examples), and SWE-bench Verified (real-world GitHub issue resolution).
  • New Benchmarks: QiskitHumanEvalSim, a democratized 143-task subset of QiskitHumanEval runnable via simulation without quantum hardware; and QiskitHumanEvalSimX, an enhanced version where Gemini 3 Pro translated oracle test behaviors and input-output pairs into natural language descriptions to explicitly test whether clearer prompts unlock self-debugging.

Key Insights and Ideas

  • "Soft" similarity crushes strict equivalence: Demanding 100% test agreement throws away massive statistical signal. Aggregating "similar" code behaviors acts as a smoothing filter against neural quirks and boosts the estimator's signal-to-noise ratio (SNR) by a factor of at least $m^2$ (where $m$ is the number of test suites)—and exponentially more when candidate scripts are diverse.
  • The Law of Irreducible Regret: Iterative self-debugging can learn library rules and fix syntax errors at a healthy sub-linear rate. However, ambiguity in the prompt creates a linear irreducible regret ($\Delta$). No amount of running self-generated tests can tell an LLM what you meant if you didn't specify edge cases.
  • Writing tests is a distinct bottleneck: Some reasoning models (like GPT-OSS-120B and MiniMax-M2.1) thrive when debugging against ground-truth "oracle" tests, yet completely flatline when relying on their own generated tests. Capturing the "test manifold" is just as critical for AI training as writing code.

Key Results

  • Soft Selection Wins: Across 10 independent generation rounds, MaxPass Soft and CodeT Soft consistently beat their strict ("Hard") counterparts. Using MiniMax-M2.1 on BigCodeBenchHard, CodeT Soft jumps to 42.03% pass@1 compared to 36.08% for CodeT Hard. Furthermore, scoring candidates purely by test pass rates (MaxPass) beats grouping code outputs (MBR-Exec), showing frontier models are poorly calibrated between code and test generation.
  • Ambiguity Dictates Backprompting: Over 10 rounds with Qwen3-235B, self-test feedback shines on LeetCodeDataset (24% $\rightarrow$ 72.11%, matching oracle feedback because prompts include input-output examples, making $\Delta \approx 0\%$), yields modest gains on QiskitHumanEvalSim ($\Delta = 16.08\%$), and completely stalls on vague BigCodeBenchHard prompts (33.11% vs. 63.78% with oracle tests; $\Delta = 30.68\%$).
10 rounds of backprompting showing how prompt ambiguity caps self-debugging performance across datasets.
  • Fixing the Prompt Fixes the Loop: Adding concrete behavioral examples in QiskitHumanEvalSimX more than doubles Qwen3's self-debugging improvement over round one (jumping from a +3.21% gain to +7.13%).
  • Agentic Coding: On repository-level SWE-bench Verified tasks (250 actions with MiniMax-M2.7), standard self-testing reaches 74.09% vs. 79.35% with oracle reproduction tests—revealing a low irreducible regret ($\Delta = 5.26\%$) because real GitHub issues naturally pack rich contextual clues.

Limitations and Future Work

  • Context Length Bottlenecks: Execution tracebacks get huge quickly; the authors had to use an LLM compressor to summarize feedback across rounds. Designing model architectures that natively digest long execution histories is flagged as an important next step.
  • Convergence Required for Ambiguity Detection: Their online estimator successfully approximates irreducible regret $\Delta$ without ground-truth tests (e.g., predicting 27.07% vs. 30.68% actual on BigCode), which could let future agents automatically pause and ask humans for clarification—provided the debugging loop has already converged.
  • Training Gaps: Because several top models fail at generating discriminative unit tests, future post-training recipes must treat test generation as a first-class citizen alongside code synthesis.

Summary updated

Abstract

Code assistants are increasingly utilized in test-driven software development, yet the theoretical mechanisms behind their environment-interaction strategies remain underexplored. We provide a probabilistic framework for two dominant paradigms: code selection after generation using the execution environment, and code generation conditioned on environment feedback. First, we formalize several well-established selection heuristics as environment-aware estimators of code correctness. We theoretically prove that estimators based on fuzzy functional similarity add an inductive bias and strictly dominate estimators based on functional equivalence in terms of signal-to-noise ratio. Second, we frame backprompting as an in-context approximation of Thompson sampling. We derive a novel regret bound for reward functions with unobservable components, theoretically explaining why the effectiveness of backprompting is limited by the ambiguity of the informal task description (an irreducible regret). Using seven state-of-the-art open weight models, we corroborate these findings across BigCodeBenchHard, LeetCodeDataset, QiskitHumanEvalSim, and SWE-bench Verified. Our formalization also suggests how to improve task descriptions effectively, leading to an improved benchmark for LLM-assisted quantum programming, QiskitHumanEvalSimX.
BibTeX
@inproceedings{menet2026theoretical,
  author = {Nicolas Menet and Michael Hersche and Andreas Krause and Abbas Rahimi},
  title = {{A Theoretical Analysis of Test-Driven Code Generation}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=pnb7TQTzC2},
}

Loading related content...

Figure