Manuscript Offprint
arXiv:2610.38311Detecting Incorrect LLM Explanations for Automated Program Repair
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Lam Nguyen Tung
Monash University
Melbourne, Australia
Chenxi Gu
Monash University
Melbourne, Australia
Xiaoning Du
Monash University
Melbourne, Australia
Haoye Tian
Aalto University
Espoo, Finland
Aldeida Aleti
Monash University
Melbourne, Australia
Neelofar Neelofar
RMIT University
Melbourne, Australia
Abstract—LLM-generated explanations are important in automated program repair (APR), as they enable developers to understand repair rationale and assess patch quality. Their correctness can directly affect how developers respond to repairs. For instance, incorrect explanations may signal unreliable repairs that fail to fix bugs. Thus, detecting incorrect explanations is essential to help developers focus on reliable repairs. However, manual detection is impractical due to the growing number of LLM-generated repairs. Automated detection is therefore necessary to filter explanations presented to developers.
Prior methods mainly detect incorrect responses of general question-answering LLMs, not APR explanations. They often sample responses and identify contradictions among them. In APR, they face two limitations: (1) to identify contradictions, they often rely on external verifiers, which may not exist or lack APR-specific reasoning; (2) their sampling techniques, e.g., paraphrasing or same-input re-prompting, tend to produce superficial or redundant samples. Such methods may reproduce the original incorrect explanation, failing to expose it via contradictions.
We propose MetaReJ, a new metamorphic testing approach and the first detection method for incorrect APR explanations. To avoid reliance on external verifiers, MetaReJ adopts a metamorphic argumentative strategy inspired by debate and viva examination to challenge the LLM's explanation. Using novel metamorphic relations (MRs), MetaReJ recursively questions the LLM under equivalent and non-equivalent repair scenarios and captures contradictions in its responses. To mitigate superficial sampling, MetaReJ leverages program transformations. It transforms the original buggy program into different variants that either preserve or alter the underlying bug. It then samples explanations by asking the LLM how to fix the transformed variants. This technique produces more diverse and non-redundant samples, making it easier to expose contradictions. Such contradictions are encoded as MR violations. If the LLM's responses violate the MRs, MetaReJ flags the original explanation as incorrect. To evaluate MetaReJ, we constructed a manually-labeled dataset of 1,756 explanations of multiple LLM-based APR systems. Experiments show that MetaReJ achieves up to 0.43 in MCC, outperforming prior methods by 333.3% in MCC.
Index Terms—Program Repair, Explanation, Metamorphism
I. INTRODUCTION
Large language models (LLMs) have advanced automated program repair (APR), achieving state-of-the-art (SOTA) re-pair success rates of up to 70% on existing benchmarks [1]–[3]. Despite this, developers still prefer to remain involved in the repair process, mainly due to the lack of trust in fully automated repairs [4], [5]. Building such trust requires developers to understand not only the generated patch, but also the rationale behind it [6], [7]. LLM-provided explanations offer a useful mechanism for communicating the LLM's repair rationale to developers [8]. This helps developers assess the quality of the generated repairs [9]. The correctness of explanations may influence how developers act on the repairs. For example, incorrect explanations indicate unreliable repairs that fail to fix bugs and should be disregarded. Hence, detecting incorrect explanations is essential in LLM-based APR. However, it is overwhelming for developers to detect them manually, as the number of LLM-generated repairs continues to grow extensively [1], [2]. This creates a need for automated detection of incorrect explanations. Such automation reduces the number of explanations presented to developers, alleviates review burden, and facilitates the repair process.
No available method detects incorrect APR explanations. Most methods identify if the final answers of LLMs in general question-answering tasks are incorrect. These methods often sample multiple responses and identify if these responses contradict one another [10], [11]. For example, SelfCheckGPT [10] re-prompts the LLM with the same query and compares the new responses with the original using semantic similarity metrics or external LLMs. MetaQA [11] and DrHall [12] paraphrase the response and identify contradictions among the paraphrased versions.
Unfortunately, existing methods are not well-suited or effective for APR explanations. We identify two key limitations. First, methods like SelfCheckGPT rely on external verifiers to identify contradictions. In APR, such verifiers often do not exist or lack APR-specific knowledge. Second, existing methods sample explanations by re-prompting LLMs with the same input or by paraphrasing the explanation. Such sampled explanations are often low-diversity or only superficially different at the word level. They may preserve incorrectness rather than revealing it through contradictions [11].
Exhaustively detecting incorrect explanations is a non-trivial task. Hence, we take a step toward mitigating manual review effort and facilitating the APR process. We achieve this by mitigating the two limitations. We propose MetaReJ, a new metamorphic testing method and the first approach for detecting incorrect APR explanations. To mitigate the first limitation, we adopt a metamorphic argumentative strategy to challenge the LLM's explanation. Rather than relying on external verifiers, MetaReJ probes whether the LLM can defend itself under a series of recursive questions without providing contradictory responses. Intuitively, reliable reasoning for generating a correct explanation should transfer to and support these probing questions. In contrast, unreliable reasoning is more likely to surface as contradictions.
This argumentative strategy is inspired by debate and viva examination. A given claim is not directly judged by outside knowledge or understanding. The adopted strategy treats the claim as a premise. The claim-giver then responds to a series of recursive questions to determine whether later responses reinforce or contradict that premise. In this way, the claim-giver is challenged using their own claims, assumptions, or logic. Analogously, we treat the LLM as the claim-giver. The original explanation and patch are considered the claim. MetaReJ questions the LLM to generate sampled explanations and then to verify if these explanations apply to the original program. Metamorphic relations (MRs) are introduced to design such questions and represent the expected responses.
To mitigate the second limitation, we do not apply prior superficial sampling techniques. Instead, we apply diverse, non-redundant transformations at the program level. We transform the original buggy program in terms of syntax or semantics. We then sample explanations by asking the LLM how to fix the transformed programs. These explanations, referred to as follow-up explanations, will inevitably be transformed accordingly. This allows MetaReJ to mitigate the repetition of superficial or redundant sampled explanations.
We encode program transformations in two MRs to generate and evaluate follow-up explanations. Explanations for fixing semantically equivalent programs apply to the original program. Explanations for fixing semantically non-equivalent programs should not apply, as they have different bugs. The LLM is expected to satisfy these MRs.
Given these two MRs, MetaReJ performs the metamorphic argumentative strategy in three steps. First, it transforms the original buggy program using semantic-preserving and semantic-altering transformations. Second, it asks the LLM to generate follow-up explanations for fixing the transformed programs. Third, it asks the same LLM to evaluate if these explanations satisfy the MRs. Our key insight is that the LLM's explanation is incorrect if the LLM's responses are likely to violate the MRs. Such violations mean the LLM contradicts itself about fixing the buggy program, likely to generate an incorrect explanation.
To effectively adopt the metamorphic argumentative strategy, we also explicitly provide the LLM with the original
patch as the context when generating follow-up explanations. This is the critical step: it prepares the LLM to be examined, sets up the premise, and anchors follow-up explanations to the same original patch. By doing so, contradictions can be unambiguously traceable back to the original explanation. Otherwise, the strategy may freely generate follow-up explanations that introduce brand new claims. These explanations are therefore less commensurable with the original one. This makes it difficult to determine if apparent contradictions are truly due to the original explanation or to the new claims. Hence, this weakens the logical foundation of the metamorphic argumentative strategy, as used in debate or viva examination.
As detecting incorrect APR explanations is not trivial, MetaReJ is designed to be high-precision while increasing the chances of detecting them. Its metamorphic argumentative strategy can improve precision by avoiding external verifiers, which introduce a new source of uncertainty that may cause false contradictions. MetaReJ derives contradictions from the LLM's own reasoning, providing stronger evidence of incorrect explanations. The improvement in precision, however, comes with a potential loss in recall. MetaReJ may fail when the LLM is stubborn and consistently defends its incorrect reasoning. By using program transformations, we mitigate the second limitation but also compensate for the loss in recall and further strengthen it by diversifying the sampling.
To evaluate MetaReJ, we create a manually-labeled dataset of APR explanations. These explanations are collected from three SOTA systems: ThinkRepair [13], ReInFix [1], and MORepair [14] on the respective bug datasets used in the original studies. These studies had already mitigated data leakage. We formulated the detection of incorrect explanations as a binary classification problem. Our experiments show that MetaReJ achieves on average Precision of 0.92, Recall of 0.64, and MCC (Matthew Correlation Coefficient [15]) of 0.39. It also outperforms the SOTA methods designed for general question-answering by up to 30.0% in Precision, 536.4% in Recall, and 333.3% in MCC.
Our main contributions can be summarised as follows:
The first benchmark of the correctness of explanations generated by LLM-based APR systems,
-
MetaReJ, the first approach that detects incorrect explanations of LLM-based APR systems,
-
A comprehensive evaluation of MetaReJ on the constructed benchmark, which shows that MetaReJ improves methods designed for general question-answering by up to 30.0% in Precision, 536.4% in Recall, 333.3% in MCC,
• The dataset and implementation are available at https://doi.org/10.5281/zenodo.21059953.

