Paper deep dive
TestGRAD: Evolving Test Suites via Failure Pattern Momentum for SWE-Agent Ensemble
Pengfei He, Jiayuan Zhou, Shaowei Wang, Ruiqi Pan
Intelligence
Status: succeeded | Model: Gemma-4-26B-A4B | Prompt: intel-v1 | Confidence: 94%
Last extracted: 10/11/2026, 4:36:56 AM
Summary
The paper introduces TestGRAD, a framework for optimizing test suites in SWE-agent ensembles by treating test-suite evolution as a gradient-descent-like optimization process. It utilizes differential loss to ensure tests distinguish between candidate patches, full CRUD gradients (Read, Create, Update, Delete) to update the test suite comprehensively, and Failure Pattern Momentum to mine frequent failure sequences from memory, thereby avoiding repeated non-discriminative directions. TestGRAD achieves 84.2% Pass@1 on SWE-bench Verified with a 4-agent ensemble, outperforming baselines.
Entities (9)
Relation Signals (8)
TestGRAD → achieves → 84.2% Pass@1
confidence 100% · On SWE-bench Verified, TestGRAD achieves 84.2% Pass@1 with a 4-agent ensemble
TestGRAD → evaluatedon → SWE-bench Verified
confidence 100% · On SWE-bench Verified (500 instances) (SWE-bench 2025), TestGRAD achieves 84.2% Pass@1
Failure Pattern Momentum → mines → frequent failure sequences
confidence 95% · Failure Pattern Momentum mines frequent failure sequences from memory
TestGRAD → uses → Differential loss
confidence 95% · TestGRAD centers on three concepts. Differential loss gives the optimizer an explicit execution-defined target
TestGRAD → uses → Full CRUD gradients
confidence 95% · Full CRUD gradients expand the update direction... TestGRAD therefore exposes all four directions as the test-space gradient.
TestGRAD → uses → Failure Pattern Momentum
confidence 95% · Failure Pattern Momentum mines frequent failure sequences from memory... TestGRAD uses an analogous mechanism
Differential loss → distinguishes → candidate patches
confidence 90% · useful tests should separate candidate patches by behavior.
TestGRAD → outperforms → TRAE
confidence 90% · outperforming the strongest baseline (80.6%) by an absolute improvement of 3.6 percentage points... TRAE, 80.6%
Cypher Suggestions (0)
No Cypher suggestions yet.
Abstract
Abstract:SWE-agent ensembles improve issue resolution by combining candidate patches from different agents with complementary strengths. The central problem is therefore test-based selection: generate tests, execute candidate patches, and identify the best patch. We formulate this process as test-space optimization: evolving an executable repository test suite until it distinguishes competing patches. Existing test-generation methods are limited optimizers. They usually lack an explicit loss for ensemble selection, optimize through incomplete directions that mostly create new tests or delete old ones, and perform one-off generation without feedback from repeated failures. Inspired by gradient descent with momentum, we introduce TestGRAD, a framework for automatic test optimization. TestGRAD centers on three concepts. Differential loss gives the optimizer an explicit execution-defined target: useful tests should separate candidate patches by behavior. Full CRUD gradients expand the update direction from merely creating or deleting tests to reading existing test infrastructure, creating new tests, updating stale assertions, and deleting only obsolete tests. Failure Pattern Momentum mines frequent failure sequences from memory, allowing the optimizer to avoid repeated non-discriminative directions while compressing the failure-history context. On SWE-bench Verified, TestGRAD achieves 84.2% Pass@1 with a 4-agent ensemble, outperforming the strongest baseline (80.6%) by an absolute improvement of 3.6 percentage points, while compressing failure-history context by over $100\times$.
Tags
Links
- Source: https://arxiv.org/abs/2610.10242v1
- Canonical: https://arxiv.org/abs/2610.10242v1
Trouble viewing inline? Open PDF directly →
Full Text
59,339 characters extracted from source content.
Expand or collapse full text
TestGRAD: Evolving Test Suites via Failure Pattern Momentum for SWE-Agent Ensemble Pengfei He Jiayuan Zhou Shaowei Wang Ruiqi Pan Abstract SWE-agent ensembles improve issue resolution by combining candidate patches from different agents with complementary strengths. The central problem is therefore test-based selection: generate tests, execute candidate patches, and identify the best patch. We formulate this process as test-space optimization: evolving an executable repository test suite until it distinguishes competing patches. Existing test-generation methods are limited optimizers. They usually lack an explicit loss for ensemble selection, optimize through incomplete directions that mostly create new tests or delete old ones, and perform one-off generation without feedback from repeated failures. Inspired by gradient descent with momentum, we introduce TestGRAD, a framework for automatic test optimization. TestGRAD centers on three concepts. Differential loss gives the optimizer an explicit execution-defined target: useful tests should separate candidate patches by behavior. Full CRUD gradients expand the update direction from merely creating or deleting tests to reading existing test infrastructure, creating new tests, updating stale assertions, and deleting only obsolete tests. Failure Pattern Momentum mines frequent failure sequences from memory, allowing the optimizer to avoid repeated non-discriminative directions while compressing the failure-history context. On SWE-bench Verified, TestGRAD achieves 84.2% Pass@1 with a 4-agent ensemble, outperforming the strongest baseline (80.6%) by an absolute improvement of 3.6 percentage points, while compressing failure-history context by over 100×100×. 1University of Manitoba, Winnipeg, Canada 2Huawei Canada, Markham, Canada 3Huawei Technologies, Hangzhou, China hep2@myumanitoba.ca, shaowei.wang@umanitoba.ca jiayuan.zhou1@huawei.com, panruiqi@huawei.com Introduction Software engineering (SWE) agents autonomously resolve repository issues by localizing faults, generating patches, and validating fixes in a live coding environment (Jimenez et al. 2023; Lingxi Authors 2025). Different agents exhibit complementary strengths: an agent that fails on one issue may still produce the best patch for another. A practical way to exploit this diversity is parallel ensembling, where multiple SWE agents generate candidate patches and a selector chooses the final patch (Se and Vert 2025). The selector must be grounded in behavior. A natural but weak approach is to ask an LLM judge to compare candidate patches and select the most plausible fix (Augment Code 2025; Zhang et al. 2025). Without execution evidence, however, the judge sees surface plausibility rather than repository behavior and can be sensitive to presentation order (Wang et al. 2023; Zheng et al. 2024). The key to SWE-agent ensembling is therefore test-based selection: generate tests, execute every candidate patch, and use the resulting behavior to identify the correct patch. This view turns ensemble selection into test-space optimization: the optimized object is the repository test suite, and the objective is to evolve it for better selection. This is difficult for three reasons. First, the loss is not obvious. A test that simply passes or fails is not necessarily useful for selection; even patches that pass benchmark tests can remain behaviorally divergent from developer fixes (Wang, Pradel, and Liu 2026). Second, the update direction cannot be limited to creating new tests. Useful repository tests often require reading fixtures and conventions, updating stale assertions, and deleting only confirmed obsolete tests (Mündler et al. 2025). Third, test generation is rarely solved in one step: when an attempted test is non-discriminative, the next attempt should use that failure as optimization signal rather than restart from scratch. Inspired by gradient descent with momentum in neural networks (Polyak 1964; Sutskever et al. 2013), we introduce TestGRAD, a framework that models test-suite evolution as gradient-descent-like optimization in test space. Table 1 summarizes the analogy. A test suite is the parameter state, differential execution is the loss, CRUD edits are gradient directions, frequent failure sequences are momentum, support is the retention weight, and the LLM agent is the optimizer. In the forward pass, TestGRAD executes the current test suite on candidate patches and observes whether their behaviors differ. In the backward pass, the LLM optimizer uses this execution-defined signal and mined failure momentum to produce the next CRUD test update. The design has three components. ➀Differential loss. TestGRAD makes the optimization target explicit: a useful test suite should separate candidate patches by behavior. We define the loss by execution. If the current test suite contains a differential test, meaning at least one test passes on some candidate patches and fails on others, the loss reaches zero. Otherwise, the loss remains nonzero and the failed update is used to guide the next iteration. This differs from pass-count selection (Xia et al. 2025; Gao et al. 2025), which simply chooses the patch that passes the most tests. Differential loss instead searches for behavioral contrast among candidates rather than merely verifying the intended fix. It prunes candidates that are indistinguishable under the current tests and discourages selection based on a single weak pass/fail signal. ➁Full CRUD gradient. TestGRAD treats test-suite evolution as a full CRUD update rather than a Create/Delete-only pipeline. Existing test-generation methods (Xia et al. 2025; Gao et al. 2025) mainly create a new test from the issue and, at most, delete conflicting tests by name matching. This partial direction is insufficient for repository tests, which often depend on existing fixtures, setup routines, imports, assertion helpers, and tests whose expected values must be revised after the fix. TestGRAD therefore exposes all four directions as the test-space gradient. Read extracts repository-specific testing knowledge for reuse. Create adds new discriminative tests. Update revises stale assertions or test bodies whose expected behavior changes with the fix. Delete removes only tests confirmed obsolete. This full direction avoids shallow standalone tests, preserves high-signal tests that only need assertion updates, and prevents a correct patch from being rejected simply because an old assertion was left unchanged. ➂Failure Pattern Momentum. In numerical optimization, momentum accumulates consistent gradient information across steps and helps avoid oscillation or repeated dead ends. TestGRAD uses an analogous mechanism for test updates. When a CRUD update produces a non-discriminative suite, the failed update is written into failure memory. TestGRAD then mines maximal frequent failure sequences from this memory. These sequences form Failure Pattern Momentum: compact evidence of directions that have repeatedly failed. The next LLM optimizer step receives this momentum and can move away from recurring non-discriminative regions of the test-suite space. Compared with summarizing failures using another LLM call (Shinn et al. 2023) or feeding raw test-execution feedback back to the generator (Huang et al. 2023), this design is deterministic, faithful to observed failures, and compresses context by over 100×100×. On SWE-bench Verified (500 instances) (SWE-bench 2025), TestGRAD achieves 84.2% Pass@1 with a 4-agent ensemble using Minimax-m2.7, outperforming the next-best baseline (TRAE, 80.6%) by an absolute improvement of 3.6 percentage points and the single-agent baseline by 5.0 percentage points. Gains are consistent across all three base LLMs. Ablations confirm the contribution of each component: removing Read drops Pass@1 by 3.0%3.0\%, removing Update by 2.4%2.4\%, replacing differential loss with pass-count selection by 3.4%3.4\%, removing Failure Pattern Momentum by 1.6%1.6\%, and removing iterative optimization entirely by 9.2%9.2\%. Contributions: ❶ We formulate SWE-agent ensemble selection as test-space optimization over executable repository test suites. ❷ We instantiate this optimization with differential execution loss and full CRUD test-suite gradients. ❸ We introduce Failure Pattern Momentum, which mines frequent failure sequences from memory to guide iterative test evolution while compressing context by over 100×100×. ❹ TestGRAD achieves 84.2% Pass@1 on SWE-bench Verified with a 4-agent ensemble. Related Work Table 1: Role-level analogy between gradient descent with momentum and test-space optimization. A one-step CRUD edit plays the role of an instantaneous gradient, whereas a high-support recurring failed edit sequence plays the role of momentum carried across attempts. Gradient Descent with Momentum TestGRAD Parameter state. Current parameter vector θt _t. Test suite state. Current candidate test suite yty_t. Objective. Loss function ℒ(θt)L( _t). Objective. Differential loss ℒ(yt)L(y_t) measuring whether the current test suite has produced a differential outcome. Retention strength. β∈[0,1]β∈[0,1] controls how much of the previous velocity is retained. Support-based retention. The β=MinSupport β=MinSupport threshold defines the minimum frequency a sequence must satisfy. Lowering this threshold retains more sequences and gives momentum broader influence. Momentum. β∇t−1 β _t-1. The accumulated direction from previous steps. Momentum analogue. mt=Mineβ(M) m_t=Mine_β(M). A persistent test update distilled from recurring failure sequences in memory M, after the latest failed update has been appended. Update with Momentum. ∇t=β∇t−1+(1−β)∂ℒ∂θt _t=β _t-1+(1-β) ∂ _t. Combines instantaneous gradient with momentum to suppress noisy one-step gradients and reinforce consistent directions. Gradient analogue. ∇TestGrad=Optimizer(ℒ,yt,mt) _TestGrad=Optimizer(L,y_t,m_t). Combines current feedback with momentum to suppress one-off noisy edits and reinforce consistent test-improvement directions. State update. θt+1=θt−η∇t _t+1= _t-η _t. Test update. yt+1=yt+∇TestGrad y_t+1=y_t+ _TestGrad, where ∇TestGrad _TestGrad is a combination of CRUD operations on the original test suite. Test Generation for SWE-Agent Ensemble LLM-based agents have transformed automated program repair, with recent systems resolving over half of real-world GitHub issues on SWE-bench (Jimenez et al. 2023). Representative frameworks include Agentless (Xia et al. 2025), which decomposes repair into localization, patch generation, and validation, OpenHands (Wang et al. 2024), which enables interactive repository navigation with tool use, and Lingxi (Lingxi Authors 2025), which guides issue resolution using procedural knowledge from past fixes. Because different SWE agents exhibit complementary strengths (Zhang et al. 2025), ensembling their candidate patches is a natural way to improve Pass@1. The key question is how to generate tests that can distinguish the correct patch from plausible but wrong alternatives. Table 1 summarizes the analogy that motivates TestGRAD: tests are optimized as text-space parameters, CRUD edits instantiate the gradient direction, frequent failure sequences provide momentum, and the LLM agent acts as the optimizer. Create/Delete test pipelines. LIBRO (Kang, Yoon, and Yoo 2023) generates a reproduction test directly from the issue description and ranks candidate patches by pass/fail outcome. Agentless (Xia et al. 2025) follows a related Create-Delete pipeline: it creates a new test from the issue description and removes conflicting tests by name matching. These pipelines provide useful execution evidence, but they are incomplete as test optimizers in three ways. First, their update direction is mostly limited to creating tests, with deletion used only as a coarse cleanup step. They do not read and update the existing test suite, so they miss project-specific fixtures, base classes, helper assertions, and stale assertions that need in-place revision. Second, their objective is not a differential loss over candidate patches. A test may pass or fail, but the generator is not directly optimized to maximize behavioral separation among competing patches. Third, they are largely one-off: once the first generated test is non-discriminative, there is no principled iterative optimization process that turns that failure into the next test-suite update. Agentic test generation. AEGIS (Wang et al. 2025) uses FSM-guided script generation to reproduce bug symptoms as standalone scripts. These scripts verify whether the symptom disappears, but they do not integrate with the project’s native test suite and cannot fully capture behavioral regression. TRAE (Gao et al. 2025) adds agentic browsing over source files to inform test creation, but it still follows a Create/Delete style of test generation, does not optimize a differential loss, and does not maintain momentum across failed test updates. TestGRAD extends this line of work by treating the test suite itself as the optimized object: it reads existing tests, updates stale assertions, creates new discriminative tests, deletes only confirmed obsolete tests, and iteratively evolves the suite using Failure Pattern Momentum. Reflection and Text-Space Optimization Reflexion (Shinn et al. 2023) and Self-Refine (Madaan et al. 2023) introduced the paradigm of linguistic self-reflection: an agent receives execution feedback, generates a natural-language reflection, and uses it to guide subsequent attempts. Language Agent Tree Search (LATS) (Zhou et al. 2024) scales this idea with Monte Carlo Tree Search, using LM-powered value functions to explore the space of possible actions. These frameworks rely on an LLM evaluator to produce the reflection signal, which is costly and may hallucinate for fine-grained code-correctness reasoning. AgentCoder (Huang et al. 2023) instead uses a test executor agent that runs generated tests and feeds the raw execution results back to the programmer agent for refinement, without abstracting recurring failures across attempts. TextGrad (Yuksekgonul et al. 2025) gives this idea a more explicit optimization form: LLM feedback is backpropagated through text variables in a computation graph, so prompts, predictions, code snippets, or other textual components can be improved by natural-language gradients. metaTextGrad (Xu et al. 2025) further studies how to optimize the LLM optimizer itself, adapting both its prompt and structure for a target task. These works motivate our use of gradient-style language for test-suite optimization, but they are general text-optimization frameworks rather than a test-time SWE-agent ensemble method. In our setting, the forward signal is produced by executing candidate patches against tests, the loss is differential over patch outcomes, and the gradient direction is constrained to CRUD edits over the repository test suite. TestGRAD takes a different approach to memory utilization. Rather than summarizing failed attempts with an LLM (Shinn et al. 2023) or feeding raw execution feedback back verbatim (Huang et al. 2023), it applies sequential mining to failure memory. This produces compact maximal frequent subsequences that represent structurally identical strategies across superficially diverse patches. In TestGRAD, these sequences serve as Failure Pattern Momentum: they carry aggregate information about prior non-discriminative directions into the next LLM optimizer step. Unlike similarity-based retrieval (RAG), which returns documents similar to the query and therefore also similar to each other, sequential mining extracts cross-document structure and compresses memory by over 100×100× in practice, keeping the optimizer’s context window available for productive repository reasoning. TestGRAD Framework Table 1 gives the role-level analogy that structures TestGRAD. A test suite is the optimization state, differential execution is the loss, a one-step CRUD edit is the instantaneous gradient, and frequent failure sequences mined from memory are the momentum carried across attempts. The whole method follows the same loop: execute the current test suite, compute the differential loss, update failure memory and momentum, and then back-propagate the signal into the next CRUD test update. Figure 1 shows this end-to-end framework, Figure 2 highlights the derivative step implemented by the LLM optimizer, and Figure 3 zooms into the generic transition from yty_t to yt+1y_t+1 through failure memory and momentum. Figure 1: TestGRAD framework overview. Given an issue and candidate patches from multiple SWE agents, TestGRAD iteratively evolves the repository test suite: the forward pass executes tests to obtain differential loss; failed non-differential updates are stored in failure memory and mined into Failure Pattern Momentum; the backward pass uses the loss and momentum to produce the next CRUD test update. Problem and Test-Space State Let c=(I,ℛ0)c=(I,R_0) denote a SWE-bench instance, where I is the issue description and ℛ0R_0 is the initial repository. A SWE-agent ensemble π1,…,πN\ _1,…, _N\ produces candidate patches =pii=1NP=\p_i\_i=1^N. Applying patch pip_i to ℛ0R_0 yields a candidate repository. The optimization state is the current test suite yty_t. The initial state y0y_0 is the original repository test suite before applying the issue-specific update. Forward Pass: Execute Candidate Patches The forward pass is purely execution-based. Given the current test suite yty_t, TestGRAD runs it against every candidate patch in P and records the pass/fail outcomes: yt→Eval(⋅,)pass/fail outcomes.y_t \; Eval(·,P)\;pass/fail outcomes. (1) A test suite is useful for ensemble selection only if at least one test is differential: it passes on some candidate patches and fails on others. Uniform outcomes do not separate candidates and therefore provide no selection signal. Loss: Differential Execution The loss measures whether the current test suite has produced a differential outcome: ℒ(yt)=0,if yt contains a differential test,1,otherwise.L(y_t)= cases0,&if y_t contains a differential test,\\ 1,&otherwise. cases (2) This is an execution-defined loss, following the differential-testing intuition that behavioral differences across executions expose semantic distinctions (Rao et al. 2025). When ℒ(yt)=0L(y_t)=0, optimization stops immediately. The checker agent is then invoked once, outside the loop and with a separate context, to use the differential result for final patch selection. When ℒ(yt)=1L(y_t)=1, the failed update becomes the optimization signal for the next iteration. Memory Update and Momentum If the current test suite is non-differential, the CRUD update that produced it has failed to separate candidate patches. TestGRAD writes this failed update into failure memory M: M←M∥[∇t−1].M← M \|[ _t-1]. (3) Here ∇t−1 _t-1 is the one-step CRUD update that produced the current failed suite yty_t, and ∥\| appends it to memory so repeated failures remain available for support counting. Instead of replaying all raw failures to the next iteration, TestGRAD mines maximal frequent failure sequences from memory: mt=Mineβ(M).m_t=Mine_β(M). (4) The support threshold β (default β=2β=2) plays the role of retention strength in Table 1. Lowering β retains more recurring failure sequences, giving momentum broader influence; raising β keeps only the most stable recurring sequences. Thus mtm_t is a compact, deterministic momentum signal: it suppresses one-off failed edits and records which directions have already been repeatedly explored, so the next update can move away from the same dead end. Backward Pass: CRUD Test Update The backward pass sends the loss and momentum back to the LLM optimizer. The optimizer produces the next test-space gradient: ∇TestGradt=Optimizer(ℒ,yt,mt). _TestGrad^t=Optimizer(L,y_t,m_t). (5) Figure 2 expands this step as a test-space derivative: the optimizer prompt receives the current suite, the execution-defined loss, and the mined momentum, then returns a CRUD edit that plays the role of ∂ℒ/∂yt /∂ y_t. This gradient is a CRUD edit over the original repository test suite. Read collects repository-specific testing knowledge such as fixtures, imports, assertion utilities, and setup conventions. Create adds new tests, Update revises stale assertions or test bodies, and Delete removes tests confirmed obsolete. Following the textual-gradient view (Yuksekgonul et al. 2025; Xu et al. 2025), these CRUD edits are the gradient direction in text/code space rather than a numerical derivative. The state update is: yt+1=yt+∇TestGradt.y_t+1=y_t+ _TestGrad^t. (6) The new suite yt+1y_t+1 enters the next forward pass. The loop continues until a differential test is found or the iteration budget is exhausted. Figure 3 illustrates this transition: repeated non-discriminative failures update memory and momentum, and the optimizer converts (ℒ,yt,mt)(L,y_t,m_t) into a CRUD edit that yields yt+1y_t+1. Gradient computation for test-space optimization: yt→Evalℒ(yt)→Optimizer∇TestGradty_t \; Eval\;L(y_t) \; Optimizer\; _TestGrad^t ∂ℒ∂yt≡∇LLM(yt,ℒ(yt),mt)≈∇TestGradt ∂ y_t\;≡\; _ LLM (y_t,L(y_t),m_t )\;≈\; _TestGrad^t ∇TestGradt=Optimizer(ℒ,yt,mt),yt+1=yt+∇TestGradt. _TestGrad^t=Optimizer (L,y_t,m_t ), y_t+1=y_t+ _TestGrad^t. Prompt template implementing the derivative. Given issue I, current test suite y_t, execution result loss L(y_t), and momentum m_t: 1. Explain why the current suite is still non-differential. 2. Identify the failed direction preserved in momentum. 3. Return one CRUD update over the original repository tests: Read required test infrastructure; Create new discriminative tests; Update stale assertions or test bodies; Delete only obsolete tests. The operator ∇LLM _ LLM returns natural-language feedback and a concrete CRUD edit rather than a numeric derivative. The differential loss provides the downstream objective, and mtm_t carries recurring failed directions from memory, so the optimizer can update the test suite away from previous non-discriminative attempts. Figure 2: TestGRAD gradient computation in the backward pass. The derivative step is implemented by an LLM optimizer that converts execution-defined loss and Failure Pattern Momentum into a CRUD update over the repository test suite. ⬇ # Read and Reuse: app/warning fixtures # current suite y_t def test_toctree_special_pages( app, status, warning): app.build() warnings = warning.getvalue() assert "...genindex’" not in warnings assert "...modindex’" not in warnings assert "...search’" not in warnings assert ’index’ in app.env.toctree_includes (a) Current suite yty_t: warning check ⬇ Momentum(M): |M|=3 failed suites -> retained frequent sequence -> all converge on warning checking [frequent: support 3/3 ≥β=2≥β=2] app.build() warn = warning.getvalue() assert "...genindex’" not in warn assert "...modindex’" not in warn assert "...search’" not in warn Dead end: "assert no warning" exhausted (3/3 attempts) Steer: inspect AST via assert_node() (b) Momentum mt=Mine(M)m_t= Mine(M) ⬇ # yt+1=yt+∇TestGradty_t+1=y_t+ _TestGrad^t # avoid dead-end warning-check # new: probe toctree AST structure def test_toctree_index(app): app.build() toctree = app.env.tocs[’index’] node = toctree[0][1][1] assert_node(node, addnodes.toctree, caption="Indices", entries=[(None, ’genindex’), (None, ’modindex’), (None, ’search’)]) (c) Updated suite yt+1y_t+1: AST probe Figure 3: TestGRAD momentum-gradient transition from yty_t to yt+1y_t+1, illustrated on sphinx-doc__sphinx-10673. (a) The current suite yty_t checks warning text and yields uniform outcomes (ℒ(yt)=1L(y_t)=1). (b) Failure memory is mined into mtm_t; the highlighted statements form the frequent sequence shared by all three failed suites (support 3≥β3≥β), marking this repeated failed direction as a dead end and steering the optimizer toward AST inspection. (c) The updated suite yt+1y_t+1 probes toctree structure with assert_node(), producing a discriminative signal for the checker. Colors: test momentum . Experimental Setup Metrics. Pass@1: Fraction of the 500 instances resolved under the SWE-bench evaluation harness, after TestGRAD’s checker selects one patch per instance. Ensemble Gain: Absolute improvement in Pass@1 over the best single-agent patch source in our candidate pool (Livesweagent, 79.2%). Dataset. We evaluate on SWE-bench Verified (OpenAI 2024), a human-validated subset of 500 real-world GitHub issues. Candidate patches are drawn from six top-performing SWE-agent leaderboard submissions, added incrementally to form ensembles of size N=1,…,6N=1,…,6: Livesweagent (20251215) (Live SWE-agent 2025), Sonar (20251205) (Sonar 2025), OpenHands (20251127) (Wang et al. 2024), Trae_doubao (20250928) (Gao et al. 2025), Gemini-Live (20251120) (Live SWE-agent 2025), and Atlassian (20250902) (Atlassian 2025). At N=1N=1 (Livesweagent alone), the single-agent Pass@1 is 79.2%, which serves as the baseline for ensemble gain. This construction has two advantages: (1) leaderboard agents produce high-quality and diverse patches, making ensemble selection challenging; (2) all patches are publicly available, ensuring full reproducibility. Baselines. We compare TestGRAD against three ensemble methods. For a fair comparison, all methods receive the same candidate patches and differ only in their ensemble selection module. Augment (Augment Code 2025) follows the LLM-as-a-judge paradigm: the LLM scores each candidate patch against the issue description and selects the most plausible fix without any test execution. Agentless (Xia et al. 2025) generates a new test from the issue description and filters existing tests by name-matching heuristics, then ranks patches by execution outcome. It follows a Create-Delete (C/D) strategy with no repository inspection and no iterative optimization. TRAE (Gao et al. 2025) is an agent-based selector that adds repository browsing to the C/D pipeline. It reads source files to inform test creation and applies name-based deletion to remove conflicting existing tests, but still lacks an Update operation and does not refine failing tests. Implementation. TestGRAD uses three base LLMs interchangeably as its LLM optimizer: Minimax-m2.7 (MiniMax 2025), DeepSeek-v3.2 (DeepSeek-AI 2025), and GLM-5.1 (Zhipu AI 2025). The maximum number of optimization steps is Tmax=8T_ =8. Failure Pattern Momentum uses sequential mining with a minimum support threshold of β=2β=2 (a sequence must appear in at least 2 failed test suites to be reported). All runs execute inside the official SWE-bench Docker images. Results Overall Effectiveness of TestGRAD Table 2 summarizes the Pass@1 performance of all ensemble methods across three base LLMs on SWE-bench Verified. TestGRAD consistently achieves the highest Pass@1 in every configuration: 84.2% with Minimax-m2.7 (+ 5.0), 84.0% with DeepSeek-v3.2 (+ 4.8), and 83.6% with GLM-5.1 (+ 4.4). Augment fails to improve over single-agent performance and even degrades it (- 0.6 to + 0.0), confirming that LLM-as-a-judge scoring is unreliable for patch selection due to positional bias and the absence of execution grounding. Agentless and TRAE show modest improvements of up to + 1.2 and + 1.4, respectively. Both rely on a Create-Delete (C/D) pipeline: they generate new tests while filtering existing ones by test name, lacking holistic test suite understanding (Read) and in-place test updating (Update). TestGRAD surpasses both by 3.4–3.6%, demonstrating the clear benefit of evolving test suites with CRUD gradients and momentum-guided optimization. Table 2: Performance comparison. Gain is computed relative to the baseline Pass@1 (79.2%). Positive gains are shown in green, while negative gains are shown in red. Base LLM Augment Agentless TRAE Ours Pass@1 (%) Gain (%) Pass@1 (%) Gain (%) Pass@1 (%) Gain (%) Pass@1 (%) Gain (%) Minimax-m2.7 79.0 - 0.2 80.4 + 1.2 80.6 + 1.4 84.2 + 5.0 GLM-5.1 78.6 - 0.6 80.2 + 1.0 80.2 + 1.0 83.6 + 4.4 DeepSeek-v3.2 79.2 + 0.0 79.8 + 0.6 80.6 + 1.4 84.0 + 4.8 Impact of Ensemble Size Figure 4 plots Pass@1 as a function of ensemble size N for TestGRAD and TRAE across three LLMs, together with the Oracle and Adversary bounds and the Expected (random-selection) baseline. Table 3 reports the full numerical results for Minimax-m2.7. TestGRAD consistently outperforms TRAE at every ensemble size N≥2N≥2. With Minimax the gap widens from +1.2%+1.2\% at N=2N=2 to +3.6%+3.6\% at N=4N=4, showing that CRUD-gradient updates and momentum become increasingly valuable as the selection task grows harder with more diverse candidates. Optimal ensemble size. Performance peaks at N=4N=4 (Minimax: 84.2%, DeepSeek: 84.0%, GLM: 83.6%) and slightly declines for N=5,6N=5,6. This trend should not be interpreted as a violation of the ensemble principle. When the underlying selection loss is non-convex, increasing ensemble size can produce plateaus, elbows, or even local non-monotonicity rather than a strictly increasing performance curve (Mattei and Garreau 2025). The decline is consistent with the Adversary and Expected curves, which also decrease beyond N=4N=4 (Expected: 79.2% → 78.7%): adding weaker agents (Gemini-Live at 77.4%, Atlassian at 76.8%) increases candidate noise and lowers the probability that a simple selector chooses a correct patch, even though the Oracle ceiling can still rise. Despite this, TestGRAD remains well above the Expected baseline for all N≥2N≥2, confirming it extracts reliable discriminative signal even from large candidate sets. At N=4N=4 the Oracle is 87.0%, leaving a 2.8% gap to TestGRAD (84.2%). This gap represents instances where a correct patch exists but the generated tests fail to discriminate it from incorrect candidates. Figure 4: Pass@1 vs. ensemble size for TestGRAD (green) and TRAE (orange), together with Oracle (blue dashed), Adversary (red dashed), and Expected (purple dotted) bounds. Results shown for Minimax, DeepSeek, and GLM (left to right). Table 3: Pass@1 across ensemble sizes (TestGRAD, Minimax-m2.7). Agent N Adv. Exp. Oracle P@1 Livesweagent 1 79.2 79.2 79.2 79.2 +Sonar 2 76.8 79.8 82.8 81.2 +OpenHands 3 74.6 79.3 83.4 81.2 +Trae_doubao 4 70.2 79.2 87.0 84.2 +Gemini 5 68.4 79.1 88.0 83.8 +Atlassian 6 66.8 78.7 88.0 83.4 Table 4: Ablation study on SWE-bench Verified (Minimax-m2.7). Model Setting P@1 Δ TestGRAD Complete 84.2 – TestGRADw/o Read TestGRAD_w/o Read w/o suite understanding 81.2 -3.0 TestGRADw/o Update TestGRAD_w/o Update w/o updating tests 81.8 -2.4 TestGRADw/o R+U TestGRAD_w/o R+U w/o Read and Update 79.4 -4.8 TestGRADw/o Diff Loss TestGRAD_w/o Diff Loss pass-count selection 80.8 -3.4 TestGRADw/o Momentum TestGRAD_w/o Momentum w/o failure momentum 82.6 -1.6 TestGRADw/o Opt TestGRAD_w/o Opt w/o iterative optimizer 75.0 -9.2 Contribution of Differential Loss and CRUD Gradients Table 4 reports the ablation results on Minimax-m2.7. We focus here on differential loss and the two CRUD-gradient components unique to TestGRAD: Read (test suite understanding) and Update (in-place test modification). Because the complete system and each ablation are evaluated on the same SWE-bench Verified instances, we use a paired hypothesis test rather than compare unpaired aggregate Pass@1 values. Specifically, we collect multiple paired overall Pass@1 results for the complete TestGRAD and each ablation variant, and apply a two-sided Wilcoxon signed-rank test (Wilcoxon 1945) at significance level α=0.05α=0.05. The complete TestGRAD shows a statistically significant advantage over every ablated variant, with all p-values below 7.32×10−37.32× 10^-3. The Pass@1 drops in Table 4 are then interpreted as effect sizes. For the non-differential-loss ablation, we replace the differential stopping criterion and checker-based final selection with a pass-count rule: after executing the generated tests on all candidate patches, the candidate that passes the largest number of tests wins. This variant tests whether ordinary test-pass maximization is sufficient, as opposed to explicitly optimizing for a test whose outcomes differ across candidates. Recent empirical evidence on SWE-bench further cautions against this assumption: patches that pass benchmark tests can still be behaviorally divergent from developer-written fixes, and differential patch testing exposes discrepancies missed by ordinary validation tests (Wang, Pradel, and Liu 2026). Effect of Differential Loss. Replacing differential loss with pass-count selection reduces Pass@1 from 84.2% to 80.8% (Δ=−3.4% =-3.4\%). This shows that simply rewarding the patch that passes the most generated tests is not enough for ensemble selection: pass count measures compatibility with the current generated tests, not agreement with the intended fix. Because tests are not exhaustive, a broadly plausible but incorrect patch may pass many weak tests, while a correct patch can fail a stale or mis-specified one. The differential objective instead searches for tests that separate candidate behavior before the checker is invoked. Effect of Read. Removing test suite understanding (TestGRADw/o Read TestGRAD_w/o Read) drops Pass@1 from 84.2% to 81.2% (Δ=−3.0% =-3.0\%), the largest CRUD-component drop. Without Read, the agent cannot discover existing fixtures, base test classes, or helper functions. Generated tests therefore rely on bare Python imports and ad-hoc setups that frequently fail to run in the project’s test runner or exercise shallower code paths than tests built on top of the project’s own infrastructure. This confirms that understanding the repository’s testing conventions is the most critical prerequisite for a useful test-suite gradient. Effect of Update. Removing in-place test updating (TestGRADw/o Update TestGRAD_w/o Update) drops Pass@1 from 84.2% to 81.8% (Δ=−2.4% =-2.4\%). When Update is disabled, tests that assert old expected values are deleted rather than corrected. This breaks regression checks, since these tests still encode the correct behavioral constraints and only require updated assertions. The −2.4%-2.4\% drop shows that deletion-only handling introduces wrong selection and weakens the differential signal of the test suite. Joint effect of Read and Update. Removing both components (TestGRADw/o R+U TestGRAD_w/o R+U) further reduces Pass@1 to 79.4% (Δ=−4.8% =-4.8\%). This variant is close to a pure Create/Delete-style test generator: it neither grounds new tests in the repository’s existing test infrastructure nor repairs stale assertions in existing tests. The larger combined drop shows that Read and Update are complementary CRUD directions. Read supplies the project-specific context needed to make generated tests executable, while Update preserves and corrects high-signal tests that would otherwise be discarded. Impact of Failure Pattern Momentum and Token Efficiency We evaluate the momentum mechanism from two angles: (1) its contribution to Pass@1 via the ablation study, and (2) its token efficiency advantage over raw memory accumulation. Performance impact. From Table 4, TestGRADw/o Momentum TestGRAD_w/o Momentum drops Pass@1 from 84.2% to 82.6% (Δ=−1.6% =-1.6\%). While the gap is smaller than Read or Update in isolation, Failure Pattern Momentum provides a qualitatively different benefit: it operates across iterations, distilling accumulated failure history into compact momentum that steers the optimizer away from dead ends. The larger baseline gap of −9.2%-9.2\% for TestGRADw/o Opt TestGRAD_w/o Opt (75.0%) confirms that iterative optimization as a whole is essential, and momentum is the mechanism that makes this optimization efficient rather than redundant. Token efficiency. Figure 5 illustrates the token cost of the two strategies across optimization iterations. Raw Memory accumulates all previously failed test suites verbatim; its token count grows steadily, reaching about 1.9K–13.6K tokens by iteration 5. Momentum extracts maximal frequent subsequences from the same corpus, producing a concise momentum context that grows far more slowly, remaining on the order of tens to about a hundred tokens across iterations. The compression ratio exceeds 100×100× for DeepSeek at later iterations and stays between 25×25× and 40×40× for GLM and Minimax, meaning the model receives equivalent or richer structural guidance at a fraction of the context cost. This is particularly important because excessive context length degrades LLM reasoning quality (Liu et al. 2023) and inflates API costs. Figure 5: Average token consumption of Raw Memory (dark gray) vs. Momentum (coral) across optimization iterations, shown on a log scale for DeepSeek, GLM, and Minimax. Italic labels denote representative compression ratios (Raw / Momentum); ratios above 100×100× are capped as >100x>100x. Conclusion We presented TestGRAD, a momentum-gradient optimizer for iterative test-space optimization. Following the analogy in Table 1, TestGRAD treats the current test suite as the optimization state, differential execution as the loss, a one-step CRUD test update as the instantaneous gradient, and Failure Pattern Momentum as the retained direction. The LLM optimizer uses this feedback to evolve discriminative test suites, while the checker is invoked only after zero-loss differential execution for final patch selection. On SWE-bench Verified, TestGRAD achieves 84.2% Pass@1 with a 4-agent ensemble, outperforming the strongest baseline by 3.6%. Failure Pattern Momentum also acts as a compact retention mechanism, preserving repeated failed update directions from failure memory while reducing raw failure-history context by over 100×100×. References Atlassian (2025) Atlassian. 2025. Atlassian SWE Agent. Accessed 2025-12-15. Augment Code (2025) Augment Code. 2025. Augment Code: The Most Powerful AI Software Development Platform Backed by the Industry-Leading Context Engine. Accessed 2025-06-10. DeepSeek-AI (2025) DeepSeek-AI. 2025. DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models. arXiv preprint arXiv:2512.02556. Gao et al. (2025) Gao, P.; Tian, Z.; Meng, X.; Wang, X.; Hu, R.; Xiao, Y.; Liu, Y.; Zhang, Z.; Chen, J.; Gao, C.; et al. 2025. Trae agent: An llm-based agent for software engineering with test-time scaling. arXiv preprint arXiv:2507.23370. Huang et al. (2023) Huang, D.; Bu, Q.; Zhang, J. M.; Luck, M.; and Cui, H. 2023. AgentCoder: Multi-Agent-based Code Generation with Iterative Testing and Optimisation. arXiv preprint arXiv:2312.13010. Jimenez et al. (2023) Jimenez, C. E.; Yang, J.; Wettig, A.; Yao, S.; Pei, K.; Press, O.; and Narasimhan, K. 2023. SWE-bench: Can Language Models Resolve Real-world GitHub Issues? arXiv preprint arXiv:2310.06770. Kang, Yoon, and Yoo (2023) Kang, S.; Yoon, J.; and Yoo, S. 2023. Large Language Models are Few-shot Testers: Exploring LLM-based General Bug Reproduction. In Proceedings of the 45th IEEE/ACM International Conference on Software Engineering, 2312–2323. Lingxi Authors (2025) Lingxi Authors. 2025. Lingxi Replication Package. Liu et al. (2023) Liu, N. F.; Lin, K.; Hewitt, J.; Paranjape, A.; Bevilacqua, M.; Petroni, F.; and Liang, P. 2023. Lost in the Middle: How Language Models Use Long Contexts. arXiv preprint arXiv:2307.03172. Live SWE-agent (2025) Live SWE-agent. 2025. Live SWE-agent. Accessed 2025-12-15. Madaan et al. (2023) Madaan, A.; Tandon, N.; Gupta, P.; Hallinan, S.; Gao, L.; Wiegreffe, S.; Alon, U.; Dziri, N.; Prabhumoye, S.; Yang, Y.; et al. 2023. Self-Refine: Iterative Refinement with Self-Feedback. Advances in Neural Information Processing Systems. Mattei and Garreau (2025) Mattei, P.-A.; and Garreau, D. 2025. Are Ensembles Getting Better All the Time? Journal of Machine Learning Research, 26(201): 1–46. MiniMax (2025) MiniMax. 2025. MiniMax API Documentation. Accessed 2025-09-12. Mündler et al. (2025) Mündler, N.; Müller, M. N.; He, J.; and Vechev, M. 2025. SWT-Bench: Testing and Validating Real-World Bug-Fixes with Code Agents. arXiv:2406.12952. OpenAI (2024) OpenAI. 2024. Introducing SWE-bench Verified. Accessed 2025-07-10. Polyak (1964) Polyak, B. T. 1964. Some methods of speeding up the convergence of iteration methods. USSR Computational Mathematics and Mathematical Physics, 4(5): 1–17. Rao et al. (2025) Rao, N.; Gilbert, E.; Green, H.; Ramananandro, T.; Swamy, N.; Goues, C. L.; and Fakhoury, S. 2025. DiffSpec: Differential Testing with LLMs using Natural Language Specifications and Code Artifacts. arXiv:2410.04249. Se and Vert (2025) Se, K.; and Vert, A. 2025. What is Test-time Compute and How to Scale It? Accessed 2025-05-25. Shinn et al. (2023) Shinn, N.; Cassano, F.; Gopinath, A.; Narasimhan, K.; and Yao, S. 2023. Reflexion: Language Agents with Verbal Reinforcement Learning. In Advances in Neural Information Processing Systems. Sonar (2025) Sonar. 2025. Sonar SWE Agent. Accessed 2025-12-15. Sutskever et al. (2013) Sutskever, I.; Martens, J.; Dahl, G.; and Hinton, G. 2013. On the importance of initialization and momentum in deep learning. In Proceedings of the 30th International Conference on Machine Learning, 1139–1147. SWE-bench (2025) SWE-bench. 2025. SWE-bench Verified Leaderboard. Accessed 2025-12-15. Wang et al. (2023) Wang, P.; Li, L.; Chen, L.; Zhu, D.; Lin, B.; Cao, Y.; Liu, Q.; Liu, T.; and Sui, Z. 2023. Large Language Models are not Fair Evaluators. arXiv preprint arXiv:2305.17926. Wang et al. (2025) Wang, X.; Gao, P.; Meng, X.; Peng, C.; Hu, R.; Lin, Y.; and Gao, C. 2025. AEGIS: An Agent-based Framework for Bug Reproduction from Issue Descriptions. In Proceedings of the 33rd ACM International Conference on the Foundations of Software Engineering, FSE Companion ’25, 331–342. New York, NY, USA: Association for Computing Machinery. ISBN 9798400712760. Wang et al. (2024) Wang, X.; Li, B.; Song, Y.; Xu, F. F.; Tang, X.; Zhuge, M.; Pan, J.; Song, Y.; Li, B.; Singh, J.; et al. 2024. OpenHands: An Open Platform for AI Software Developers as Generalist Agents. arXiv preprint arXiv:2407.16741. Wang, Pradel, and Liu (2026) Wang, Y.; Pradel, M.; and Liu, Z. 2026. Are “Solved Issues” in SWE-bench Really Solved Correctly? An Empirical Study. In Proceedings of the IEEE/ACM International Conference on Software Engineering. Wilcoxon (1945) Wilcoxon, F. 1945. Individual Comparisons by Ranking Methods. Biometrics Bulletin, 1(6): 80–83. Xia et al. (2025) Xia, C. S.; Deng, Y.; Dunn, S.; and Zhang, L. 2025. Demystifying LLM-Based Software Engineering Agents. Proc. ACM Softw. Eng., 2(FSE). Xu et al. (2025) Xu, G.; Yuksekgonul, M.; Guestrin, C.; and Zou, J. Y. 2025. metaTextGrad: Automatically Optimizing Language Model Optimizers. In Advances in Neural Information Processing Systems. Yuksekgonul et al. (2025) Yuksekgonul, M.; Bianchi, F.; Boen, J.; Liu, S.; Huang, Z.; Guestrin, C.; and Zou, J. 2025. Optimizing Generative AI by Backpropagating Language Model Feedback. Nature, 639: 609–616. Zhang et al. (2025) Zhang, K.; Yao, W.; Liu, Z.; et al. 2025. Diversity Empowers Intelligence: Integrating Expertise of Software Engineering Agents. In International Conference on Learning Representations. Zheng et al. (2024) Zheng, C.; Zhou, H.; Meng, F.; Zhou, J.; and Huang, M. 2024. Selection Biases in Large Language Models. In Findings of the Association for Computational Linguistics. Zhipu AI (2025) Zhipu AI. 2025. GLM Model Documentation. Accessed 2025-09-12. Zhou et al. (2024) Zhou, A.; Yan, K.; Shlapentokh-Rothman, M.; Wang, H.; and Wang, Y.-X. 2024. Language Agent Tree Search Unifies Reasoning, Acting, and Planning in Language Models. In International Conference on Machine Learning. Supplementary Material for TestGRAD 1University of Manitoba, Winnipeg, Canada 2Huawei Canada, Markham, Canada 3Huawei Technologies, Hangzhou, China hep2@myumanitoba.ca, shaowei.wang@umanitoba.ca jiayuan.zhou1@huawei.com, panruiqi@huawei.com Appendix A Motivation In this section, we illustrate why CRUD-gradient updates over the original test suite are necessary, and why Failure Pattern Momentum is essential for effective iterative optimization. (A) Naive Test Generation (CD) Create a test to reproduce the issue from the description. ⟨ ⟩ ⬇ # Must implement all setup manually import django os.environ[’DJANGO_SETTINGS_MODULE’]= ’repro_settings’ django.setup() class Place(models.Model): class Meta: app_label=’repro’ class ParkingLot(Place): parent=OneToOneField(Place,CASCADE) class Meta: app_label=’repro’ with assertRaises(ImproperlyConfigured): ParkingLot.check() # tests OLD behavior -- non-discriminative Delete tests that conflict with the patch. ⟨ _name_list⟩ ⬇ test_missing_parent_link, test_onetoone_with_parent, test_m2m_table_name_clash, test_no_clash_for_parent_ptr # deleted by name-match heuristic # correct test discarded too (B) CRUD Gradient on django__django-12325 Read: Test Suite Understanding (tests/invalid_models_tests/) ⬇ @isolate_apps(’invalid_models_tests’) class InvalidModelsTests( SimpleTestCase): def test_missing_parent_link(self): with self.assertRaisesMessage( ImproperlyConfigured, msg): self.assertEqual(Model.check(), []) self.assertEqual(Model.check(), [Error(id=...)]) from django.core.checks import Error, Warning Create new discriminative test ⬇ + @isolate_apps( + ’invalid_models_tests’) + class TestParentLink( + SimpleTestCase): + def test_onetoone_parent(self): + class Place(models.Model): pass + class ParkingLot(Place): + other = OneToOneField( + Place, CASCADE, + related_name=’other_parking’) + self.assertEqual( + ParkingLot.check(), []) reused from Read Update existing test assertion ⬇ def test_render(self): OneToOneField( ’migrations.Tag’, CASCADE, - parent_link=False, + parent_link=True, primary_key=True, to_field=’id’, serialize=False, ...) Delete stale test ⬇ - def test_missing_link(self): - msg = (’Add parent_link=True’ - ’ to ParkingLot.parent.’) - with self.assertRaisesMessage( - ImproperlyConfigured, msg): - class ParkingLot(Place): - parent=OneToOneField( - Place, CASCADE) - ParkingLot.check() Figure 1: (A) CD-only generation produces a reproduction script that must hand-roll all setup boilerplate and tests the old exception-raising behavior, making it non-discriminative; tests are deleted by name heuristic, discarding valid ones. (B) TestGRAD applies a CRUD gradient: it reads the test suite first to extract infrastructure (@isolate_apps, SimpleTestCase, .check() convention), creates a grounded test reusing that infrastructure (blue = reused from Read), updates the expected model state in test_render, and semantically deletes test_missing_parent_link whose expected exception is no longer raised after the fix. Instance: django__django-12325. CRUD Gradient over Test Suites Figure 1 contrasts two test generation strategies on django__django-12325, a bug where OneToOneField to a parent model should implicitly set parent_link=True instead of raising ImproperlyConfigured. The fix changes an exception-raising behavior into a silently-accepted one, making test design non-trivial: a test must assert the new correct behavior, not merely reproduce the old crash. We use this instance to identify two critical gaps in existing C/D-only (Create + Delete) approaches. Read. Generating a test without first inspecting the repository forces the agent to reconstruct from scratch everything the project already provides. As shown in Figure 1(A), the C/D-only reproduction script must manually configure DJANGO_SETTINGS_MODULE, call django.setup(), and declare app_label in every model’s Meta class, boilerplate that Django’s own test suite has long abstracted away behind the @isolate_apps decorator. Beyond verbosity, this hand-rolled setup is fragile: without the app registry being properly initialized, ParkingLot.check() may raise an unrelated AppRegistryNotReady error rather than the assertion under test. Even when it does run, the reproduction script asserts that ImproperlyConfigured is raised, the old behavior, so it passes on both the correct and incorrect patches and is therefore invalid. In contrast, TestGRAD begins by reading tests/invalid_models_tests/, extracting four pieces of infrastructure: the @isolate_apps decorator, the SimpleTestCase base class, the Model.check() → [] assertion convention, and the Error/Warning imports. The subsequently created test in Figure 1(B) reuses all four elements (highlighted in blue) and requires no configuration boilerplate. Because it is executed by Django’s standard test runner inside the existing test environment, infrastructure errors are eliminated and the assertion directly targets the new correct behavior. Update. A correct patch does not always add behavior. It often changes expected values that existing tests already assert. In django__django-12325, the fix causes OneToOneField to acquire an implicit parent_link=True attribute, which alters the serialized migration state that test_render inspects. The original test_render does not include parent_link=True in its expected field kwargs, so after the correct patch is applied, test_render fails, not because the patch is wrong, but because the test asserts the old (now-incorrect) behavior. A C/D-only pipeline resolves this conflict in one of two ways, both harmful. If it deletes test_render by name-based heuristics, it discards a structurally sound test that could have been a strong discriminator after a one-line edit. If it leaves test_render unchanged, the test penalizes the correct patch: it passes on every incorrect patch (which does not change field serialization) and fails on the correct one, inverting the desired discrimination signal. TestGRAD applies an Update operation instead: it inserts parent_link=True into the expected kwargs of test_render, aligning the assertion with the correct behavior while preserving the test’s full discriminative structure. The updated test then passes exactly on the correct patch and fails on the rest, becoming a genuine discriminative signal. These two gaps, infrastructure-unaware test generation and destructive handling of behavior-changing patches, motivate using CRUD as the gradient direction over the test suite rather than a conventional C/D pipeline. Failure Pattern Momentum Momentum in iterative test optimization relies on conditioning on past history. However, how these failures are represented introduces critical limitations. Existing approaches typically adopt one of two strategies. As discussed in the main paper, one line of work summarizes failures using an additional LLM, while another directly appends raw failed history to the model input. Both strategies are problematic. LLM-based summarization incurs additional inference cost at every iteration, and its outputs may omit or distort key structural details due to abstraction or hallucination. In contrast, directly injecting raw failure history preserves full information but leads to rapidly growing context size and severe redundancy, as many failed test suites correspond to the same underlying strategy. This redundancy is not merely a matter of efficiency. As illustrated in Figure 3(b) of the main paper, independently generated failed test suites often share the same core logic despite superficial differences. When presented in raw form, such failures create an illusion of diversity, causing the optimizer to repeatedly explore equivalent strategies under different surface realizations. Moreover, as failure memory grows, redundant patches occupy an increasing fraction of the context window, crowding out essential information such as the issue description and repository context, and leaving less capacity for effective reasoning. Overall, existing failure representation strategies either sacrifice fidelity (LLM summarization) or scalability (raw history), and neither provides a compact, faithful abstraction of recurring failure modes. TestGRAD therefore treats maximal frequent failure sequences as momentum: a compact, deterministic signal that carries prior failed directions into the next CRUD update. Appendix B Human–LLM Collaboration for Aspect Discovery in Test Suite Understanding What the Read step collects. In the Method section, the Read step collects repository-specific test infrastructure before any CRUD update is written. In practice, this means that the optimizer first extracts a compact checklist of reusable testing knowledge from the target repository. The checklist has six categories: • project API imports and module paths; • project-specific assertion utilities and call signatures; • setUp/setUpTestData bodies and conftest.py fixtures; • test base classes and inheritance structure; • expected literal values and behavioral contracts from similar tests; • shared helper or factory functions defined in the test module. These aspects are derived empirically from SWE-bench training instances, as described below. Methodology. We sample 200 instances from SWE-bench, excluding SWE-bench Verified to avoid data leakage. For each instance, Minimax-m2.7 analyzes the ground-truth test file and summarizes the test-suite understanding aspects. Aspects present in fewer than 50% of instances are discarded. This threshold ensures that retained aspects are sufficiently pervasive across repositories; aspects below this threshold tend to reflect repository-specific idioms (e.g., custom database fixtures in a single project) and do not generalize well. The remaining six aspects form the final taxonomy used by the Read step. Human–LLM validation. To assess annotation reliability, one of the authors independently re-labels a random subset of 40 instances (20% of the sample) without access to the LLM outputs. Agreement between the human annotator and the LLM reaches a Cohen’s κ score of 0.82, indicating almost perfect agreement and suggesting that the LLM annotations do not introduce systematic bias. Findings. Table 1 reports the frequency of each retained aspect. All six aspects appear in over 60% of test files, confirming that they capture pervasive conventions rather than repository-specific idioms. Project APIs / Imports and Assertion Conventions are the most universal (>90%>90\%), as nearly all test files import project modules and rely on project-specific assertion utilities (e.g., assertQuerysetEqual, assert_array_equal). Fixtures and Test Base Classes appear in roughly 80% of instances, reflecting the prevalence of Django-style TestCase inheritance and pytest conftest.py conventions. Expected Values and Helper Functions are present in about two-thirds of test files, typically in suites with shared data builders or custom matchers. Table 1: Frequency of the six retained test-suite understanding aspects across 200 sampled SWE-bench instances (SWE-bench Verified excluded). Frequency is the fraction of instances where the aspect is present in the target test file. The six discarded aspects each fell below 50%. Aspect Typical evidence Freq. (%) Cohen’s κ Project APIs / Imports from django.core.checks import Error 96 0.91 Assertion Conventions self.assertQuerysetEqual(...), assert_array_equal 91 0.88 setUp / Fixtures setUp(), setUpTestData(), conftest.py 83 0.84 Test Base Classes class MyTest(SimpleTestCase): 79 0.86 Expected Values literals in assertEqual, docstring examples 71 0.79 Helper Functions make_response(), assert_called_with(...) 64 0.76 These six aspects instantiate the Read operation used by TestGRAD. By requiring the agent to locate repository infrastructure before any CRUD update is written, TestGRAD grounds generation in the project’s own abstractions rather than reconstructing them from scratch, the failure mode of C/D pipelines discussed in the Method section. Appendix C Overhead Analysis Table 2: Average per-instance overhead across methods and base LLMs. Time is in minutes; tokens are in thousands (K). TestGRAD values are measured from run logs; baseline values are estimated from conversation logs and API call traces. Metric Method Minimax-m2.7 DeepSeek-v3.2 GLM-5.1 Avg. Time (min) Augment 1.3 1.8 1.4 Agentless 7.2 8.6 7.5 TRAE 19.3 26.7 20.8 TestGRAD 12.2 23.0 20.7 Avg. Tokens (K) Augment 2.8 3.2 2.9 Agentless 14.8 16.2 15.3 TRAE 318 412 334 TestGRAD 670 1,670 1,307 Table 2 reports average per-instance time and token consumption across all four methods and three base LLMs. Sources of overhead. TestGRAD’s token cost is higher than all baselines for two structural reasons. First, the Read step issues repository exploration calls once per generation round to extract test-suite understanding. Second, TestGRAD may run up to Tmax=8T_ =8 momentum-guided optimization steps per instance, which raises the average token cost to 670K–1,670K per instance. By contrast, Augment and Agentless are one-shot LLM calls, and TRAE runs a single agentic pass without iterative feedback, so their token budgets are structurally lower. This overhead is the direct cost of two design choices: holistic test-suite understanding and iterative momentum optimization, which account for most of the accuracy gain. Time. Despite the higher token count, TestGRAD’s time is shorter than TRAE on all three base LLMs (e.g., 12.2 vs. 19.3 min on Minimax-m2.7), because optimization steps run sequentially only when needed and early stopping applies once a discriminative test is found. Agentless and Augment are faster but operate in a one-shot regime, foregoing the +9.2%+9.2\% gain that iterative optimization provides. Accuracy–cost tradeoff. For applications where selection quality is critical, where a wrong patch propagates a bug to production, the additional token cost translates directly into +5.0% Pass@1 over the single-agent baseline and +3.6% over the next-best method. Reducing overhead further (e.g., by capping TmaxT_ or pruning the Read step) is straightforward at the cost of proportionally lower accuracy, and we leave adaptive budget allocation to future work.