LLM-Driven Code Defect Repair and Test Generation Practices

    This article explores the practices of automating code defect repair using large language models (LLMs). It details a dual-role collaborative framework involving a Fixer and a Test Writer, result-oriented reinforcement learning training strategies, multi-candidate generation during inference, and crucial engineering considerations for real-world CI/CD integration. By using executable test results as the objective criterion, this approach transforms repetitive debugging and verification tasks into a reliable automated workflow.

    1. Background: Why Automated Defect Repair is Needed

    In software projects, defect repair consumes a significant amount of development time. A single defect often goes through multiple rounds of communication and debugging from reproduction, localization, modification to verification. For large codebases, the localization phase is particularly time-consuming, as developers need to understand cross-file call relationships, module boundaries, and historical design decisions.

    Large language models (LLMs) have the ability to understand code semantics and generate patches, making them useful for assisting or even automating repair tasks. However, directly instructing the model to output a piece of “correct-looking” code is unreliable. The model might modify unrelated files, merely mask the symptoms, or generate patches that fail regression tests. What engineering truly requires is a mechanism that subjects repair results to objective standards.

    The core of this approach is: using executable test results as the evaluation criterion, rather than model self-evaluation or subjective human feelings.

    2. Task Decomposition: Making the Repair Process Controllable

    Automated repair can be decomposed into two basic phases.

    1. File Localization

    The goal of the localization phase is to identify the files and functions related to the defect. Inputs typically include the problem description, error stack trace, failing test cases, and the directory structure of the code repository. The quality of localization directly determines whether subsequent edits are meaningful. If localization fails, even the most beautifully written patch cannot solve the problem.

    In practice, localization can be a two-step process: first, narrow down candidate files through keyword retrieval or dependency graphs, and then ask the model to rank the candidates and provide reasons. This reduces the context length and mitigates the risk of the model “hallucinating” file paths.

    2. Code Edits

    The editing phase includes two types of tasks. The first is defect repair, which involves fixing logic errors, boundary conditions, or resource management issues in existing code. The second is test supplementation, which involves writing unit tests that reproduce the issue, ensuring they fail before the fix and pass after the fix.

    Handling both tasks within the same framework creates a closed loop of repair and verification. This is the foundation of the dual-role design discussed below.

    3. Dual-Role Collaborative Framework: Fixer and Test Writer

    The dual-role design divides the model’s work into two relatively independent responsibilities.

    The Fixer is responsible for analyzing the root cause of the defect and submitting minimal code changes. Its constraints are: keep the modification scope as small as possible, do not alter existing interface semantics, and do not introduce refactoring unrelated to the defect.

    The Test Writer is responsible for generating reproduction cases based on the problem description. A good reproduction case should meet three conditions: it must fail consistently when the defect exists; its assertions must align with the problem description; and it must not depend on accidental execution order or external state.

    The collaboration between the two can be summarized as: the Test Writer first provides a reproducible failing case, the Fixer modifies the code accordingly, and finally, the entire test suite is run together to determine if the repair is valid.

    This design has two engineering values. First, the reproduction case itself is a reusable regression asset; even if the patch is rejected, the test retains its value. Second, role separation allows the output of each step to be inspected individually, making it easier to pinpoint the failing component.

    It is crucial to note that the Fixer should not be allowed to modify test files to “make the tests pass.” Otherwise, the model might learn to weaken assertions or delete test cases, severely undermining the credibility of the results. In engineering practice, this is typically addressed through permission controls, setting the test directory to read-only, or using unmodified copies of the tests during the evaluation phase.

    4. Training Strategy: Result-Oriented Reinforcement Learning

    Relying solely on supervised data training, models tend to learn “human-like patches” but cannot guarantee their correctness. The value of reinforcement learning (RL) lies in its ability to use execution results directly as the optimization target.

    1. Training Data Preparation

    Training data should come from real open-source or enterprise internal code repositories. Each sample should include the problem description, the pre-fix code snapshot, an executable test environment, and a test suite that can verify the repair effect. The environment must be reproducible, and dependency versions must be locked; otherwise, the same patch may yield inconsistent results on different machines, distorting the reward signal.

    Data cleaning is equally important. Samples that cannot be stably reproduced must be removed, items with inherent test uncertainty should be discarded, and overlap between training and evaluation sets must be checked to avoid inflated evaluation results.

    2. Reward Design

    A straightforward approach is “outcome-based reward”: the model receives a positive reward only if the entire test suite passes; otherwise, the reward is zero or negative. The advantage of this design is a clear objective consistent with engineering acceptance criteria.

    However, it introduces a problem: sparse rewards. Many difficult samples are nearly impossible to succeed early in training, making it hard for the model to obtain effective gradients. Common countermeasures include:

    • Stratified sampling by sample difficulty, using easier samples first to build basic capabilities;
    • Providing small process rewards for correct localization but incomplete edits, while ensuring the final reward remains based on test results;
    • Setting a reasonable maximum number of interaction rounds to prevent the model from wasting computational resources on invalid paths.

    3. Preventing Reward Hacking

    As long as rewards can be exploited, the model will attempt to exploit them. In addition to the aforementioned prohibition on modifying test files, checks should be made to see if the patch includes special handling for the test framework, bypasses assertions via hardcoded return values, or swallows exceptions. These checks can be implemented using static rules or delegated to an independent review model.

    5. Inference Phase: Multi-Candidate Generation and Self-Verification

    When a trained model is used in practice, it typically employs a “generate multiple candidates, then filter uniformly” strategy.

    1. Candidate Generation

    For the same issue, several repair patches and corresponding test cases can be generated using different sampling temperatures or context organization methods. The number of candidates is a trade-off parameter: more candidates increase the probability of hitting the correct solution, but also increase computational cost and wait time. In practice, the number of candidates is usually set based on task importance and budget.

    2. Filtering Mechanism

    Filtering can be divided into three layers:

    1. Syntax and build checks: Filter out patches that cannot compile or pass static checks;
    2. Test execution: Run the complete test suite in an isolated environment, recording pass/fail statuses;
    3. Comprehensive evaluation: Rank candidates that passed tests based on code style, change size, and complexity.

    If multiple patches pass the tests, priority should be given to the one with the smallest footprint and clearest semantics, rather than picking one randomly.

    3. Schematic Flow

    1. Input: Problem description, code repository snapshot, test suite
    2. Steps:
    3. 1. Locate candidate files -> Sort and take top K
    4. 2. For each candidate, sample and generate patch P_i and reproduction test T_i
    5. 3. Apply P_i in an isolated environment, run T_i and the original test suite
    6. 4. Discard candidates that fail to build or fail tests
    7. 5. Sort passed candidates by change size, output the optimal patch
    8. 6. Submit results for manual review or enter the merge process

    6. Engineering Implementation: Environment, Permissions, and Integration

    Once automated repair enters a real development workflow, engineering details determine whether it can operate stably.

    1. Environment Isolation

    Each repair attempt should be completed in an independent container or virtual environment to prevent dependency and cache pollution between different tasks. Environments should be pre-built with cached base images to reduce startup time. Resource quotas need upper limits, including CPU, memory, execution time, and network access, to prevent abnormal tasks from overwhelming the cluster.

    2. Principle of Least Privilege

    The automated agent should only have permissions to read code, write to working branches, and run tests. It should not push directly to the main branch or access production environment secrets. Credentials must be injected via secret management services and never written into code or logs.

    3. Integration with Existing R&D Processes

    Automated repair can be integrated gradually via the following path:

    • Provide a “generate fix suggestion” entry in the IDE, confirmed by developers one by one;
    • Create independent branches via the version control system and submit patches, accompanied by reproduction cases and explanations;
    • Trigger complete tests in the CI/CD pipeline, using results as a pre-merge check;
    • Establish manual review nodes; patches for high-risk modules involving security, payments, or data consistency must be confirmed by the person in charge.

    For enterprise users, historical patches and test logs can be stored in object storage, generation and evaluation processes logged in logging services, and success rates, timeout rates, and anomalies tracked via monitoring and alerting. These capabilities belong to general cloud infrastructure categories and can be selected based on the existing tech stack.

    7. Evaluation Metrics and Risk Boundaries

    When evaluating an automated repair system, looking solely at the “repair success rate” is insufficient. It is recommended to also track the following metrics:

    • First-time pass rate: The proportion of patches that pass tests without human intervention;
    • False repair rate: The proportion of patches that pass tests but are found to have semantic errors upon manual inspection;
    • Regression risk: The frequency of patches introducing new defects, observable by expanding the regression test scope;
    • Cost per repair: Including computational resources, wait time, and manual review time.

    It must be clear that passing tests only proves that the patch satisfies the behaviors covered by existing tests; it cannot guarantee correctness outside that coverage. When tests themselves are incomplete, the meaning of “passing” is compromised. Therefore, automated repair is better suited for modules with clear definitions and good test coverage, rather than legacy code lacking tests.

    Additionally, model-generated code may introduce security risks, such as missing input validation, permission logic errors, or inappropriate dependency usage. These issues should be managed through a combination of static security scanning and manual review.

    8. Implementation Recommendations

    For teams preparing to introduce these capabilities, it is recommended to proceed in the following order:

    1. Pilot on subsystems with sufficient test coverage and clear module boundaries;
    2. Fix the evaluation set and establish baseline data before and after repairs;
    3. Run in an isolated environment for a period, logging results only without auto-merging;
    4. Adjust prompt design, filtering rules, and reward conditions based on false repair cases;
    5. Gradually expand the scope of application while retaining manual review nodes.

    Automated repair is not a tool to replace developer judgment, but one that offloads repetitive localization, reproduction, and verification tasks to machines, allowing engineers to focus on design and decision-making. As long as verification standards are reliable, permission boundaries are clear, and processes are traceable, this methodology can play a stable role in actual R&D.