Software workflows · Research feature

Counterfactual Rollout Replay: Forkable Environments as Free Process Rewards for Software Engineering Agents

The researchers introduce Counterfactual Rollout Replay (CRR), a training-time procedure that uses forkable executable environments to obtain step-level return contrasts.

Adapted from research by Yuanhao Li, Hongbo Wang, Xuhong Chen and colleagues.

arXiv preprint revision · 2026-10-03 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Authors’ overview

Outcome-only reinforcement learning gives software engineering (SWE) agents a terminal success signal but little direct guidance about intermediate decisions. We introduce Counterfactual Rollout Replay (CRR), a training-time procedure that uses forkable executable environments to obtain step-level return contrasts. CRR selects a small set of decision points, restores each state, samples an alternative action, and rolls the branch forward under the policy. It retains the realised training trajectory and replaces the advantage at selected steps with the difference between its terminal return and the sampled counterfactual return. The method needs no human process labels or learned process reward model; free refers to those supervision costs, not replay compute. With a 14B policy, CRR improves pass@1 on SWE-bench Verified, SWE-bench Live, and SWE-rebench, and combines with process-reward and trajectory-search methods. On SWE-bench Verified, an equal-wall-clock comparison on the same hardware yields 41.7% versus 36.7% for extended outcome-only GRPO, a 5.0-point gain with fork overhead included. These results apply to environments with affordable, reliable state restoration; stochastic continuations and expensive or imperfect replay remain limitations.

Introduction

Software engineering agents solve repository-level issues through sequences of file inspection, code edits, shell commands, and tests. Benchmarks such as SWE-bench and executable training environments such as SWE-Gym and SWE-rebench make terminal-verifier reinforcement learning practical. PPO- and GRPO-style updates can improve task success, but a trajectory-level advantage does not distinguish a useful localisation decision from a later edit that breaks the patch. Learned process rewards and search provide alternative sources of guidance. We investigate whether executable alternatives can instead provide a training-time credit signal.

Repository-level SWE agents and benchmarks

Tool-using agents such as ReAct established the reasoning-and-acting loop for language models, and SWE-bench reframed this loop as repository-level GitHub issue resolution. Subsequent systems improved the agent-computer interface, search pipeline, and multi-agent scaffold: SWE-agent tailored file editing and test execution to autonomous agents; AutoCodeRover, MAGIS, LingmaAgent, HyperAgent, and OpenHands developed increasingly capable repository-level scaffolds and platforms. Benchmarking has also moved toward cleaner and fresher evaluation through SWE-bench Verified, SWE-bench Live, SWE-bench+, multilingual or re-collected SWE tasks, and adversarial or audit-style reassessments. Complementary microbenchmarks probe dependency-version constraint semantics with machine-checkable answers. CRR is complementary to this line: it changes the training-time advantage estimator rather than the scaffold, benchmark, or verifier.

RLVR training for software engineering agents

Recent SWE-agent training systems move beyond prompting by optimising code policies against executable feedback. RLEF grounds code policies in execution feedback, SWE-Gym provides thousands of executable Python tasks for training agents and verifiers, and recent pipelines such as SoRFT, SWE-Fixer, SWE-Lego, Murphy, SkyRL-Agent, SWE-Dev, and SWE-MiniSandbox refine SFT, RL objectives, and infrastructure efficiency. Fine-grained studies of supervised fine-tuning also identify cases of incomplete learning. The underlying optimisation machinery follows PPO-style clipped policy gradients and GRPO-style group-relative advantages introduced for mathematical reasoning and scaled in RLVR systems. These pipelines make training possible, but their reward signal remains sparse and trajectory-level; CRR targets this credit-assignment bottleneck.

Process rewards and multi-turn credit assignment

One response to sparse terminal rewards is to train or infer dense process feedback. Process-supervised reward models, implicit rewards such as PRIME, rubric-based SWE PRMs, execution-free feedback models, and self-evolved reasoning rewards all provide denser supervision than a terminal pass bit. Structured auxiliary tasks provide another form of process supervision for multimodal decisions, while generative reward modelling can allocate reasoning according to internal uncertainty. For LLM-based evaluation, distinguish within-prompt sampling noise from between-prompt variation in LLM judges and derive debiased estimators of quadratic prompt instability. A parallel line imposes structure on long-horizon trajectories through hierarchical agent RL, hindsight or belief-update credit assignment, and trajectory-search rollouts. Scoring-based selection of multilingual reasoning paths has also been used to construct fine-tuning data. CRR differs mechanistically: it does not learn a process reward model, infer credit from text, or select the best branch. It executes a counterfactual branch in the real SWE environment and uses the observed return differential as a training-time advantage signal.