Fig. 1: A motivating example: Two different repairs A and B (left side) generated by ThinkRepair [13] and ReInFix [1], respectively, for fixing JacksonCore-8 in Defects4J [16]. Repair A provides an incorrect explanation ExplA0 and a plausible but incorrect patch. Repair B provides both a correct explanation ExplB0 and a correct patch. MetaReJ can classify ExplA0 as incorrect and ExplB0 as correct (right side).
A. Motivating Example
The left side of Figure 1 shows the buggy program getTextBuffer, also known as JacksonCore-8 in Defects4J [16]. The bug arises in how the single-segment case is handled if (!_hasSegments) return _currentSegment; When only one segment exists, the program returns _currentSegment without checking if it is null. To fix JacksonCore-8, ThinkRepair [13] and ReInFix [1], two SOTA LLM-based APR systems, generate two repairs A and B, respectively. In each repair, the system generates a patch and an explanation.
As expressed in natural language, the explanations are useful to help developers understand the repair rationale and review patch quality. ThinkRepair's explanation, ExplA0, reveals its flawed reasoning, suggesting that this repair is unreliable. The if (!_hasSegments) branch is supposed to handle the single-segment case. ThinkRepair incorrectly thinks that returning _currentSegment is buggy in this case. In fact, if there is only one segment, _currentSegment may truly contain the correct content, and returning it is correct. On the other hand, ReInFix's explanation, ExplB0, is correct. It correctly identifies the potential null pointer exception. The suggestion in this explanation is also correct, adding a null check on _currentSegment before returning it.
Based on the explanations, ReInFix's repair is clearly more reliable than ThinkRepair's. Indeed, ThinkRepair's patch turns out to be incorrect, although it is plausible by passing all available test cases. In this case, the test cases may be
incomplete and the patch is overfitting. In contrast, ReInFix's patch is correct, successfully eliminating the bug.
This example demonstrates that incorrect explanations of LLM-based APR systems help developers disregard unreliable repairs. However, manually detecting them requires a lot of effort and is inherently impractical, given the growing number of LLM-generated repairs. This motivates the need for automated detection methods like MetaReJ to reduce developer effort.
The right side of Figure 1 illustrates MetaReJ's metamorphic argumentative strategy, where it correctly classifies ExplA0 as incorrect and ExplB0 as correct. First, it applies semantic-preserving and semantic-altering transformations to getTextBuffer to produce multiple transformed buggy programs Program1, Program2, ..., ProgramN¹. For instance, MetaReJ generates semantically equivalent Program1 by rewriting the code using nested if-else blocks. In contrast, MetaReJ generates semantically non-equivalent Program2 by changing _inputStart >= 0 to _inputStart > 0. Details about these transformed programs can be found in Supplementary Material A.
Under the two MRs, MetaReJ asks each APR system to explain how to fix the transformed programs. For example, ThinkRepair generates ExplA1 for Program1 and ExplA2 for Program2. ReInFix generates ExplB1 for Program1 and ExplB2 for Program2. ExplA1 and ExplB1 describe the same
¹Due to page limitation, we illustrate only one equivalent transformed program and one non-equivalent transformed program rationale as ExplA0 and ExplB0, respectively, while ExplA2 and ExplB2 illustrate rationales different from them.
MetaReJ then asks each system if each follow-up explanation applies to the original getTextBuffer. We expect these systems to think that ExplA1 and ExplB1 also fix getTextBuffer, and ExplA2 and ExplB2 do not. However, ThinkRepair fails to satisfy these relations when assessing ExplA1 and ExplA2. It incorrectly answers “No” for ExplA1, thinking it is not applicable to getTextBuffer. It also incorrectly answers “Yes” for ExplA2, even though ExplA2 is derived from fixing a different bug. Since all ThinkRepair’s responses violate the two MRs, its violation score is 1. MetaReJ classifies ExplA0 as incorrect. In contrast, ReInFix’s responses consistently satisfy the MRs. ReInFix answers “Yes” for ExplB1 and “No” for ExplB2, as expected. Hence, its violation score is 0 and MetaReJ classifies ExplB0 as correct.
B. Metamorphic Testing
Metamorphic testing [17] addresses the oracle problem [18], where expected outputs are unavailable. Instead of directly verifying output correctness, it generates follow-up inputs and checks whether the resulting outputs satisfy predefined MRs. In this setting, the test oracle becomes if the MRs are satisfied.
Formally, an MR is a property between a set of inputs and their outputs for a function . It can be denoted as [18]. Essentially, an MR specifies how a system should behave under specific transformations to the inputs. If the system’s outputs violate the MRs, it indicates that the system may produce incorrect outputs.
MRs have been applied in traditional software testing [18], [19]. More recently, research has defined MRs to classify the factual correctness of information produced by NL question-answering systems, including LLMs [11], [12], [20], [21]. However, their application to explanation correctness, particularly in coding tasks like APR, remains underexplored.
As far as we know, this work is the first to leverage MRs to detect incorrect APR explanations. Inspired by debate and viva examination, we introduce a metamorphic argumentative strategy that exposes contradictions in an LLM’s responses. MRs design recursive questions to challenge the LLM and encode its expected responses. MR violations represent contradictions in the LLMs’ bug-fixing reasoning. Such violations are more likely when the original explanation is incorrect.
III. METAREJ: THE PROPOSED DETECTION METHOD
In this section, we describe MetaReJ, the first method for detecting incorrect APR explanations. MetaReJ adopts a metamorphic argumentative strategy. This strategy is inspired by debate and viva examination, where a claim acts as a premise under examination. In APR, the LLM is considered the claim-giver; the original repair is treated as the claim.
Let represent the LLM-based APR system under test. We denote by Prog the set of programs that implement a function, and by Expl the set of textual explanations that describe LLM reasoning. Let be the buggy program,