Counterfactual and causal credit assignment

Counterfactual credit assignment has a pre-LLM history in RL. Future-conditional baselines separate skill from luck by learning hindsight-conditioned value functions, while counterfactual data augmentation and causal approaches manufacture alternative transitions under structural assumptions. Counterfactual reasoning has also been studied in multi-agent communication and information-theoretic credit assignment, and recent LLM-agent work adapts contextual counterfactual credit to multi-agent collaboration. These works generally learn, model, or infer counterfactual outcomes; CRR exploits the special forkability of containerised SWE tasks to execute selected counterfactuals directly.

Execution feedback also supports LLM-driven optimisation of programmatic policies and other artefacts. The environmental property we use is not forkability in the abstract: games and simulators may also restore state, but SWE repositories can be restored cheaply, exactly, and auditably from a commit and executable environment. Containerised SWE infrastructures such as SWE-Gym, OpenHands, and SWE-MiniSandbox make this practical during training, and CRR can be viewed as a Dyna-style use of the real environment as the model rather than a learned simulator. Inference-time tree search and test-time scaling for coding agents also branch environments, but they use branches to choose better completions or rollout continuations. The interplay between search algorithms and reward design has also been surveyed. CRR uses forks differently: a branch is replayed to estimate what the realised action contributed relative to a plausible alternative, not to replace the behaviour policy’s chosen action.

Tree-based training and uncertainty-guided branching

Branching also supports training-time credit assignment: Tree-GRPO shares rollout prefixes and combines intra-tree and inter-tree group-relative advantages derived from outcome rewards. This is distinct from inference-time best-first search for selecting action trajectories and from Entropy-Guided Branching, which replays alternative actions at high-entropy steps to repair failed tool-use trajectories. CRR instead retains the realised on-policy trajectory and uses environment-executed alternative-action contrasts to score selected decisions during training. Its contribution is therefore this credit-assignment construction in forkable SWE environments, rather than branching or entropy-based selection alone.

Data and evaluation

The post-filter training corpus contains 3,638 deterministic instances: 2,438 admitted SWE-Gym tasks and 1,200 admitted SWE-rebench tasks. These counts follow the three-rerun filter (Section F). The SWE-rebench training/evaluation split precedes filtering and excludes overlap by task identity, issue/PR URL, collection month, repository commit window, and exact or near-duplicate issue/patch content. We evaluate greedy pass@1 with a 50-turn cap on SWE-bench Verified, SWE-bench Live, and held-out SWE-rebench Python tasks. Main results are means and standard deviations across three random seeds.

Sampling Consistency and Counterfactual Quality

The appendix further tests how the fork budget is allocated and whether counterfactual quality explains the gain. Among 20,000 logged forks, 12% use an immediately invalid alternative; this class contributes 8% of a class-mean plug-in contrast diagnostic. This diagnostic is not a decomposition of the total training gradient. A validity-filtered proposal changes pass@1 from 36.2% to 36.4% in the reduced-budget, single-seed comparison, which does not establish equivalence. Selector-alignment probes find enrichment for patch-relevant edits and large sampled contrasts, without identifying per-step causality. Controlled replay-noise experiments show gradual degradation in the tested setting; averaging multiple counterfactuals does not generally remove systematic replay bias. Severe trajectory-length heterogeneity remains unresolved. Section P gives the full protocols and diagnostics.

Limitations

CRR requires affordable, reliable forks and a trustworthy terminal verifier. Expensive restoration can erase its resource-efficiency advantage, and the reported operating points do not isolate severe trajectory-length skew. The reduced-budget noise experiments test a controlled injection protocol; averaging multiple continuations does not remove systematic replay bias. Deterministic transitions also leave future policy-sampling variance intact. Our unbiasedness result concerns a fixed-index contrast, whereas the implemented selector induces a weighted training objective without an established convergence guarantee. The selector-alignment diagnostics provide decision-relevance proxies, not proof of per-step causality. Additional boundary cases and cost diagnostics appear in Section M.

Broader impact

Better SWE agents can support software maintenance, while executable counterfactual traces make their training signals more inspectable. The same capabilities can accelerate malicious software development, and verifier-coupled training can exploit incomplete tests or harnesses. CRR does not resolve these risks. We recommend adversarial test-suite hardening, execution-free corroboration such as SWE-RM, and documentation of replay traces and verifier limitations when releasing training artefacts.

Conclusion

CRR uses executable counterfactual continuations to score selected actions while retaining the realised training trajectory. It requires neither process labels nor a learned reward model, but charges the additional replay compute. The reported experiments show improved pass@1 across three SWE benchmarks and an equal-wall-clock gain over vanilla GRPO on Verified. Its practical value depends on affordable, reliable forkability; understanding replay noise, selector weighting, and heterogeneous trajectory costs remains an important direction.

Tool catalogue

The agent has five tools: view_file(path, start, end) returns up to 200 lines of a file with line numbers; edit_file(path, start, end, replacement) replaces a contiguous range with new content and returns a diff; run_shell(command, timeout) executes a shell command in the repository root, with a default 60-second timeout; run_tests(test_filter) invokes the project’s canonical test runner, filtered by an optional pytest-style selector; and submit_patch terminates the episode and triggers the held-out test suite. The tool schemas used by the harness follow these semantics, and stdout is truncated deterministically to keep observations bounded.

Deterministic package mirror

Network operations during patch installation are routed through a deterministic mirror that pins every package version, hash, and metadata blob at the time the task instance is admitted. Subsequent counterfactual rollouts hit the same frozen mirror, so pip install and equivalent operations return bit-identical artefacts even if upstream packages mutate during training.

HTTP replay layer

For tasks whose test suite issues outbound HTTP requests (a small minority dominated by requests, flask, and sphinx extension hooks), we capture every request-response pair during canonical solution execution and replay them deterministically during training. The replay layer matches on request method, URL, and a normalised body digest; mismatches are surfaced as task-level errors and the instance is excluded.

SWE-rebench split hygiene

The 1,200 admitted SWE-rebench training tasks are disjoint from the held-out SWE-rebench Python evaluation split. We split the candidate stream by collection month before filtering and then remove overlaps by task identifier, issue URL, pull-request URL, repository/commit window, exact patch hunk, near-duplicate patch hunk, and near-duplicate issue text. Held-out evaluation tasks are never used for rollout collection, counterfactual replay, selector tuning, or hyperparameter selection.

Case study 3: a beneficial counterfactual

These cases illustrate early localisation, a contrast between edits with different regression outcomes, and a beneficial alternative to a failing edit. They are examples rather than an estimate of how much of the total training signal each pattern explains.

Semantic understanding and the conditioning context

The policy’s representation and interpretation of a task influence the decisions available for credit assignment. Domain-adaptive pretraining for multimodal governance uses task-specific perception, question answering, and reasoning supervision. Complementary work examines prompt structure, question calibration and multi-hop temporal reasoning, fine-grained semantic conflicts, and structured contrastive semantic matching. For visual settings, complementary upstream challenges include foreground–background separation in open-vocabulary segmentation and spatiotemporal registration between RGB and event observations. These approaches address upstream understanding and representation; they provide possible complements to learning from the execution outcomes of selected actions.

Feedback and supervision-budget allocation

Evidence-conditioned critique and iterative revision support retrieval-augmented reasoning, while disclosure policies learn when reasoning should continue before emitting supported content. Selection of additional supervision can also exploit error neighbourhoods in representation space. These mechanisms suggest possible alternatives or complements to CRR’s entropy-based allocation of counterfactual rollouts. Their usefulness for a fork selector would require evaluation on the same SWE tasks and compute budget.

Broader agent environments and evaluation coverage

Agent workflows also appear in automated scientific discovery and multi-agent poster generation. Embodied action generation can use intermediate vision-language representations routed to an action decoder. In decentralised multi-agent control, local observations and communication constraints shape the information available to a policy. Extending executable contrasts to these settings would depend on reliable state restoration and an appropriate verifier. Cross-lingual reasoning training and culturally grounded multimodal evaluation additionally identify coverage dimensions beyond the current SWE experiments. Remote-sensing video question answering further tests scene-centric spatiotemporal reasoning. Evaluation also extends beyond aggregate answer scores: trace-level acknowledgment of injected biasing content and configuration-dependent model rankings on alignment benchmarks address distinct aspects of evaluation reliability.

Task objectives, planning, and deployment cost