Fig. 2: An explanation and patch are generated by the LLM under test for fixing the buggy program. MetaReJ performs the metamorphic argumentative strategy to determine if the explanation is incorrect. First, it transforms the buggy program into multiple equivalent and non-equivalent variants. Next, MetaReJ asks the LLM to explain how to fix each transformed variant, given the originally generated patch as the argumentative context. This produces a set of follow-up explanations. MetaReJ then asks the LLM whether each follow-up explanation applies to the original buggy program. Based on whether the LLM’s responses violate the MRs, MetaReJ calculates a violation score and uses it to detect if the original explanation is incorrect.
be the original explanation, and be the original patch. In this case, the repair can be considered as the given claim. Given this repair, MetaReJ’s goal is to detect if the generated explanation is incorrect.
Figure 2 illustrates the process of MetaReJ. It recursively questions the LLM under equivalent and non-equivalent repair scenarios, and exposes contradictions in the LLM’s responses. The process consists of four main steps: program transformation, follow-up explanation generation, follow-up explanation verification, and violation score calculation. These steps are described in III-A, III-B, III-C, and III-D, respectively.
A. Program Transformation
This step aims to transform the original buggy program into a diverse set of semantically equivalent and non-equivalent buggy programs. We define and for preserving and altering the semantics of a program, respectively. They are modeled as two functions that map each program
to a corresponding set over . Formally, for all :
A transformed program sampled from or for x is thus modeled by a variable as follows:
where is semantically equivalent to x, sharing the same underlying bug, while is not.
Program transformations have been extensively studied in prior research, including APR [22]. Hence, we reuse the existing transformations. Ultimately, we select 40 semantic-preserving and 20 semantic-altering transformations. Supplementary Material C describes the detailed process of collecting transformations, and provides the list of transformations.
MetaReJ aggregates the selected transformations to generate transformed programs. To validate the transformed programs, we compile and run them against the available test cases. Equivalent programs are expected to fail the same test cases as the original buggy program, whereas non-equivalent programs should fail different test cases. Programs that do not satisfy this criterion are discarded. The remaining programs are then used for follow-up explanation generation.
B. Follow-up Explanation Generation
Given the curated transformed programs, MetaReJ instructs the LLM m to generate follow-up explanations. This process is designed to simulate the argumentative strategy used in debates or viva examinations. To effectively adopt this strategy, the claim-giver must be aware of the claim as a premise. Otherwise, the claim-giver may bring up new claims that bear no logical relationship to the premise. It is difficult to determine if contradictions stem from the original or the new claims. This weakens the logical foundation of the argumentative strategy. Hence, we do not repeat the original repair pipeline to produce follow-up explanations. We design a repair sub-task that prepares the LLM for the argumentative strategy. It explicitly provides the original patch y as the context to set up the premise and anchor follow-up explanations to y.
We denote this sub-task by as a function that maps each pair of a transformed buggy program and the originally generated patch to a follow-up explanation . Formally, for all :
where or .
To implement , we embed the original patch directly into the prompt and ask to explain how to fix the transformed program based on the given patch . Supplementary Material D shows the prompt template for follow-up explanation generation for transformed programs.
C. Follow-up Explanation Verification
In this step, MetaReJ asks the LLM under test to verify whether each follow-up explanation applies to the original buggy program . We model this verification task performed by as . It is a function that maps a pair of the follow-up explanation and the buggy program to . The value of 1 indicates that the model thinks the explanation can be applied to the program , and 0 otherwise. Formally, for all :
This verification task can be performed through a straightforward question-answering process. Specifically, MetaReJ uses a prompt-based method that allows the LLM m itself to rigorously assess whether the explanation is applicable to the buggy program. The prompt template shown in Supplementary Material D is used to guide the LLM in generating precise responses to enhance the overall reliability of MetaReJ.
If the original explanation r is correct, the follow-up explanations derived from equivalent programs are expected to return “Yes” when verified, and those derived from non-equivalent programs should return “No.” When the LLM is uncertain about the correctness of a follow-up explanation, MetaReJ instructs it to return “Not Sure.”
D. Violation Score Calculation
The goal of this step is to enhance the testing of LLM explanations by analyzing the violations of the two MRs. The MRs can be modeled as follows.
MR1. Explanations derived from equivalent programs that lead to the same patch also apply to the original program.
where and . Violating MR1 means while m fixes a program semantically equivalent to x using , m does not think is applicable to x.
MR2. Explanations derived from non-equivalent programs do not apply to the original program.
where and . Violating MR2 means that m believes both and r are applicable to x, even though they are derived from fixing semantically different programs.
For the same LLM m, verifying explanations is inherently no more difficult than generating a correct one. This is because, from a complexity perspective [23], explanation generation requires m to search over an extremely large space to produce a correct explanation. Therefore, if m generates a correct explanation, it will provide verification results satisfying the expected outcome specified by the MRs. Our empirical results in Supplementary Material B support this assumption. When the LLM generates a correct explanation, it verifies explanations correctly with a probability of 0.90 (close to 1). Moreover, verification failures are rare when the LLM generates correct explanations, while verification still often succeeds even when the LLM generates incorrect explanations. These results show that verifying explanations is almost always no more difficult than generating them. Hence, verification failures, which are encoded as MR violations, strongly imply that the LLM generates an incorrect explanation.
We define the violation score of the two MRs as follows.
Based on this, the violation score provides a lower bound on the incorrectness probability:
Supplementary Material B provides detailed theoretical and empirical proofs. In this study, we consider as incorrect if , implying . Consequently, this approach provides a statistically sound way to identify incorrect explanations without access to ground truths.
Practical consideration: Program transformations and are typically inexpensive. However, generating follow-up explanations may be costly, as it requires querying the LLM multiple times. To reduce this cost, we adopt a fixed sampling budget strategy. Given a budget , we draw N follow-up explanations for N equivalent programs and N follow-up explanations for N non-equivalent ones. To enhance the diversity of this sampling, MetaReJ selects the most representative transformed programs. It clusters each list of equivalent and non-equivalent transformed programs into N clusters, and randomly chooses one in each cluster as a representative example. Details about the clustering process are provided in Supplementary Material F-1. The value of N will be analysed through a sensitivity analysis in RQ4.
Given the budget , we define an empirical violation score that approximates described in Equation 10.
where is the indicator function, which returns 1 when the predicate holds and 0 otherwise. Let represent the verification response for the follow-up explanation . only returns 0 or 1, while can receive three values. To map these values, we design a mechanism that assigns a numeric score for each follow-up explanation on a scale of [0, 1] based on its verification response . “Not Sure” is considered equally likely to indicate whether the explanation is correct or not, thus receiving a score of 0.5. The scores are mapped as follows:
The empirical violation score approximates the original violation score while avoiding repeated expensive LLM queries. As N increases, the estimation of the violation score becomes more faithful. While this approximation introduces some additional variance, it is highly effective in practice [10], [11]. It amortizes LLM sampling costs across many evaluations, enabling scalable violation estimation.
According to Equation 11, we consider the original explanation as incorrect if . The value of the threshold will be identified through sensitivity analysis in RQ4.
IV. EXPERIMENTAL DESIGN
We study the following research questions (RQs):
RQ1. To what extent do SOTA LLM-based APR systems produce incorrect explanations?
RQ2. How effective is MetaReJ in detecting incorrect explanations of LLM-based APR systems?
RQ3. How efficient is MetaReJ in detecting incorrect explanations of LLM-based APR systems?
RQ4. How do the parameters N and impact MetaReJ?
RQ5. How does each component influence MetaReJ?
To measure detection quality, we use standard binary classification metrics. In particular, we adopt the Matthews Correlation Coefficient (MCC) as it considers all four components of the confusion matrix, and produces more reliable statistical results than F1-score [15]. We also report Balanced Accuracy (BA), Precision (Pre), Recall (Rec), also known as True Positive Rate, and Specificity (Spe), also known as True Negative Rate. To measure efficiency, we report the number of input tokens, output tokens, and total tokens.
A. Hyperparameters
In MetaReJ, we set the LLM's temperature to 0 when generating and verifying follow-up explanations to enhance stability. RQ4 investigates the optimal values of N and , while other RQs use their default values, 5 and 0.5, respectively. The implementation of program transformations is reused from Le et al.'s work [22]. We performed three runs per experiment.
B. Baselines for Detecting Incorrect Explanations
Several detection approaches rely on databases, search engines [24], or internal access to LLMs [25]. As they are often unavailable, these approaches are unsuitable as baselines. Consequently, we compare MetaReJ with the following methods.
• SelfCheckGPT [10]: an SOTA task-agnostic, zero-resource approach for checking the correctness of an LLM's response. It repeatedly queries the LLM to generate multiple samples and measures their consistency with the original response. Following the prior setting [11], we set the LLM's temperature to 0.5 when sampling, which yields the best performance.
-
MetaQA [11]: a method for detecting incorrect facts generated by an LLM for general question-answering. It paraphrases the originally generated fact, then checks if the paraphrases remain valid. For APR, we adapt MetaQA by using the LLM under test to paraphrase the original explanation. We use the same setting as the original study.
-
DrHall [12]: a metamorphic testing method for detecting incorrect facts generated by an LLM for general question-answering. Since most of its MRs are not applicable to APR, we only consider AMR1, which asks the LLM a follow-up question "[Original Answer] Is this statement not true?" We use the same setting as the original study.
-
SelfCheck w/ ProgTrans: an extension of SelfCheckGPT. It samples responses using transformed programs instead of re-querying the LLM with the same input. It uses the same set of transformed programs as MetaReJ.
C. Studied Models (LLMs Under Test)
We aim to select LLM-based APR systems published within the past five years at top venues in SE, such as conferences (e.g., ICSE, FSE, ASE, ISSTA) and journals (e.g., TOSEM, TSE, EMSE). We focus specifically on systems that can produce explanations. At the time of writing, only a limited number of such systems are available, as most existing systems only generate patches. Three systems are selected:
-
ThinkRepair [13]: A self-directed LLM-based APR approach. ThinkRepair first gathers CoTs as repair knowledge. It then repairs bugs via few-shot example selection, iterative LLM interaction, and testing feedback. We use CodeLlama 13B as the underlying model, the best-performing open-source LLM in the original study.
-
ReinFix [1]: An agentic framework that enables LLMs to autonomously search for repair ingredients throughout both the reasoning and solution phases of bug fixing. ReinFix employs GPT-4o as the underlying LLM.
-
MOREpair [14]: A novel perspective on LLM fine-tuning for APR. It not only adapts model parameters to the syntactic nuances of code transformation but also fine-tunes the model to capture the underlying logic behind code changes in the training data. We use CodeLlama 13B as the underlying LLM, as in the original study.
D. Benchmark Construction
To answer RQ1, we constructed a benchmark of the correctness of explanations generated by LLM-based APR systems.
- Data leakage: All three original studies [1], [13], [14] evaluated their APR systems on Defects4J [16]. To mitigate potential data leakage, they also evaluated their systems on benchmarks constructed after the LLMs' cutoff dates. ThinkRepair and ReinFix were evaluated on RWB [13], while MOREpair was evaluated on SWE-Repair (a subset of SWE-Bench [26]), EvalRepair-C++, EvalRepair-Java [14]. Regardless, as we do not train an LLM and program transformations are used, data leakage has limited impact on MetaReJ.
TABLE I: Benchmarking explanations generated by LLM-based APR systems
| APR System Under Test | # Expls | # Correct Expls | # Incorrect Expls | Incorrect Expl Rate |
|---|---|---|---|---|
| ThinkRepair [13] | 431 | 54 | 377 | 87.5% |
| ReInFix [1] | 711 | 305 | 406 | 57.1% |
| MOREpair [14] | 614 | 180 | 434 | 70.7% |
| Total | 1,756 | 539 | 1,217 | 69.3% |
-
Prediction collection: The original evaluations of the studied systems have already performed data cleaning to avoid data leakage. Therefore, we directly replicated their experiments using the original settings. Specifically, both ThinkRepair and ReinFix were evaluated on Defects4J and RWB datasets, producing 556 and 720 repairs. MOREpair was evaluated on Defects4J, EvalRepair-C++, and EvalRepair-Java, and SWE-Repair, producing 902 repairs.
-
Data cleaning: We excluded incomplete responses, resulting in 432, 711, and 615 completed responses from ThinkRepair, ReinFix, and MOREpair, respectively. We further removed duplicates based on their MD5 hash code. Ultimately, we curated 1,756 responses of patches and explanations, including 431, 711, and 614 from ThinkRepair, ReinFix, and MOREpair, respectively.
-
Data Labeling: In this step, we labeled the correctness of 1,756 APR explanations. Two annotators, each with 3–5 years of experience in programming and program repair, were assigned to independently label them. For each explanation, the annotators were given the buggy program, the developer's patch, the LLM's explanation, the LLM's patch, and the auxiliary information such as the bug report and triggering tests. They were instructed to review these artifacts to understand the bug. Then, they judged whether the explanation is correct and indicated their confidence on a five-point Likert scale. If one of them was unsure or the two annotators disagreed, a third annotator with over five years of relevant experience participated in the discussion to reach a consensus. Details about the labeling process are described in Supplementary Material E. Table I shows the final results.
V. EXPERIMENTAL RESULTS
A. RQ1: Benchmark
The annotation process achieves a Cohen's Kappa value [27] for inter-annotator agreement of 0.78, indicating substantial consistency and reliability. This has significantly bolstered our confidence in both the benchmark's quality and the evaluation of the detection approach, MetaReJ.
Table I shows the results of the labeling process. It is clear that many generated explanations are incorrect. Among 1,756 explanations produced, 1,217 are incorrect, accounting for 69.3% of all explanations. This shows that the systems are still highly unreliable for explaining their repairs, even the best-performing agentic system, ReinFix. A breakdown of the benchmark is shown in Supplementary Material F-3.
TABLE II: The effectiveness in detecting incorrect APR explanations of MetaReJ and the other methods.
| APR System Under Test | # Expls | Detector | Detection Quality | Tokens (Millions) | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| MCC↑ | ΔMCC↑ | BA↑ | Pre↑ | Rec↑ | Spe↑ | Input | Output | Total | |||
| ThinkRepair [13] | 431 | SelfCheckGPT [10] | 0.05* | -50.0% | 0.53* | 0.89* | 0.38* | 0.68° | 8.96 | 4.89 | 13.85 |
| SelfCheck w/ ProgTrans | 0.10* | 0% | 0.56* | 0.89* | 0.75 | 0.36* | 9.15 | 4.97 | 14.12 | ||
| MetaQA [11] | -0.02* | -120.0% | 0.49* | 0.87* | 0.37* | 0.61* | 4.06 | 2.55 | 6.61 | ||
| DrHall [12] | -0.06* | -160.0% | 0.49* | 0.87* | 0.98* | 0.00* | 0.29 | 0.17 | 0.46 | ||
| MetaReJ (ours) | 0.34 | +240.0% | 0.75 | 0.96 | 0.72 | 0.77 | 9.19 | 5.20 | 14.39 | ||
| MetaReJ w/ ext. Claude | 0.25* | +150.0% | 0.68* | 0.92 | 0.75° | 0.60* | 9.30 | 5.11 | 14.41 | ||
| MetaReJ w/o non-eqv. | 0.08* | -20.0% | 0.56* | 0.92° | 0.31* | 0.80* | 4.54 | 2.57 | 7.11 | ||
| MetaReJ w/o eqv. | 0.23* | +130.0% | 0.64* | 0.91* | 0.83* | 0.45* | 4.65 | 2.63 | 7.28 | ||
| ReInFix [1] | 711 | SelfCheckGPT [10] | 0.17* | 0% | 0.54* | 0.92* | 0.09* | 0.99° | 30.41 | 2.52 | 32.93 |
| SelfCheck w/ ProgTrans | -0.07* | -141.2% | 0.47* | 0.55* | 0.70* | 0.24* | 32.58 | 2.45 | 35.03 | ||
| MetaQA [11] | 0.16* | -5.9% | 0.57* | 0.72* | 0.27* | 0.86° | 7.43 | 4.67 | 12.1 | ||
| DrHall [12] | 0.12* | -29.4% | 0.54* | 0.72* | 0.19* | 0.90* | 0.52 | 0.28 | 0.80 | ||
| MetaReJ (ours) | 0.43 | +152.9% | 0.70 | 0.88 | 0.50 | 0.91 | 15.08 | 8.60 | 23.68 | ||
| MetaReJ w/ ext. Claude | 0.29* | +70.6% | 0.64* | 0.76* | 0.48 | 0.80* | 15.12 | 7.35 | 22.47 | ||
| MetaReJ w/o non-eqv. | 0.20* | +17.6% | 0.57* | 0.79* | 0.23* | 0.92 | 7.59 | 4.11 | 11.70 | ||
| MetaReJ w/o eqv. | 0.18* | +5.9% | 0.58* | 0.63* | 0.77* | 0.40* | 7.49 | 4.49 | 11.98 | ||
| MORepair [14] | 614 | SelfCheckGPT [10] | 0.09* | 0% | 0.53* | 0.84* | 0.11* | 0.95* | 9.31 | 5.12 | 14.43 |
| SelfCheck w/ ProgTrans | -0.14* | -255.6% | 0.45* | 0.68* | 0.82* | 0.07* | 9.39 | 5.25 | 14.64 | ||
| MetaQA [11] | -0.01* | -111.1% | 0.50* | 0.70* | 0.48* | 0.51* | 5.15 | 5.86 | 11.01 | ||
| DrHall [12] | 0.08* | -11.1 | 0.54* | 0.75* | 0.45* | 0.64° | 0.33 | 0.59 | 0.92 | ||
| MetaReJ (ours) | 0.39 | +333.3% | 0.71 | 0.91 | 0.70 | 0.72 | 9.44 | 8.50 | 17.94 | ||
| MetaReJ w/ ext. Claude | 0.36° | +300.0% | 0.70 | 0.83* | 0.79° | 0.60* | 10.34 | 7.41 | 17.75 | ||
| MetaReJ w/o non-eqv. | 0.06* | -33.3% | 0.52* | 0.79* | 0.11* | 0.93* | 4.24 | 3.85 | 8.09 | ||
| MetaReJ w/o eqv. | 0.02* | -77.8% | 0.50* | 0.71* | 0.92* | 0.09* | 5.20 | 4.65 | 9.85 | ||
Abbreviations: MCC = Matthews Correlation Coefficient, ΔMCC: Relative MCC Improvement Over the Best Baseline, BA = Balanced Accuracy, Pre = Precision, Rec = Recall, Spe = Specificity. Paired t-test between MetaReJ and other methods, with ∅: p-value < 0.05, *: p-value < 0.01.
RQ1: All APR systems frequently generate incorrect explanations, with an overall incorrect rate of 69.3%.
B. RQ2: Detection Effectiveness of MetaReJ
In RQ2, we examine whether MetaReJ can achieve better effectiveness in detecting correct explanations than the baselines. Table II compares their effectiveness across three LLM-based APR systems: ThinkRepair, ReInFix, and MORepair.
Overall, the baselines achieve poor effectiveness. Self-CheckGPT is the strongest baseline on ReInFix and MORepair in terms of MCC (0.17 and 0.09, respectively). The main issue is its low Recall of 0.09–0.38, despite high Specificity of 0.69–0.99. This means SelfCheckGPT misclassifies many incorrect explanations as correct. MetaQA is generally unstable and close to random. It achieves MCC of -0.02–0.01 on ThinkRepair and MORepair, only getting better MCC of 0.16 on ReInFix. MetaQA's Recall is low (0.27–0.48), showing that it misses many incorrect explanations. DrHall is the poorest baseline, with MCC of -0.06–0.12.
Adding program transformations into SelfCheckGPT, as expected, improves Recall by 97.4%–677.8% but severely hurts Specificity by 47.1%–92.6%. This causes MCC to become negative on ReInFix (-0.07) and MORepair (-0.14). SelfCheck w/ ProgTrans tends to over-detect explanations as incorrect, failing to identify many correct ones.
In contrast, MetaReJ consistently achieves strong effectiveness across the APR systems. It achieves 0.34–0.43 in MCC and 0.70–0.75 in BA. Compared with the best baseline on each APR system, MetaReJ improves MCC substantially by up to 580.0%. MetaReJ maintains relatively higher Precision of 0.88–0.96 and much higher Recall of 0.50–0.72. These results contrast with SelfCheckGPT and MetaQA, with lower Precision and Recall, and DrHall, which can achieve high Precision and Recall by always classifying explanations as incorrect. Therefore, MetaReJ provides a better balance between detecting incorrect explanations.
RQ2: MetaReJ consistently outperforms the baselines in detection quality across all APR systems and bug datasets. It achieves an improvement of up to 333.3% in MCC over SelfCheckGPT, the best detection baseline.
C. RQ3: Token Usage
Since MetaReJ involves multiple rounds of LLM queries, it may consume more tokens than direct LLM prompts. We quantify this increase and investigate the trade-off between token use and detection quality. Table II provides the token usage across detectors and APR systems. For each detector, we measure the input tokens, the output tokens, and total tokens.
SelfCheckGPT and SelfCheck w/ ProgTrans consume tokens comparable to MetaReJ on ThinkRepair and MORepair. On ReInFix, they consume 0.48 times more tokens on average than MetaReJ, due to the design of ReInFix's query. MetaReJ consumes 0.92 times more tokens than MetaQA and 25.79 times more tokens than DrHall, two more direct prompting methods. These results reveal a clear trade-off between computational cost and detection effectiveness. MetaReJ consumes comparable or more tokens than most baselines, but justifies that cost by superior detection effectiveness.
RQ3: MetaReJ consumes similar or even fewer tokens than SelfCheckGPT by 0.39 times. It consumes 0.92 times more tokens than MetaQA and 25.79 times more tokens than DrHall. MetaReJ's superior performance boost sometimes comes at the cost of increased token usage.
D. RQ4: Sensitivity Analysis
RQ4 further investigates the sensitivity of MetaReJ to two thresholds, and N, across the APR systems. Figure 3 shows MetaReJ's effectiveness with different values of . Across all APR systems, MetaReJ achieves the best MCC consistently around . When is small, Precision remains low, while Recall is high. This indicates that MetaReJ relaxes the detection condition and tends to detect explanations as incorrect. As increases, Precision improves rapidly while Recall decreases. However, after , Recall drops substantially, meaning that more incorrect explanations are misclassified as correct. This degradation is reflected in MCC, which decreases after for all systems. These results suggest that provides the best detection for incorrect explanations.
Figure 4 shows MetaReJ's effectiveness with different values of N. Increasing N generally improves MCC and Precision across all three APR systems, while Recall changes only slightly. This indicates that sampling more explanations helps MetaReJ detect incorrect explanations more effectively. The gains are most evident from N = 1 to N = 5. After N = 5, MetaReJ's effectiveness becomes more stable.
RQ4: MetaReJ shows a clear trade-off between Precision and Recall as changes: increasing improves Precision but reduces Recall. achieves the balance with the best MCC. MetaReJ's effectiveness is improved when increasing N and becomes more stable when .
E. RQ5: Ablation Study
We conduct an ablation study to understand the contribution of MetaReJ's three components: identifying contradictions by the same LLM, the equivalent questioning, and non-equivalent questioning. We develop three variants of MetaReJ. The first one relies on an external LLM to identify contradictions instead of using the same LLM. Claude Opus 4.5 (claude-opus-4-5-20251101) is selected as it is the best LLM for SE and is different from the LLM families used in APR systems. The next two variants only use the equivalent questioning or non-equivalent questioning, respectively. The results show that all components are necessary for MetaReJ's detection quality. Removing a component consistently degrades MCC and balanced accuracy across all three APR systems.
When MetaReJ relies on Claude Opus 4.5 to identify contradictions, its MCC decreases by up to 32.6%. This variant often achieves slightly higher Recall of 0.75–0.79, except for lower Recall of 0.48 on ReInFix. It achieves lower Precision of 0.76–0.92 (drop by up to 13.6%) and lower Specificity of 0.60–0.80 (drop by up to 22.1%). Although its Recall is slightly better, many explanations are misclassified, leading to the overall decrease in MCC.
Compared to MetaReJ, removing the non-equivalent questioning reduces MCC by up to 84.6%. This variant often achieves high Specificity of 0.80–0.93, but at the cost of a much lower Recall of 0.11–0.31. This indicates that it tends to misclassify incorrect explanations as correct.
In contrast, removing the equivalent questioning decreases MCC by up to 94.9%. Doing so substantially harms the ability to differentiate incorrect and correct explanations. This variant often has lower Specificity, especially on MORepair, where Specificity drops to 0.09. Although it sometimes achieves higher Recall, the big drops in Specificity show that it becomes overly relaxed and often mislabels explanations as incorrect.
RQ5: When using an external LLM to identify contradictions, MetaReJ maintains slightly higher Recall but achieves lower Precision. This leads to the overall decrease in MCC of up to 32.6%. Additionally, both equivalent and non-equivalent questioning in MetaReJ are crucial. Removing them reduces MetaReJ's detection ability by up to 84.6% and 94.9% in MCC, respectively.
F. Qualitative Error Analysis
To better understand the limitations of MetaReJ, we manually analyzed a subset of misclassifications. The most common reason for incorrect explanations being misdetected is that the LLM is stubborn and consistently defends its wrong reasoning under MetaReJ. We provide a few examples in Supplementary Material F-4. This is a well-known limitation of sampling-based detection methods. Future work can explore different sampling techniques to better reveal LLMs' contradictions. On the other hand, correct explanations misclassified as incorrect are rare. As shown in Supplementary Material B, there are only a few outliers, where the LLM generates a correct explanation but incorrectly verifies the follow-up explanations.
VI. THREATS TO VALIDITY
Construct Validity: We constructed a new benchmark based on recent APR studies. They have already mitigated data leakage. In the benchmark, each record is manually labeled by at least two annotators with 3–5 years of programming and repair experience. The labeling process achieved a Cohen's Kappa of 0.78 for inter-annotator agreement. This suggests substantial consistency and reliability of labels. We acknowledge that the labeling is imperfect, leaving a small portion of mislabeled data. However, we believe the results still hold good.
Internal Validity: LLMs are inherently nondeterministic, leading to varied responses. To address this, we set the temperature to 0 and employed three runs of experiments. Another threat is data leakage. Although we do not train an LLM and program transformations are used, data leakage may have limited impact on MetaReJ. We mitigate this threat by using the experimental design in prior studies [1], [13], [14] of LLMs and datasets. They have already mitigated data leakage.



Fig. 3: MetaReJ's effectiveness with different values of across three APR systems: ThinkRepair, ReInFix, and MOREpair.



Fig. 4: MetaReJ's effectiveness with different values of across three APR systems: ThinkRepair, ReInFix, MOREpair.
External Validity: Main threats to external validity are that the selected dataset may not generalize to other programs, or that performance enhancements will not generalize to other LLMs. While the benchmark contains three different programming languages (Java, Python, and C++), future studies on alternative datasets could further validate generalizability and performance trends. We evaluated MetaReJ across three recent SOTA LLM-based APR systems, including both open-source and commercial LLMs. This broad spectrum enhances generalizability; however, different systems may yield varying results. Nevertheless, observed trends suggest broad applicability. Evaluating MetaReJ on larger and more powerful models may help assess its scalability and effectiveness.
Conclusion Validity: We interpreted the results using multiple well-established metrics: Precision, Recall, Specificity, and MCC. We also used appropriate statistical tests, such as the paired t-test, to support our findings.
VII. RELATED WORK
A. Automated Program Repair with LLMs
Novel approaches have been designed to maximize the repair potential of LLMs. Many approaches can generate correct patches for buggy programs with a success rate of up to 70% [28], [29]. In recent years, approaches have also been developed to explain what the bug is and how to fix it.
Many studies have adopted the fine-tuning paradigm [9], [14]. This allows LLMs to learn empirical knowledge used to guide bug repair from bug-fix history. For example, MOREpair [14] leverages explanations of code changes to capture the logic underlying a repair operation during fine-tuning.
In addition, researchers have utilized the prompt-learning paradigm [2], [13] to stimulate the repair potential of LLMs. They often combine LLMs with traditional APR techniques to construct specific prompt templates. For example, ThinkRe-
pair [13] enables LLMs to better implement reasoning to complete the repair by leveraging CoT prompting [30].
Recent research has entered the era of agents. Researchers have allowed LLMs to take on different task roles, further expanding the repair capabilities of LLMs. For example, AutoCodeRover [31] combines LLMs with sophisticated code search capabilities to generate patches. RepairAgent [32] enables the LLM-based agent to perform repair by invoking external tools. ReInFix [1] allows LLMs to search for repair ingredients, such as variables and historical changes, to better analyze bug causes and guide bug fixing.
B. The Detection of Incorrect LLM Responses
Incorrect responses generated by LLMs are often referred to as hallucinations. Detecting them is essential for assuring the trustworthiness of LLM-generated content. Many detection approaches have been introduced for both NL [10], [11], [33] and code artifacts [34]–[36]. A straightforward strategy is to compare the content against reliable knowledge sources [24]. However, this strategy requires curated databases, which are often unavailable and costly to construct.
To address this, prior work has explored zero-resource detection approaches. One line of work exploits LLMs' internal states [25], [37]–[39] These methods do not require external knowledge and can be computationally efficient. However, they assume access to the internal states, which are not always available. A second line of work targets black-box settings. Some methods adopt a multi-agent perspective by using additional LLMs to judge the original LLM's response [12], [33]. Others use a sampling-based approach, which is often more practical [11]. They sample multiple responses from the LLM and identify if they contradict one another. For instance, SelfCheckGPT [10] repeatedly queries the LLM and identifies contradictions. MetaQA [11] and DrHall [12] apply semantic perturbations and check if new responses remain valid.
The sampling-based methods have significantly advanced the detection of incorrect LLM-generated content, primarily in general question-answering. Unfortunately, these methods are not well-suited or effective for APR explanations. This is because detection methods need APR-specific knowledge, and the correctness of APR explanations depends on the bug and the intended program behavior. We introduce MetaReJ, a more effective detection method of incorrect APR explanations by addressing these limitations.
VIII. CONCLUSION
This work introduces MetaReJ, the first approach to detect incorrect explanations of LLM-based APR systems. Inspired by debate and viva examination, MetaReJ adopts a metamorphic argumentative strategy to identify contradictions in LLM responses. MetaReJ also applies sampling based on diverse program transformations to better reveal contradictions. Our evaluation shows significant performance improvements in detection quality. MetaReJ improves MCC by up to 333.3% over existing SOTA methods designed for general question-answering. Although MetaReJ sometimes consumes more tokens, it is an acceptable cost for improving the detection quality. Future work can define more MRs to better detect incorrect APR explanations, as well as explore the application of MetaReJ in other SE tasks.
REFERENCES
[1] J. Zhang, K. Huang, J. Zhang, Y. Liu, and C. Chen, "Repair ingredients are all you need: Improving large language model-based program repair via repair ingredients search," 2025. [Online]. Available: https://arxiv.org/abs/2506.23100
[2] C. S. Xia and L. Zhang, “Automated program repair via conversation: Fixing 162 out of 337 bugs for $0.42 each using chatgpt,” in Proceedings of the 33rd ACM SIGSOFT International Symposium on Software Testing and Analysis, ser. ISSTA 2024. New York, NY, USA: Association for Computing Machinery, 2024, p. 819–831. [Online]. Available: https://doi.org/10.1145/3650212.3680323
[3] F. Li, J. Jiang, J. Sun, and H. Zhang, “Evaluating the Generalizability of LLMs in Automated Program Repair,” in 2025 IEEE/ACM 47th International Conference on Software Engineering: New Ideas and Emerging Results (ICSE-NIER). Los Alamitos, CA, USA: IEEE Computer Society, May 2025, pp. 91–95. [Online]. Available: https://doi.ieeecomputersociety.org/10.1109/ICSE-NIER66352.2025.00024
[4] M. Böhme, E. O. Soremekun, S. Chattopadhyay, E. Ugherughe, and A. Zeller, “Where is the bug and how is it fixed? an experiment with practitioners,” in Proceedings of the 2017 11th Joint Meeting on Foundations of Software Engineering, ser. ESEC/FSE 2017. New York, NY, USA: Association for Computing Machinery, 2017, p. 117–128. [Online]. Available: https://doi.org/10.1145/3106237.3106255
[5] E. Winter, D. Bowes, S. Counsell, T. Hall, S. Haraldsson, V. Nowack, and J. Woodward, “How do developers really feel about bug fixing? directions for automatic program repair,” IEEE Transactions on Software Engineering, vol. 49, no. 4, pp. 1823–1841, 2023.
[6] F. N. Meem, J. Smith, and B. Johnson, “Exploring experiences with automated program repair in practice,” in Proceedings of the IEEE/ACM 46th International Conference on Software Engineering, ser. ICSE '24. New York, NY, USA: Association for Computing Machinery, 2024. [Online]. Available: https://doi.org/10.1145/3597503.3639182
[7] Y. Tao, J. Kim, S. Kim, and C. Xu, “Automatically generated patches as debugging aids: a human study,” in Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering, ser. FSE 2014. New York, NY, USA: Association for Computing Machinery, 2014, p. 64–74. [Online]. Available: https://doi.org/10.1145/2635868.2635873
[8] D. Khati, Y. Liu, D. N. Palacio, Y. Zhang, and D. Poshyvanyk, "Mapping the trust terrain: IIMS in software engineering - insights and perspectives," ACM Trans. Softw. Eng. Methodol., Oct. 2025, just Accepted. [Online]. Available: https://doi.org/10.1145/3771282
[9] J. Zhang, C. Wang, A. Li, W. Wang, T. Li, and Y. Liu, “Vuladvisor: Natural language suggestion generation for software vulnerability repair,” in Proceedings of the 39th IEEE/ACM International Conference on Automated Software Engineering, ser. ASE '24. New York, NY, USA: Association for Computing Machinery, 2024, p. 1932–1944. [Online]. Available: https://doi.org/10.1145/3691620.3695555
[10] P. Manakul, A. Liusie, and M. Gales, “SelfCheckGPT: Zero-resource black-box hallucination detection for generative large language models,” in Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, H. Bouamor, J. Pino, and K. Bali, Eds. Singapore: Association for Computational Linguistics, Dec. 2023, pp. 9004–9017. [Online]. Available: https://aclanthology.org/2023.empl-main.557/
[11] B. Yang, M. A. Al Mamun, J. M. Zhang, and G. Uddin, “Hallucination detection in large language models with metamorphic relations,” Proc. ACM Softw. Eng., vol. 2, no. FSE, Jun. 2025. [Online]. Available: https://doi.org/10.1145/3715735
[12] W. Wu, Y. Cao, N. Yi, R. Ou, and Z. Zheng, “Detecting and reducing the factual hallucinations of large language models with metamorphic testing,” Proc. ACM Softw. Eng., vol. 2, no. FSE, Jun. 2025. [Online]. Available: https://doi.org/10.1145/3715784
[13] X. Yin, C. Ni, S. Wang, Z. Li, L. Zeng, and X. Yang, “Thinkrepair: Self-directed automated program repair,” in Proceedings of the 33rd ACM SIGSOFT International Symposium on Software Testing and Analysis, ser. ISSTA 2024. New York, NY, USA: Association for Computing Machinery, 2024, p. 1274–1286. [Online]. Available: https://doi.org/10.1145/3650212.3680359
[14] B. Yang, H. Tian, J. Ren, H. Zhang, J. Klein, T. F. Bissyandé, C. L. Goues, and S. Jin, “Morepair: Teaching IIMS to repair code via multi-objective fine-tuning,” ACM Trans. Softw. Eng. Methodol., vol. 35, no. 2, Jan. 2026. [Online]. Available: https://doi.org/10.1145/3735129
[15] D. Chicco and G. Jurman, “The matthews correlation coefficient (mcc) should replace the roc acc as the standard metric for assessing binary classification,” BioData Mining, vol. 16, no. 1, p. 4, Feb 2023. [Online]. Available: https://doi.org/10.1186/s13040-023-00322-4
[16] R. Just, D. Jalali, and M. D. Ernst, “Defects4j: a database of existing faults to enable controlled testing studies for java programs,” in Proceedings of the 2014 International Symposium on Software Testing and Analysis, ser. ISSTA 2014. New York, NY, USA: Association for Computing Machinery, 2014, p. 437–440. [Online]. Available: https://doi.org/10.1145/2610384.2628055
[17] T. Y. Chen, S.-C. Cheung, and S.-M. Yiu, “Metamorphic testing: A new approach for generating next test cases,” Hong Kong University of Science and Technology, Department of Computer Science, Tech. Rep. HKUST-CS98-01, 1998. [Online]. Available: https://arxiv.org/abs/2002.12543
[18] E. T. Barr, M. Harman, P. McMinn, M. Shahbaz, and S. Yoo, “The oracle problem in software testing: A survey,” IEEE Transactions on Software Engineering, vol. 41, no. 5, pp. 507–525, 2015.
[19] S. Segura, G. Fraser, A. B. Sanchez, and A. Ruiz-Cortés, “A survey on metamorphic testing,” IEEE Transactions on Software Engineering, vol. 42, no. 9, pp. 805–824, 2016.
[20] S. Cho, S. Ruberto, and V. Terragni, “Metamorphic testing of large language models for natural language processing,” in 2025 IEEE International Conference on Software Maintenance and Evolution (ICSME), 2025, pp. 174–186.
[21] G. A. Guo, A. Aleti, N. Neelofar, C. Tantithamthavorn, Y. Qi, and T. Y. Chen, “Mortar: Multi-turn metamorphic testing for llm-based dialogue systems,” IEEE Transactions on Software Engineering, pp. 1–18, 2026.
[22] T. Le-Cong, D. Nguyen, B. Le, and T. Murray, “Towards reliable evaluation of neural program repair with natural robustness testing,” ACM Trans. Softw. Eng. Methodol., vol. 34, no. 7, Aug. 2025. [Online]. Available: https://doi.org/10.1145/3716167
[23] C. H. Papadimitriou, Computational complexity. GBR: John Wiley and Sons Ltd., 2003, p. 260–265.
[24] Z. Guo, M. Schlichtkrull, and A. Vlachos, “A survey on automated fact-checking,” Transactions of the Association for Computational Linguistics, vol. 10, pp. 178–206, 2022. [Online]. Available: https://aclanthology.org/2022.tacl-1.11/
[25] G. Sriramanan, S. Bharti, V. S. Sadasivan, S. Saha, P. Kattakinda, and S. Feizi, "Llm-check: Investigating detection of hallucinations in large language models," in Advances in Neural Information Processing Systems, A. Globerson, L. Mackey, D. Belgrave, A. Fan, U. Paquet, J. Tomczak, and C. Zhang, Eds., vol. 37. Curran Associates, Inc., 2024, pp. 34 188–34 216.
[26] C. E. Jimenez, J. Yang, A. Wettig, S. Yao, K. Pei, O. Press, and K. Narasimhan, “Swe-bench: Can language models resolve real-world github issues?” in International Conference on Learning Representations, B. Kim, Y. Yue, S. Chaudhuri, K. Fragkiadaki, M. Khan, and Y. Sun, Eds., vol. 2024, 2024, pp. 54 107–54 157.
[27] M. L. McHugh, “Interrater reliability: the kappa statistic,” Biochem Med (Zagreb), vol. 22, no. 3, pp. 276–282, 2012.
[28] J. Zhao, D. Yang, L. Zhang, X. Lian, Z. Yang, and F. Liu, “Enhancing automated program repair with solution design,” in Proceedings of the 39th IEEE/ACM International Conference on Automated Software Engineering, ser. ASE '24. New York, NY, USA: Association for Computing Machinery, 2024, p. 1706–1718. [Online]. Available: https://doi.org/10.1145/3691620.3695537
[29] T. Le-Cong, B. Le, and T. Murray, “Memory-efficient large language models for program repair with semantic-guided patch generation,” 2025. [Online]. Available: https://arxiv.org/abs/2410.16655
[30] J. Wei, X. Wang, D. Schuurmans, M. Bosma, b. ichter, F. Xia, E. Chi, Q. V. Le, and D. Zhou, “Chain-of-thought prompting elicits reasoning in large language models,” in Advances in Neural Information Processing Systems, S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh, Eds., vol. 35. Curran Associates, Inc., 2022, pp. 24 824–24 837.
[31] Y. Zhang, H. Ruan, Z. Fan, and A. Roychoudhury, “Autocoderover: Autonomous program improvement,” in Proceedings of the 33rd ACM SIGSOFT International Symposium on Software Testing and Analysis, ser. ISSTA 2024. New York, NY, USA: Association for Computing Machinery, 2024, p. 1592–1604. [Online]. Available: https://doi.org/10.1145/3650212.3680384
[32] I. Bouenenia, P. Devanbu, and M. Pradel, “Repairagent: An autonomous, llm-based agent for program repair,” in Proceedings of the IEEE/ACM 47th International Conference on Software Engineering, ser. ICSE '25. IEEE Press, 2025, p. 2188–2200. [Online]. Available: https://doi.org/10.1109/ICSE55347.2025.00157
[33] R. Cohen, M. Hamri, M. Geva, and A. Globerson, “LM vs LM: Detecting factual errors via cross examination,” in Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, H. Bouamor, J. Pino, and K. Bali, Eds. Singapore: Association for Computational Linguistics, Dec. 2023, pp. 12621–12640. [Online]. Available: https://aclanthology.org/2023.emnlp-main.778/
[34] Y. Tian, W. Yan, Q. Yang, X. Zhao, Q. Chen, W. Wang, Z. Luo, L. Ma, and D. Song, “Codehalu: Investigating code hallucinations in llms via execution-based verification,” Proceedings of the AAAI Conference on Artificial Intelligence, vol. 39, no. 24, pp. 25300–25308, Apr. 2025. [Online]. Available: https://ojs.aaai.org/index.php/AAAI/article/view/34717
[35] B. Yang, J. Dang, H. Liu, and Z. Jin, “Advancing llm-generated code reliability: A hybrid approach for hallucination detection,” IEEE Transactions on Software Engineering, vol. 52, no. 2, pp. 578–594, 2026.
[36] V. Agarwal, Y. Pei, S. Alamir, and X. Liu, “Codemirage: Hallucinations in code generated by large language models,” 2025. [Online]. Available: https://arxiv.org/abs/2408.08333
[37] W. Su, C. Wang, Q. Ai, Y. Hu, Z. Wu, Y. Zhou, and Y. Liu, “Unsupervised real-time hallucination detection based on the internal states of large language models,” in Findings of the Association for Computational Linguistics: ACL 2024, L.-W. Ku, A. Martins, and V. Srikumar, Eds. Bangkok, Thailand: Association for Computational Linguistics, Aug. 2024, pp. 14379–14391. [Online]. Available: https://aclanthology.org/2024.findings-acl.854/
[38] X. Du, C. Xiao, and Y. Li, “Haloscope: Harnessing unlabeled llm generations for hallucination detection,” in Advances in Neural Information Processing Systems, A. Globerson, L. Mackey, D. Belgrave, A. Fan, U. Paquet, J. Tomczak, and C. Zhang, Eds., vol. 37. Curran Associates, Inc., 2024, pp. 102 948–102 972.
[39] H. Kim, T. A. Lamb, A. Bibi, P. Torr, and Y. Gal, “Detecting LLM hallucination through layer-wise information deficiency: Analysis of ambiguous prompts and unanswerable questions,” in Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, C. Christodoulopoulos, T. Chakraborty, C. Rose, and
V. Peng, Eds. Suzhou, China: Association for Computational Linguistics, Nov. 2025, pp. 32310–32322. [Online]. Available: https://aclanthology.org/2025.emnlp-main.1644/
[40] P. Schober, C. Boer, and L. A. Schwarte, “Correlation coefficients: Appropriate use and interpretation,” Anesthesia & Analgesia, vol. 126, no. 5, 2018.
Supplemental Material of “Detecting Incorrect LLM Explanations for Automated Program Repair”
APPENDIX A
MOTIVATING EXAMPLE
Listing 1: Program1 semantically equivalent to getTextBuffer, as shown in Figure 1. It is generated by rewriting the program into nested if-else blocks.
public char[] getTextBuffer() {
if (_inputStart >= 0) {
return _inputBuffer;
} else {
if (_resultArray != null) {
return _resultArray;
} else {
if (_resultString != null) {
return _resultArray = _resultString.toCharArray();
} else {
if (!_hasSegments) {
return _currentSegment;
} else {
return contentsAsArray();
}
}
}
}
}
Listing 2: Program3 semantically non-equivalent to getTextBuffer, as shown in Figure 1. The comparison operator >= in _inputStart >= 0 is changed to >.
public char[] getTextBuffer() {
if (_inputStart > 0)
return _inputBuffer;
if (_resultArray != null)
return _resultArray;
if (_resultString != null) {
return (_resultArray = _resultString.toCharArray());
}
if (!_hasSegments)
return _currentSegment;
return contentsAsArray();
}
APPENDIX B
DETECTION PROOF
- Empirical Proof by Comparing MR Violation Rates: Figure 5 shows a clear association between the correctness of the original LLM-generated explanation and the MR violation score. Overall, the violation score across all cases is 0.54. For cases where the original explanation is correct, the violation score is . Most values fall close to 0.00, although there are some high outliers near 0.50–0.70. For cases where the original explanation is incorrect, the violation score is