Reward design for UAV hovering combines position holding, control effort, and disturbance response; risk-aware grid planning incorporates obstacle proximity and localisation uncertainty into search costs. These illustrate different uses of task feedback: specifying control objectives or ranking paths. CRR constructs credit for selected actions under a given terminal verifier. Separating offline model-assisted computation from deployment-time prediction is also explored in few-shot tabular learning. This provides a cross-domain perspective on reporting where additional computation occurs; CRR’s reported costs explicitly charge replay during training.

Data

All training tasks are drawn from the public SWE-Gym and SWE-rebench releases. The main training corpus contains 3,638 post-filter deterministic tasks, and the SWE-rebench training split is disjoint from the held-out SWE-rebench Python evaluation split by the rules in Section F. The flaky-test filter, the package mirror configuration, and the recorded HTTP responses will be released with the code alongside the camera-ready paper.

Limitations of reproduction

Because CRR depends on environment determinism, exact bit-level reproduction of pass-rates may differ across container engines (podman vs. docker) and across operating-system kernel versions. The controlled nondeterminism diagnostics characterise only the stated injection protocol; they do not guarantee robustness to arbitrary systematic changes in environment behaviour.

Evaluation protocols

The full-budget experiments use the final checkpoints from the main comparison. The reduced-budget protocol allocates 48 H100-hours to each arm, holds the scaffold and hyperparameters fixed except for the tested factor, and evaluates the final checkpoint greedily on all 500 SWE-bench Verified instances. Reduced-budget sensitivity experiments use one training seed unless stated otherwise. The matched Search-Select comparison instead uses three seeds per arm. Means and seed standard deviations are reported only where available; small differences in single-seed experiments are descriptive and do not establish statistical significance or equivalence.

Matched wall-clock learning curves and cumulative ledger

Generated tokens include counterfactual suffixes for CRR. Effective tokens are unique, loss-masked on-policy tokens. The training window begins at dispatch and ends at the last committed update. It includes tests, forks, waits, retries, optimization, and checkpointing; one-time loading, final evaluation, and separate ablation runs are excluded from both arms. At 40.125 hours, CRR reaches 41.7% and extended GRPO reaches 36.7%, an observed difference of 5.0 percentage points with the fork overhead fully charged. The larger number of GRPO trajectories and optimizer updates at this endpoint is part of the matched-time comparison, not a quantity held fixed.

Credit assignment versus selecting a branch

The Search-Select control isolates two uses of the same executable forks. Search-Select uses branch returns to select a training sequence, whereas CRR retains the realized trajectory and uses the return differential to assign credit to its actions. Both fork-using arms share the selector, number of fork executions per realized trajectory, branch-scoring verifier, rollout horizon, group size, device-time budget, and clipped learner.

Search-Select protocol

The behavior-policy log-probabilities of each generated sequence are retained, and current-policy log-probabilities are recomputed during optimization to form the clipped current-to-behavior ratio. This ratio accounts for policy drift; it does not remove the selection of the training distribution. The control deliberately implements an expert-iteration-style distribution in which a better branch may replace the realized sequence. The replacement rate is 12%, and PPO clipping is activated for 26% of tokens in the replacement sequences.

Multiple-sample evaluation

The CRR advantage over GRPO persists at pass@8, with a difference of 3.9 percentage points. All-8 improves by 5.2 points, indicating greater consistency across samples. These are trajectory-level evaluation metrics and do not directly measure the quality or causal effect of individual decisions.

Counterfactual quality and validity filtering

Valid but failing alternatives account for 83% of this class-mean plug-in quantity, compared with 8% for immediately invalid alternatives. The quantity summarizes class frequencies and class means. It is not the fraction of total gradient magnitude, nor the fraction of the sum of absolute per-sample contrasts, because taking the absolute value after averaging within a class can cancel contrasts of different signs.

Decision-relevance diagnostics for the selector

We evaluate selector alignment using two complementary data collections. The gold-patch-file first-touch statistic uses 2,000 logged training trajectories. The two advantage-magnitude statistics use a separate 300-trajectory probe in which counterfactuals are additionally evaluated at random, stride, and entropy-only step sets. This probe allows the selectors to be compared against the same counterfactual-advantage distribution.

Interpretation boundaries

The diagnostic evidence is consistent with useful allocation of a limited fork budget, but does not extend the fixed-index action-conditional analysis to a convergence guarantee for the selector-weighted training objective. The reduced-budget, single-seed experiments characterize measured sensitivity rather than a universal ordering of configurations. The evidence also leaves the effects of severe trajectory-length heterogeneity unresolved. These distinctions remain relevant even when the final endpoint improves under complete resource accounting.