Fig. 5: Comparing MR violation rates when the original LLM-generated explanations are correct and incorrect.
. This is much higher than the violation score when the explanation is correct. Most values fall close to 1.00. There are a few low outliers, but the overall distribution is shifted upward.
Let represent that the LLM correctly verifies an explanation's correctness. Let represent that the LLM generates a correct explanation. Given the benchmark shown in Table I, we get . Based on the empirical results, we have . , meaning . , meaning . We can calculate as follows
(close to 1), and . Hence, is almost always no more difficult than . This relationship can be visualised in the Venn diagram in Figure 6. Given , we can imply , with only a few false positives (). On the other hand, false negatives () are relatively more common.
- Theoretical Proof: Let be the LLM-based APR system, be the original repair consisting of the explanation and the patch . Let indicate whether the original explanation is incorrect or correct.

Fig. 6: Venn diagram of correctly verifying explanations (V) and generating correct explanations (G).
We define and for preserving and altering the semantics of a program, respectively. We design a repair sub-task that asks the system m to explain how to fix transformed programs, explicitly given the original patch y. We further model the verification task performed by m, where MetaReJ asks m to assess if a follow-up explanation applies to the original program. We denote it by , where the response of 1 indicates that the model m thinks the explanation can be applied to the program x, and 0 otherwise.
A violation of the two MRs can be represented as
where and .
Our assumption is that when a system is capable of generating a correct explanation, it is also capable of performing easier follow-up tasks correctly.
where and is less complex than , i.e., .
Explain , and Verify are designed to be easier than Gen . A violation of the MRs represents failures in a sequence of tasks Explain , and Verify . Hence, an MR violation indicates that Gen fails. In other words,
Taking corresponding probabilistic events
We thus have
Therefore
Since by definition, the violation score . We thus obtain
The violation score acts as a lower bound on the incorrectness of the explanation r.
APPENDIX C
LITERATURE SURVEY OF PROGRAM TRANSFORMATION
-
Scope: Our literature survey covers research published between 2021 and 2025, focusing on the most influential venues in software engineering. We selected conferences and journals known for their prominence and impact in the field. Specifically, we included the International Conference on Software Engineering (ICSE), Foundations of Software Engineering (FSE), International Symposium on Software Testing and Analysis (ISSTA), Automated Software Engineering (ASE), and Programming Language Design and Implementation (PLDI). We also considered some leading venues in security and machine learning, such as Symposium on Security and Privacy (S&P), Computer and Communications Security (CCS), USENIX Security Symposium (USENIX), International Conference on Machine Learning (ICML), Annual Meeting of the Association for Computational Linguistics (ACL), and Annual AAAI Conference on Artificial Intelligence (AAAI). In addition, we incorporated top software engineering journals, such as Transactions on Software Engineering and Methodology (TOSEM), Transactions on Software Engineering (TSE), Journal of Systems and Software (JSS), Information and Software Technology (IST), and Empirical Software Engineering (ESE). These venues were chosen for their reputation in publishing high-quality and influential research in software engineering (CORE rank A* or A).
-
Criteria for Paper Selection: To identify relevant publications, we established clear selection criteria. Eligible papers must:
• Be full-length papers published in the proceedings or issues of the listed in-scope venues between 2021 and 2025.
• Exclude short papers (e.g., PhD symposium or work-in-progress papers), as these typically represent incomplete research, and
• Address program transformations, meaning they either propose a new transformation technique or provide a review of existing ones.
To support paper identification, we defined a set of keywords that capture the research focus of this area: program, code, transformation, transform, modify, modification, perturb, perturbation, mutate, mutation, mutant, counterexample, adversarial, attack, semantic, preserve, alter, equivalence, and morph. We searched for these keywords in the titles and abstracts of all in-scope papers using multiple tools, including IEEE Xplore Advanced Search for IEEE venues, ACM DL Advanced Search for ACM venues, and Google Scholar Advanced Search
https://www.core.edu.au/home for independent venues. This process yielded 88 potential papers, which were flagged for further manual review.
- Filtering Process: We manually reviewed the flagged papers to exclude those not directly related to program transformations. A total of 49 papers were excluded as off-topic. The remaining 39 papers are shown in Table III.
APPENDIX D
PROMPT TEMPLATES
Listing 3: Follow-up Explanation Generation
System: You are an Automatic Program Repair Tool. You are now the examinee in a debate-style viva examination, where you defend your original repair decision.
User: You originally provided the following fix for the original buggy function:
// Buggy Function
{{original_buggy_code}}
// Fixed Function
{{fixed_code}}
Now, the examiner presents a transformed buggy function:
// Buggy Function
{{transformed_buggy_code}}
Since you proposed the original fix, explain how this transformed buggy function should be fixed.
Listing 4: Follow-up Explanation Verification
System: You are an Automatic Program Repair Tool. You are now the examinee in a debate-style viva examination, where you defend your original repair decision.
Answer YES or NO. If you are NOT SURE, answer NOT SURE. Don't return anything else except YES, NO, or NOT SURE.
User:
// Buggy Function
{{original_buggy_code}}
// Explanation
{{explanation}}
Given a buggy function and an explanation, you need to verify if the explanation is applicable to fix the buggy function.
APPENDIX E
ANNOTATION PROCESS
Experts were invited to label the correctness of 1,756 explanations, as collected in Section IV-D. Each has 3–5 years of experience in programming and program repair. They first went through a tutorial on how to review and label an explanation. Then, for each explanation, two annotators were assigned to independently label its correctness. A web application was developed to facilitate this process. Figure 7
shows a screenshot of the web application for labeling an explanation generated by MORepair for Cli-19 in Defects4J. The annotators were provided with various artifacts, including the buggy program, the developer's fix, the LLM-generated explanation, the LLM-generated fix, and auxiliary information about the bug, such as the bug report and triggering tests. After reviewing these artifacts, the annotators decided whether the explanation is correct and stated their level of confidence from 1 to 5 on a Likert-like scale. They were also encouraged to note their rationale during the labeling process. If they are unsure, the third option "unsure" could be selected.
For example, the program processOptionToken in Figure 7 does not handle the token properly. The token is simply ignored if it does not belong to options or if stopAtNonOption is disabled. Based on the developer's fix, this buggy program can be fixed by moving tokens.add(token) outside of the if-else block. The explanation generated by MORepair correctly describes the bug and how to fix it. As a result, this explanation is labeled as correct.
The web application recorded that it took 182.62 seconds on average for an annotator to label an explanation. In total, it took 178.15 hours to label the entire 1,756 explanations. This annotation process achieved a Cohen's Kappa value for inter-annotator agreement of 0.78. This indicates substantial consistency and reliability, significantly bolstering our confidence in both the benchmark's quality and MetaReJ's evaluation.
If an annotator is unsure about the explanation's correctness or the two annotators disagree, a third annotator got involved in the discussion to reach a consensus. Ultimately, 1,217 incorrect explanations were identified, as shown in Table I. This shows that many generated explanations, in particular 69.3% of the explanations, are incorrect. The APR systems are still highly unreliable for explaining their repairs, even the best-performing system, ReInFix.
APPENDIX F
EXPERIMENTS
- Sampling Transformed Programs: The generations of transformed programs Tran_eqv and Tran_neq are typically inexpensive. However, generating follow-up explanations Explain_m may be costly, as it requires querying the LLM multiple times. To reduce this cost, we adopt a fixed sampling budget strategy: given a budget N, we draw N follow-up explanations for N equivalent programs and N follow-up explanations for N non-equivalent ones. To enhance the diversity of this sampling, MetaReJ selects the most representative transformed programs.
To do this, MetaReJ clusters each list of equivalent and non-equivalent transformed programs into N clusters. MetaReJ transform each program into its vector representation using UniXCoder³. For each category of equivalence or non-equivalence, MetaReJ clusters the vector representations of transformed programs into N clusters. Then, it randomly chooses one in each cluster as a representative example.
³https://github.com/microsoft/CodeBERT/tree/master/UniXcoder
TABLE III: Papers about Program Transformation
| Title | Year | Venue |
|---|---|---|
| Assessing Robustness of ML-Based Program Analysis Tools using Metamorphic Program Transformations | 2021 | ASE |
| On the generalizability of Neural Program Models with respect to semantic-preserving program transformations | 2021 | IST |
| Self-Supervised Contrastive Learning for Code Retrieval and Summarization via Semantic-Preserving Transformations | 2021 | SIGIR |
| Adversarial Robustness of Deep Code Comment Generation | 2022 | TOSEM |
| Bridging Pre-trained Models and Downstream Tasks for Source Code Understanding | 2022 | ICSE |
| CODE-MVP: Learning to Represent Source Code from Multiple Views with Contrastive Pre-Training | 2022 | NAACL |
| Data augmentation by program transformation | 2022 | JSS |
| NatGen: generative pre-training by “naturalizing” source code | 2022 | FSE |
| ReACC: A Retrieval-Augmented Code Completion Framework | 2022 | ACL |
| Selfapr: Self-supervised program repair with test execution diagnostics | 2022 | ASE |
| Towards Learning (Dis)-Similarity of Source Code from Program Contrasts | 2022 | ACL |
| Towards Robustness of Deep Program Processing Models—Detection, Estimation, and Enhancement | 2022 | TOSEM |
| TransRepair: Context-aware Program Repair for Compilation Errors | 2022 | ASE |
| A Black-Box Attack on Code Models via Representation Nearest Neighbor Search | 2023 | EMNLP |
| An Extensive Study on Adversarial Attack against Pre-trained Models of Code | 2023 | FSE |
| CCTEST: Testing and Repairing Code Completion Systems | 2023 | ICSE |
| Challenging Machine Learning-Based Clone Detectors via Semantic-Preserving Code Transformations | 2023 | TSE |
| Code Difference Guided Adversarial Example Generation for Deep Code Models | 2023 | ASE |
| CodeAttack: Code-Based Adversarial Attacks for Pre-trained Programming Language Models | 2023 | AAAI |
| CodeMark: Imperceptible Watermarking for Code Datasets against Neural Code Completion Models | 2023 | FSE |
| DIP: Dead code insertion based black-box attack for programming language model | 2023 | ACL |
| Discrete Adversarial Attack to Models of Code | 2023 | PLDI |
| How Effective Are Neural Networks for Fixing Security Vulnerabilities | 2023 | ISSTA |
| Is Your Code Generated by ChatGPT Really Correct? Rigorous Evaluation of Large Language Models for Code Generation | 2023 | NeurIPS |
| Repair Is Nearly Generation: Multilingual Program Repair with LLMs | 2023 | AAAI |
| ALANCA: Active Learning Guided Adversarial Attacks for Code Comprehension on Diverse Pre-trained and Large Language Models | 2024 | SANER |
| An LLM-Assisted Easy-to-Trigger Backdoor Attack on Code Completion Models: Injecting Disguised Vulnerabilities against Strong Detection | 2024 | USENIX |
| Benchmarking Automated Program Repair: An Extensive Study on Both Real-World and Artificial Bugs | 2024 | ISSTA |
| Do large code models understand programming concepts? counterfactual analysis for code predicates | 2024 | ICML |
| Effective test generation using pre-trained Large Language Models and mutation testing | 2024 | IST |
| Mutation-based Consistency Testing for Evaluating the Code Understanding Capability of LLMs | 2024 | CAIN |
| Poison Attack and Poison Detection on Deep Source Code Processing Models | 2024 | TOSEM |
| Stealthy Backdoor Attack for Code Models | 2024 | TSE |
| AdverIntent-Agent: Adversarial Reasoning for Repair Based on Inferred Program Intent | 2025 | ISSTA |
| CodeMorph: Mitigating Data Leakage in Large Language Model Assessment | 2025 | ICSE |
| How Accurately Do Large Language Models Understand Code? | 2025 | |
| Metamorphic-Based Many-Objective Distillation of LLMs for Code-related Tasks | 2025 | ICSE |
| Towards Reliable Evaluation of Neural Program Repair with Natural Robustness Testing | 2025 | TOSEM |
| Understanding the Robustness of Transformer-Based Code Intelligence via Code Transformation: Challenges and Opportunities | 2025 | TSE |
Table VII compares MetaReJ’s effectiveness with two strategies for sampling transformed programs. The default strategy is clustering, as aforementioned. The alternative strategy is to randomly select programs. The results show that clustering is consistently more effective than random selection for sampling transformed programs across all three APR systems. For ThinkRepair, MCC drops from 0.42 with clustering to only 0.04 with random selection, a reduction of 91.4%. ReInFix also drops from 0.47 to 0.24, while MOREpair decreases from 0.39 to 0.14. This shows that random sampling substantially weakens MetaReJ’s ability to distinguish correct and incorrect explanations. Precision, Recall, and Specificity help clarify the difference between the two strategies. For ThinkRepair, random selection achieves higher Recall than clustering, but its Specificity drops sharply from 0.75 to 0.20. This means MetaReJ correctly detects many incorrect explanations but incorrectly labels correct ones as incorrect, which severely reduces MCC. For ReInFix, the opposite trend appears. Random selection has slightly higher Specificity, but Recall falls from 0.67 to 0.36, meaning it misses many true incorrect explanations. For MOREpair, random selection performs worse on almost every metric. Overall, the results suggest that clustering selects a more diverse and representative set of
transformed programs, leading to more effective detection.
-
Interpretation of Evaluation Metrics: Tables VIII–IX show the interpretations of Matthew Correlation Coefficient (MCC) [40] and Cohen’s Kappa [27], respectively.
-
Benchmark Breakdown: Table VI shows that incorrect explanations are common across all APR systems and datasets. On Defects4J, all three systems produce a large proportion of incorrect explanations. ThinkRepair has the highest incorrect rate at 88.1%, followed by MOREpair at 79.4%, and ReInFix at 57.2%. Even the best-performing system, ReInFix, still produces more incorrect explanations than correct ones.
The trend remains consistent on the other datasets. ThinkRepair and ReInFix show almost the same incorrect rates as on Defects4J, with 87.1% and 56.1%, respectively. This suggests that their explanation correctness is relatively stable across bug benchmarks. MOREpair achieves a lower incorrect rate on the other datasets, dropping from 79.4% to 63.4%, but incorrect explanations still dominate.
Overall, these results suggest that incorrect APR explanations are not an isolated issue of Defects4J. Across all datasets, there are 1,756 explanations, of which 1,219 are incorrect, giving an overall incorrect explanation rate of about 69.3%. This supports the need for automated methods such
TABLE IV: Semantic preserving transformations used in this study
| Id | Transformation | Original | Transformed |
|---|---|---|---|
| Stylistic Transformations | |||
| PCS-1 | Change Spacing Style | ||
| PCS-2 | Change Naming Style | myNumber | my_number |
| Unused or Dead Code Transformations | |||
| PUD-1 | Add Unused Statements/Dead Code | ||
| PUD-2 | Delete Unused Statement | ||
| PUD-3 | Add Unused Parameters/-Variable | ||
| PUD-4 | Move Partial Code into Function | z=x+y | |
| PUD-5 | Delete Unused Variable | ||
| Expression Transformations | |||
| PEL-1 | Wrap with Logical NOT | x<y | !(y>=x) |
| PEL-2 | Split Compound Condition into Nested Ifs | if (cond1 && cond2) {\n//Body} | if (cond1) {\nif (cond2) {\n//Body} |
| PEL-3 | Merge Variable Declarations | int a, b; | |
| PEL-4 | Separate Declaration and Initialization | int i=0; | int i; i=0; |
| PEL-5 | Combine Declaration and Initialization | int i; i=0; | int i=0; |
| PEL-6 | Transform Relational Expression | a < b | b > a |
| PEL-7 | Transform Boolean Logic Equivalently | x == -1\ni == j\n(a || b) && c | x + 1 == 0\nj == i\n(a && c) || (b && c) |
| PEL-8 | Convert Add/Subtract Assignment to Equal Assignment | ||
| PEL-9 | Divide Expression into Small Expressions with Intermediate Variables | ||
| PEL-10 | Swap Operands | a + b | b + a |
| PEL-11 | Combine Small Expressions into Expression | ||
| PEL-12 | Change Arithmetic Expression Equivalently | a - b + c | a - (b - c) |
| Id | Transformation | Original | Transformed |
|---|---|---|---|
| PNL-1 | Modify Comment | ||
| PNL-2 | Add Comment | ||
| PNL-3 | Remove Comment | ||
| PNL-4 | Add Print Statement | ||
| PNL-5 | Remove Print Statement | ||
| PNL-6 | Modify Print Message | ||
| Control Flow Transformations | |||
| PCL-1 | Convert For-Loop to While-Loop | ||
| PCL-2 | Convert While-Loop to For-Loop | ||
| PCL-3 | Convert If-Elseif to If-Else | ||
| PCL-4 | Convert If-Else to If-Elseif | ||
| PCL-5 | Convert Switch-Case to If-Else | ||
| PCL-6 | Convert If-Else to Switch-Case | ||
| PCL-7 | Convert If-Continue to If-Else | ||
| PCL-8 | Swap If and Else Blocks | ||
| PCL-9 | Swap Two Independent Statements | ||
| PCL-10 | Convert If Statement to Conditional Expression | condition ? BodyA : BodyB | |
| PCL-11 | Convert Conditional Expression to If Statement | condition ? BodyA : BodyB | |
| PCL-12 | Add Else Clause | ||
| PCL-13 | Wrap Statement in If or Loop | statement | if (1) statement |
| PCL-14 | Move Iterator Declaration into For-Loop | int i; for (i; i < n; i++) | for (int i = 0; i < n; i++) |
| PCL-15 | Move Iterator Declaration out of For-Loop | for (int i = 0; i < n; i++) | int i; for (i; i < n; i++) |
as MetaReJ to detect incorrect explanations before they are presented to developers.
- Detection Examples: We provide an example of a true positive, where an incorrect explanation is correctly detected.
Listing 5: The buggy program contains IgnoreCase, also known as Lang-40 in Defects4J.
public static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return contains(str.toUpperCase(), searchStr.toUpperCase()); }
Listing 6: The fix for Lang-40 generated by ThinkRepair.
return contains(str.toUpperCase(), searchStr.toUpperCase()); return contains(str.toUpperCase(), searchStr.toUpperCase()) || contains(str.toLowerCase(), searchStr.toLowerCase());
Original Explanation: The bug in the containsIgnoreCase function is with the line 'contains(str.toUpperCase(), searchStr.toUpperCase())'. This line checks if the search string is a substring of the input string, but it is incorrect and will result in a stack overflow for certain inputs.
TABLE V: Semantic altering transformations used in this study
| Id | Transformation | Original | Transformed |
|---|---|---|---|
| Identifier Based Transformations | |||
| AIB-1 | Rename Variable | ||
| Control Flow Transformations | |||
| ACL-1 | Misplace Return | ||
| ACL-2 | Swap Break and Continue | ||
| ACL-3 | Delete Exception Handler | except: pass | except: raise |
| ACL-4 | Swallow Exception | except: return | except: pass |
| ACL-5 | Delete Statement | ||
| ACL-6 | Wrap Statement with Condition | ||
| ACL-7 | Unwrap Block | ||
| ACL-8 | Delete Block | ||
| ACL-9 | Insert Block | ||
| ACL-10 | Misuse Variable | ||
| Id | Transformation | Original | Transformed |
|---|---|---|---|
| Expression Transformations | |||
| PEL-1 | Off-By-One | n | n+1 |
| PEL-2 | Replace Conditional Expression | a || b | a |
| PEL-3 | Expand Boolean Expression | x && y | x && y || z |
| PEL-4 | Replace Relational Operator | x < 10 | x <= 10 |
| PEL-5 | Replace Boolean Operator | x && y | x || y |
| PEL-6 | Replace Literal Value | ||
| PEL-7 | Negative Condition | !cond | cond |
| PEL-8 | Remove Slice Index | sorted(l[:3]) | sorted(l[:]) |
| PEL-9 | Modify Function Call | ||
Buggy code
| 1 | { |
|---|---|
| 2 | { |
| 3 | { |
| 4 | { |
| 5 | currentOption = options.getOption(token); |
| 6 | tokens.add(token); |
| 7 | } |
| 8 | else if (stopAtNonOption) |
| 9 | { |
| 10 | eatTheRest = true; |
| 11 | tokens.add(token); |
| 12 | } |
| 13 | } |
Bug info
| Bug report url: |
|---|
| https://issues.apache.org/jira/browse/CLI-164 |
| Root cause in triggering tests: |
| - org.apache.commons.cli.PosixParserTest::testUnrecognizedOption2 |
| --> junit.framework.AssertionFailedError: |
| UnrecognizedException wasn't thrown |
| List of modified sources: |
| - org.apache.commons.cli.PosixParser |
Decision
| Label | correct |
|---|---|
| incorrect | unsure |
| correct | |
| Confidence | 4 |
| 1 - low confidence, 5 - high confidence | |
| 1 | 2 |
| 3 | 4 |
| 5 | |
| Note |
Developer fix
| 2 | 2 | @ -2,12 +2,12 @ |
|---|---|---|
| 3 | 3 | { |
| 4 | 4 | { |
| 5 | 5 | currentOption = options.getOption(token); |
| 6 | - | tokens.add(token); |
| 7 | 6 | } |
| 8 | 7 | { |
| 9 | 8 | else if (stopAtNonOption) |
| 10 | 9 | eatTheRest = true; |
| 11 | - | tokens.add(token); |
| 12 | 10 | } |
| 11 | + | |
| 12 | + | tokens.add(token); |
| 13 | 13 | } |
LLM fix
| 2 | 2 | @ -2,12 +2,11 @ |
|---|---|---|
| 3 | 3 | { |
| 4 | 4 | { |
| 5 | 5 | currentOption = options.getOption(token); |
| 6 | - | tokens.add(token); |
| 7 | 6 | } |
| 8 | 7 | else if (stopAtNonOption) |
| 9 | 8 | { |
| 10 | 9 | eatTheRest = true; |
| 11 | - | tokens.add(token); |
| 12 | 10 | } |
| 11 | + | tokens.add(token); |
| 13 | 12 | } |
Hide
LLM explanation
The bug in the processOptionToken method is with the lines that add the token to the tokens list. These lines should be moved outside of the if-else block, so that the token is added to the list only after it has been processed.
| Save | Back to list |
Fig. 7: Annotation page of an MORepair-generated explanation for Cli-19 in Defects4J.
Listing 7: A transformed program semantically non-equivalent to Lang-40 in Defects4J. The logical operator || is replaced by &&.
public static boolean containsIgnoreCase(String str, String searchStr) { if (null == str && null == searchStr) { return false; } return contains(str.toUpperCase(), searchStr.toUpperCase()); }
Follow-up Explanation: The bug in the original function is
that it returns 'false' if either 'str' or 'searchStr' is 'null', even if the other argument is not 'null'. This is because the '&&' operator short-circuits and returns 'false' as soon as it encounters a 'null' value. To fix this bug, we need to change the '&&' operator to '||' so that both arguments are checked for 'null' before calling the 'contains' method. This will ensure that the function returns 'false' only if both 'str' and 'searchStr' are 'null'.
This follow-up explanation explains that we need to change the '&&' operator to '||', which is not applicable to the original Lang-40. However, ThinkRepair responds that it is not applicable.
TABLE VI: Benchmarking the correctness of LLM-generated APR explanations
| APR System Under Test | Defects4J | Name | Other Datasets | ||||||
|---|---|---|---|---|---|---|---|---|---|
| # Expls | # Correct Expls | # Incorrect Expls | Incorrect Expl Rate | # Expls | # Correct Expls | # Incorrect Expls | Incorrect Expl Rate | ||
| ThinkRepair | 369 | 44 | 325 | 88.1% | RWB | 62 | 8 | 54 | 87.1% |
| ReInFix | 670 | 287 | 383 | 57.2% | RWB | 41 | 18 | 23 | 56.1% |
| MORepair | 281 | 58 | 223 | 79.4% | SWE-Repair, EvalRepair-C++, EvalRepair-Java | 333 | 122 | 211 | 63.4% |
TABLE VII: Comparing two strategies for sampling transformed programs: clustering and random selection
| System Under Test | Detector | Detection Quality | ||||
|---|---|---|---|---|---|---|
| MCC | MCC | BA | Pre | Rec | ||
| ThinkRepair | Cluster | 0.34 | -88.2% | 0.75 | 0.96 | 0.72 |
| Random | 0.04 | 0.52 | 0.88 | 0.84 | ||
| ReInFix | Cluster | 0.43 | -39.5% | 0.70 | 0.88 | 0.50 |
| Random | 0.26 | 0.61 | 0.79 | 0.36 | ||
| MORepair | Cluster | 0.39 | -61.5% | 0.71 | 0.91 | 0.70 |
| Random | 0.15 | 0.58 | 0.76 | 0.63 | ||
TABLE VIII: Interpretation of Matthew Correlation Coefficient (MCC), based on thresholds from [40]
| Matthew Correlation Coefficient (MCC) | Interpretation |
|---|---|
| 0.00 – 0.09 | Negligible correlation |
| 0.10 – 0.39 | Weak correlation |
| 0.40 – 0.69 | Moderate correlation |
| 0.70 – 0.89 | Strong correlation |
| 0.90 – 1.00 | Very strong correlation |
TABLE IX: Interpretation of Cohen's Kappa [27]
| Value of Kappa | Level of Agreement |
|---|---|
| 0.00 – 0.20 | None |
| 0.21 – 0.39 | Minimal |
| 0.40 – 0.59 | Weak |
| 0.60 – 0.79 | Moderate |
| 0.80 – 0.90 | Strong |
| 0.91 – 1.00 | Almost Perfect |
We provide an example of a false negative.
Listing 8: The buggy program random, also known as Lang-12 in Defects4J.
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (start == 0 && end == 0) { if (!letters && !numbers) {
end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ''; }
char[] buffer = new char[count]; int gap = end - start;
while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch)) || !letters && !numbers) { if (ch >= 56320 && ch <= 57343) { if (count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if (ch >= 55296 && ch <= 56191) { if (count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if (ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } } }
58 return new String(buffer); 59 }
Listing 9: The fix for Lang-12 generated by ThinkRepair.
- if (start == 0 && end == 0) {
- if (start == 0 || end == 0) {
Original Explanation: The bug is in the 'if (start == 0 && end == 0)' statement. The function is checking if both 'start' and 'end' are 0, but the intended behavior is to check if either one of them is 0.
This repair generated by ThinkRepair is incorrect. The actual bug is that the chars array may be null or empty and there is currently no check for that. The repair incorrectly identifies the root cause, and proposes a wrong explanation.
We transform the program Lang-12 into a semantically equivalent program as follows.
Listing 10: A transformed program semantically equivalent to Lang-12 in Defects4J.
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } else if (count == 0) { return ""; }
if (start == 0 && end == 0) { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ''; } }
char[] buffer = new char[count]; int gap = end - start;
while (count-- != 0) { char ch = (chars == null) ? (char) (random.nextInt(gap) + start) : chars[random.nextInt(gap) + start]; if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if (ch >= 56320 && ch <= 57343) { if (count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if (ch >= 55296 && ch <= 56191) { if (count == 0) {
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if (ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } return new String(buffer);
The transformed program makes two refactoring changes while preserving the original behavior. First, it reorders the initial boundary checks by checking 'count' 0' before 'count == 0'; this does not change the logic because the two conditions are mutually exclusive. Second, it replaces the explicit 'if-else' block used to assign 'ch' with an equivalent ternary expression. Thus, the transformation simplifies the code structure and makes the assignment more compact, but it does not alter the program's intended functionality.
Follow-up Explanations: The bug is caused by the fact that the function is using the '&&' operator instead of the '||' operator to check if either 'start' or 'end' is equal to 0. This means that the function will only set 'end' to 'Integer.MAX_VALUE' if both 'start' and 'end' are equal to 0, which is not the intended behavior. To fix this bug, you should change the line 'if (start == 0 && end == 0) { ... }' to 'if (start == 0 || end == 0) { ... }'. This will ensure that the function sets 'end' to 'Integer.MAX_VALUE' if either 'start' or 'end' is equal to 0, which is the intended behavior.
This follow-up explanation is similar to the original one. Although the follow-up explanation is incorrect, as the original, the LLM verifies that it is applicable to the buggy program Lang-12.
We also transform the program Lang-12 into a semantically non-equivalent program as follows.
Listing 11: A transformed program semantically non-equivalent to Lang-12 in Defects4J.
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { char[] buffer = new char[count]; int gap = end - start;
while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } } }
} else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch)) || numbers && Character.isDigit(ch) || !letters && !numbers) { if (ch >= 56320 && ch <= 57343) { if (count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if (ch >= 55296 && ch <= 56191) { if (count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if (ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } else { count++; } } } return new String(buffer);
This new program removes the if statement 'if (start == 0 && end == 0) { ... }'. ThinkRepair provides a follow-up explanation for this program.
Follow-up Explanation: The bug in the original function is that it does not correctly handle the case where 'start' and 'end' are both 0. In this case, the function sets 'end' to 'Integer.MAX_VALUE' and 'start' to'', which is not the correct behavior. To fix this bug, we need to check if 'start' and 'end' are both 0, and if so, set 'end' to 'Integer.MAX_VALUE' and 'start' to '0'. We can do this by adding the following code at the beginning of the function:
if (start == 0 && end == 0) { end = Integer.MAX_VALUE; start = 0; }
This follow-up explanation is completely different from the original. ThinkRepair verifies that this explanation is not applicable to the original program. In this case, ThinkRepair is stubborn and consistently defends its wrong reasoning. As a result, MetaReJ fails to detect the original explanation generated by ThinkRepair as incorrect.