Manuscript Offprint
arXiv:2611.06863Rethinking Self-Repair in Code-as-Policy Agents: What Drives Retry Success?
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Siddharth Aphale
Stanford University
Ayushman Singh
Sesame AI
Abstract: Code-as-policy agents often use execution feedback to retry failed programs. Additional sampling and task guidance can also improve success, leaving the contribution of failure-specific feedback unclear. We study this question in simulated robot manipulation. A fixed lookup selects feedback templates using failure labels and the API variant. A frozen code model generates a fresh program after each scene reset. On the same 252 initial failures, Qwen2.5-Coder-7B recovers 85.3% within five retries, compared with 68.3% for resampling with the same retry cap. The advantage persists under fixed total-token budgets. Feedback from other episodes and fixed task guidance yield similar recovery point estimates, with no detected benefit from matching the coarse failure label. In a separate study, a fixed guided prompt used from the first attempt achieves an observed overall success rate similar to that of template-based feedback. Template-based feedback also lowers recovery on a nut-insertion task requiring a rim grasp, consistent with an incompatible center-grasp instruction. Evaluations of robot self-repair should include resampling, mismatched feedback, and concise, task-compatible static guidance as baselines.
Keywords: Code-as-policy agents, Self-repair, Execution feedback, Test-time evaluation
1 Introduction
Code-as-policy agents translate language instructions into executable robot programs [1]. Their failures often follow clear patterns: a program may skip the grasp, release an object after lifting, or place it away from the target. A common response is iterative self-reflection. The model reads its failed program and execution trace, writes a critique, and tries again [2, 3, 4]. Retry success can reflect additional sampling, concise task instructions, feedback about the current failure, or editing the previous program. We ask whether feedback after failure improves recovery over guidance available from the first attempt.
We study this question with frozen Qwen2.5-Coder-3B/7B models in a reset-and-retry setting. Each retry starts from the original scene. Our main conditions generate a fresh program with the failed program omitted from the prompt. We use template-based feedback to study which information improves retry success. A fixed lookup selects instructions using the failure label and API variant, such as “MUST grasp the object before lifting.” We call this condition Compiled. The lookup lets us replace matched feedback with another episode’s feedback, hold the guidance fixed, or remove it while keeping the retry loop unchanged (Figure 1). Separate editing conditions expose the previous program and request a revision. All conditions restart the original scene. We do not test recovery from the physical state left by failure.
Compiled recovers 85.3% of the 252 initial failures within five retries, compared with 68.3% for resampling with the same retry cap. The gain persists under fixed total-token budgets. Feedback from other episodes and one fixed template per task produce similar point estimates. We detect no benefit
Workshop on Robot Learning at Deployment (Learn@Deploy), CoRL 2026.

Figure 1: Template-based feedback improves recovery over resampling. (a) Reset-and-retry loop and feedback methods. (b) Recovery on 252 initial failures, with similar outcomes for Compiled, Different-Label Feedback, and Fixed Task Template.
from matching the coarse failure label to the current episode. The confidence intervals still allow differences between conditions. In a separate study, a fixed guided prompt used from the first attempt achieves an observed overall success rate similar to Compiled's, with fewer tokens per solved episode. That comparison changes initial guidance and the generation instruction together. Their individual contributions remain unresolved.
We compare feedback content and program-generation strategies under matched retry budgets to test how additional sampling, reusable task guidance, and failure-label matching affect recovery. Evaluations of robot self-repair should include static guidance as a baseline for adaptive feedback.
Evaluation of iterative self-repair. Reflexion and Self-Refine use model-written critiques to improve later outputs [2, 3]. Self-Debugging conditions code generation on the previous program and its execution results [4]. On code benchmarks, Olausson et al. [11] found that self-repair often does not outperform independent sampling at matched compute. Self-correction of reasoning is also unreliable without external feedback, whereas critique grounded in external evidence can help [12, 13]. We extend matched-sampling comparisons to embodied code execution and test whether guidance must match the current failure or follow a failure at all.
Execution feedback and interactive evaluation. CodeRL, RLEF, and MURPHY use compiler or test feedback to update model parameters [14, 15, 16]. RLEF also tests random execution feedback from unrelated programming problems at inference time. This comparison tests the value of feedback specific to the current problem, although its training, tasks, and feedback construction differ from ours. Inference-time agents such as ReAct, Voyager, and LATS use feedback during search or interaction [17, 18, 19]. InterCode, AppWorld, and AgentBoard evaluate execution outcomes and intermediate progress [20, 21, 22]. With model weights fixed, we ask which information in a robot's retry prompt accounts for recovery.
3 Methods
3.1 Experimental Setup
We evaluate frozen code models in robosuite simulation with a Panda arm [23, 24]. Models receive state information and generate Python programs using a documented robot API, without images. The primary evaluation uses Qwen2.5-Coder-7B-Instruct [25] with the primitive API on cube lifting and stacking.
An episode comprises an initial program execution for a task and scene, followed by any retries under one method. The initial execution is attempt 0. After an initial failure, the model is allowed up to five retries. Before each retry, the simulator resets to the original scene. Each retry produces a complete program, either generated from scratch or revised from the previous program.
We use 252 initial failures for evaluation and 40 for development. The sets contain distinct initial programs, identified by their hashes. The evaluation covers 159 combinations of task, API variant, and scene, including 24 also used in development. All methods are evaluated on the same stored initial failures. The end-to-end studies pair methods by scene seed.
Conditional recovery@k is the fraction of attempt-0 failures solved within k retries. This metric measures sequential retries and differs from pass@k estimated from independent samples. For end-to-end studies, initial success is success on attempt 0 and overall success@6 is success in any of the six allowed executions. An attempt is valid if its program compiles, uses only documented API functions, and finishes before timeout.
The generalization study includes Qwen2.5-Coder-3B/7B and two additional pick-and-place tasks. We combine results across seven settings that meet the predefined eligibility criteria. Separate studies examine API variants with fewer high-level helper functions, Qwen2.5-Coder-32B, and DeepSeek-Coder-6.7B [26]. Further details of the software, tasks, evaluation sets, and metrics are provided in Appendix A.
3.2 Template-Based Feedback
After an unsuccessful execution, a rule-based labeler assigns one primary label from a 14-label taxonomy. Compiled maps this label and the API variant to a fixed feedback template containing a diagnosis and short MUST/NEVER instructions (Table 1). This lookup requires no additional model call. The instructions guide code generation without imposing execution-time checks.
Compiled accumulates feedback from the initial failure and subsequent failed retries, retaining the labels and attempt indices. The feedback block presents the newest feedback first, omits duplicate instruction lines, and respects the feedback-length limit. The generation prompt contains the task, API documentation, and accumulated feedback, with the previous program omitted. An example from the earlier study shows an initial failure followed by a successful fresh retry (Figure 2a). The prompts are provided in Appendix B, and the reset-and-retry algorithm is given in Algorithm 1.
3.3 Comparison Methods
We compare methods within each study using the same generator, task, API, decoding settings, and retry limit. Resample repeats the base retry prompt without feedback. Other-Episode Feedback replaces the current episode's feedback with feedback from other failures, matched by task, API
Table 1: Failure labels select fixed retry guidance. Example instruction excerpts for the primitive API. Full templates are provided in Appendix D.
| Detected failure | Guidance added to the retry prompt |
|---|---|
| Grasp did not secure the object | MUST: grasp at the object's CENTRE: ..., with the gripper empty |
| Object grasped but not lifted | MUST: ... call lift(name, height=0.1) after the grasp |
| Unsupported function call | MUST: use ONLY the documented API functions ...NEVER: import statements |
variant, and initial task-progress bin. The primary matching control, Different-Label Feedback, selects individual feedback records from other episodes of the same task, preferring the same initial task-progress bin and requiring a different failure label whenever available. Both add feedback as the evaluated episode accumulates failures and use the same feedback-length limit. These controls test the value of matching the coarse failure label while retaining useful task information. The matching and fallback rules are specified in Appendix B.3.
We select a fixed template for each task from the development data, choosing the most frequent failure label with task-compatible guidance. Fixed Task Template reuses this template across retries after the initial failure. Static-from-Start uses the complete Fixed Task Template retry prompt from attempt 0, changing both the initial generation instruction and the presence of guidance.
Direct+Compiled shows the failed program and requests an edit, jointly changing code exposure and the generation instruction. Reflection uses an extra model call to critique the failed program and execution log. Its generation call receives the accumulated critiques and omits the previous code. Reflection was tested only in the earlier core evaluation with the original generation instruction.
The primary evaluation uses a condition-neutral generation instruction for regeneration methods. The original instruction referred to a repair plan even when feedback was absent. Both prompt versions are provided in Appendix B.4.
Eligibility criteria, multiplicity corrections, decoding settings, and token accounting are specified in Appendix A.
4 Results
4.1 Recovery under Matched Budgets
In the primary evaluation, Compiled recovers 85.3% of the 252 held-out failures within five retries. Resample, with the same retry cap, recovers 68.3%, a difference of +17.1 pp (95% CI [+9.9, +24.2]).¹ Compiled recovers more failures than Resample from the first retry (Figure 1b) and uses fewer total model tokens, including prompts and completions.
Under fixed token budgets, Compiled improves recovery over Resample by +15.9 pp at 2,000 tokens and +14.7 pp at 5,000 (Figure 2b). Fixed Task Template and Different-Label Feedback yield similar observed recovery rates to Compiled, while Direct+Compiled has lower recovery. Compiled also achieves higher overall success than Resample in the earlier 700-scene end-to-end study with the original generation instruction (Appendix C).
4.2 Feedback Matching and Content
Different-Label Feedback and Fixed Task Template each recover 86.1% in the primary evaluation, compared with 85.3% for Compiled. We detect no advantage from matching the coarse label to the current failure, although the paired confidence intervals do not establish equivalence (Table 2;
¹pp denotes percentage points. Bands and error bars show 95% CIs: Wilson for recovery proportions and paired bootstrap for differences.
(a)

(b)
(c)


| Compiled | Different-Label Feedback | Direct+Compiled |
|---|---|---|
| Resample | Fixed Task Template |
Figure 2: Guidance improves recovery under fixed token budgets. (a) An initial failure followed by a successful retry after reset. (b) Recovery under total-token budgets. (c) Paired recovery@5 comparisons show an advantage over resampling, with no detected advantage over different-label or fixed-template guidance.
Figure 2c). In earlier studies, we also detected no advantage for Compiled over Other-Episode Feedback, Permuted Labels, or Initial-Label Only (Appendix C).
In the primary evaluation, the exploratory Repeated API Rules control copies rules already in the prompt and does not reproduce Compiled's improvement. Earlier comparisons using the original generation instruction likewise show lower recovery with content-free feedback and All-Template Union than with concise feedback templates (Appendix C).
Table 2: Primary paired contrasts on 252 initial failures. Each entry is Compiled minus the comparator in recovery@5, with a 95% paired-bootstrap CI.
| Comparator | Question | (pp; 95% CI) |
|---|---|---|
| Resample | benefit beyond another sample? | +17.1 [+9.9, +24.2] |
| Different-Label Feedback | must the label match? | -0.8 [-6.3, +4.8] |
| Fixed Task Template | dynamic versus fixed guidance? | -0.8 [-6.7, +5.2] |
| Direct+Compiled | does editing improve recovery? | +63.9 [+56.7, +70.6] |
4.3 Guidance from the First Attempt
On 700 new scenes, Static-from-Start increases initial success from 19.3% with the standard prompt to 36.9%. It uses the complete Fixed Task Template retry prompt from the first attempt, changing both task guidance and the generation instruction. Their individual contributions remain unresolved.
By the sixth execution, Static-from-Start reaches 92.4% overall success, compared with 89.6% for Compiled and 90.1% for Fixed Task Template (Figure 3). Its advantage over Compiled is not statistically significant after multiplicity correction (+2.9 pp; Holm-adjusted p=0.13). It also uses the fewest total model tokens per solved episode. Complete results and prompt differences are reported in Appendix C.2.
(a)

(b)

Figure 3: A fixed guided prompt improves initial success. (a) Initial and overall success on 700 fresh scenes. (b) Total model tokens per solved episode. Static-from-Start changes both the initial instruction and guidance.
The matching controls and Static-from-Start results suggest that reusable task guidance accounts for the gain. These results do not establish that the model uses the current execution trace.
4.4 Editing and Reflection
Direct+Compiled achieves 21.4% recovery in the primary evaluation. Earlier analyses show smaller program changes with editing than with fresh generation. Because Direct+Compiled changes code exposure and the generation instruction together, the cause of its lower recovery remains unresolved.
In the earlier core evaluation, Reflection achieves 56.0% recovery, below Resample, while using more completion tokens and wall-clock time. These findings concern the tested editing and reflection implementations. Further editing and critique results are summarized in Appendix C.1.
4.5 Generalization and Failure Cases
Across seven Qwen2.5-Coder-3B/7B settings covering four tasks and 354 initial failures, Compiled improves recovery@5 over Resample by +18.1 pp (CI ). Its difference from Other-Episode Feedback is smaller, at +2.3 pp (CI ), with no detected advantage over this same-task feedback control (Figure 4; Appendix C.3).
The recovery advantage persists in most additional evaluations of API variants, pose noise, and generation seeds. At temperature 0.2 on lifting with pose shift, however, Compiled's recovery is 19.6 pp lower than Resample's.
With Qwen2.5-Coder-32B, Compiled and Resample solve the same 52 of 55 initial stack failures (94.5% recovery@5). This high recovery rate leaves limited room for further improvement.
On nut insertion, the required rim grasp conflicts with the center-grasp instruction in the pick-and-place template for failed_grasp. Recovery@5 is 82.5% with Compiled and 97.5% with Resample, a difference of -15.0 pp (CI ). The decrease is consistent with the incompatible grasp instruction, while attempt validity remains similar. Guidance that helps within one task family can therefore be harmful in another.
| Generalization study | n |
|---|---|
| 7B lift + pose shift | 56 |
| 7B lift + distractor | 48 |
| 7B stack + paraphrase | 49 |
| 7B stack + distractor | 60 |
| 3B lift | 52 |
| 3B cube-to-zone | 44 |
| 3B place-in-bin | 45 |
| Combined (7 settings) | 354 |
| Additional task / API settings | |
| 7B stack + pose shift | 60 |
| 3B stack | 60 |
| 7B cube-to-zone, position API | 60 |
| 7B place-in-bin, position API | 60 |
| Pose-noise studies | |
| 7B lift + 5 mm pose noise | 60 |
| 7B stack + 5 mm pose noise | 60 |
| Model and task boundaries / scale | |
| DeepSeek-6.7B lift | 60 |
| DeepSeek-6.7B stack | 60 |
| 7B nut insertion | 40 |
| 32B stack + distractor | 55 |
| Earlier end-to-end replication | |
| 7B fresh scenes (initial failures) | 553 |

Figure 4: Guidance benefits vary across tasks and models. Compiled–Resample recovery differences across evaluated settings. The diamond summarizes the seven eligible generalization settings.
5 Discussion
Our results suggest that reusable task guidance explains the recovery advantage of template-based feedback over resampling in the tested tasks. Fixed guidance and feedback from other failures yield similar recovery point estimates to Compiled, with no detected benefit from matching the coarse failure label. Static-from-Start also achieves similar observed overall success to Compiled while using fewer tokens per solved episode. Evaluations should test fixed guidance from the first attempt alongside feedback selected after failure. The Static-from-Start comparison changes both guidance and the generation instruction, so their individual contributions remain unresolved.
Evaluations of self-repair should therefore distinguish the contributions of additional sampling, reusable guidance, and failure-specific information. Resampling provides a baseline for additional sampling, with retry and token budgets matched across methods. Static guidance tests whether instructions are useful before a failure occurs, while mismatched feedback tests the value of matching the coarse failure label to the current episode. These comparisons should check for instructions that conflict with a task's requirements, such as center-grasp guidance on a task requiring a rim grasp.
6 Conclusion
Evaluations of robot self-repair should include resampling, mismatched feedback, static guidance from the first attempt, and previous-program editing, with retry and token budgets matched across methods.
Our findings are limited to simulated manipulation with privileged state and coarse feedback. Some comparisons combine instruction and information changes. Future work should isolate these effects and examine larger models on harder tasks or under tighter budgets. Extending evaluation to visual feedback and physical recovery, including post-failure states and action costs, would clarify when adaptive feedback improves on static guidance.
References
[1] J. Liang, W. Huang, F. Xia, P. Xu, K. Hausman, B. Ichter, P. Florence, and A. Zeng. Code as policies: Language model programs for embodied control. In IEEE International Conference on Robotics and Automation (ICRA), 2023. URL https://arxiv.org/abs/2209.07753.
[2] N. Shinn, F. Cassano, A. Gopinath, K. Narasimhan, and S. Yao. Reflexion: Language agents with verbal reinforcement learning. In Advances in Neural Information Processing Systems (NeurIPS), volume 36, 2023. doi:10.52202/075280-0377.
[3] A. Madaan, N. Tandon, P. Gupta, S. Hallinan, L. Gao, S. Wiegreffe, U. Alon, N. Dziri, S. Prabhumoye, Y. Yang, S. Gupta, B. P. Majumder, K. Hermann, S. Welleck, A. Yazdanbakhsh, and P. Clark. Self-Refine: Iterative refinement with self-feedback. In Advances in Neural Information Processing Systems (NeurIPS), volume 36, 2023. doi:10.52202/075280-2019.
[4] X. Chen, M. Lin, N. Schärli, and D. Zhou. Teaching large language models to self-debug. In International Conference on Learning Representations (ICLR), 2024. URL https://openreview.net/forum?id=KuPixIqPiq.
[5] I. Singh, V. Blukis, A. Mousavian, A. Goyal, D. Xu, J. Tremblay, D. Fox, J. Thomason, and A. Garg. ProgPrompt: Generating situated robot task plans using large language models. In IEEE International Conference on Robotics and Automation (ICRA), 2023. URL https://arxiv.org/abs/2209.11302.
[6] M. Ahn, A. Brohan, N. Brown, Y. Chebotar, O. Cortes, B. David, C. Finn, C. Fu, K. Gopalakrishnan, K. Hausman, A. Herzog, D. Ho, J. Hsu, J. Ibarz, B. Ichter, A. Irpan, E. Jang, R. Jauregui Ruano, K. Jeffrey, S. Jesmonth, N. J. Joshi, R. Julian, D. Kalashnikov, Y. Kuang, K.-H. Lee, S. Levine, Y. Lu, L. Luu, C. Parada, P. Pastor, J. Quiambao, K. Rao, J. Rettinghouse, D. Reyes, P. Sermanet, N. Sievers, C. Tan, A. Toshev, V. Vanhoucke, F. Xia, T. Xiao, P. Xu, S. Xu, M. Yan, and A. Zeng. Do as i can, not as i say: Grounding language in robotic affordances. In Conference on Robot Learning (CoRL), volume 205 of Proceedings of Machine Learning Research, pages 287–318. PMLR, 2023. URL https://proceedings.mlr.press/v205/ichter23a.html.
[7] L. Fu, J. Yu, K. El-Refai, E. Kou, H. Xue, H. Huang, W. Xiao, G. Wang, D. Niu, F.-F. Li, G. Shi, J. Wu, S. Sastry, Y. Zhu, K. Goldberg, and L. Fan. CaP-X: A framework for benchmarking and improving coding agents for robot manipulation. arXiv preprint arXiv:2603.22435, 2026. URL https://arxiv.org/abs/2603.22435.
[8] Z. Liu, A. Bahety, and S. Song. REFLECT: Summarizing robot experiences for failure explanation and correction. In Conference on Robot Learning (CoRL), volume 229 of Proceedings of Machine Learning Research, pages 3468–3484. PMLR, 2023. URL https://proceedings.mlr.press/v229/liu23g.html.
[9] Y. Guo, Y.-J. Wang, L. Zha, and J. Chen. DoReMi: Grounding language model by detecting and recovering from plan-execution misalignment. In IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), 2024. URL https://arxiv.org/abs/2307.00329.
[10] X. Li, Y.-L. Li, Y. Wang, H. Wang, and S. Wang. TCoT: Trajectory chain-of-thoughts for robotic manipulation with failure recovery in vision-language-action model. Proceedings of the AAAI Conference on Artificial Intelligence, 40(8):6486–6494, 2026. doi:10.1609/aaai.v40i8.37577.
[11] T. X. Olausson, J. P. Inala, C. Wang, J. Gao, and A. Solar-Lezama. Is self-repair a silver bullet for code generation? In International Conference on Learning Representations (ICLR), 2024. URL https://openreview.net/forum?id=y0GJXRungR.
[12] J. Huang, X. Chen, S. Mishra, H. S. Zheng, A. W. Yu, X. Song, and D. Zhou. Large language models cannot self-correct reasoning yet. In International Conference on Learning Representations (ICLR), 2024. URL https://openreview.net/forum?id=IkmD3fKBPQ.
[13] Z. Gou, Z. Shao, Y. Gong, Y. Shen, Y. Yang, N. Duan, and W. Chen. CRITIC: Large language models can self-correct with tool-interactive critiquing. In International Conference on Learning Representations (ICLR), 2024. URL https://arxiv.org/abs/2305.11738.
[14] H. Le, Y. Wang, A. D. Gotmare, S. Savarese, and S. C. H. Hoi. CodeRL: Mastering code generation through pretrained models and deep reinforcement learning. In Advances in Neural Information Processing Systems (NeurIPS), volume 35, 2022. doi:10.52202/068431-1549.
[15] J. Gehring, K. Zheng, J. Copet, V. Mella, T. Cohen, and G. Synnaeve. RLEF: Grounding code LLMs in execution feedback with reinforcement learning. In International Conference on Machine Learning (ICML), volume 267 of Proceedings of Machine Learning Research, pages 19034–19055. PMLR, 2025. URL https://proceedings.mlr.press/v267/gehring25a.html.
[16] C. Ekbote, V. Lingam, S. Sanghavi, J. Huan, B. Omidvar-Tehrani, A. Deoras, and S. Soatto. MURPHY: Feedback-aware GRPO with retrospective credit assignment for multi-turn code generation. arXiv preprint arXiv:2511.07833, 2025. URL https://arxiv.org/abs/2511.07833.
[17] S. Yao, J. Zhao, D. Yu, N. Du, I. Shafran, K. Narasimhan, and Y. Cao. ReAct: Synergizing reasoning and acting in language models. In International Conference on Learning Representations (ICLR), 2023. URL https://openreview.net/forum?id=WE_vluYUL-X.
[18] G. Wang, Y. Xie, Y. Jiang, A. Mandlekar, C. Xiao, Y. Zhu, L. Fan, and A. Anandkumar. Voyager: An open-ended embodied agent with large language models. Transactions on Machine Learning Research, 2024. URL https://openreview.net/forum?id=ehfRiFOR3a.
[19] A. Zhou, K. Yan, M. Shlapentokh-Rothman, H. Wang, and Y.-X. Wang. Language agent tree search unifies reasoning, acting, and planning in language models. In International Conference on Machine Learning (ICML), volume 235 of Proceedings of Machine Learning Research, pages 62138–62160. PMLR, 2024. URL https://proceedings.mlr.press/v235/zhou24r.html.
[20] J. Yang, A. Prabhakar, K. Narasimhan, and S. Yao. InterCode: Standardizing and benchmarking interactive coding with execution feedback. In Advances in Neural Information Processing Systems (NeurIPS), volume 36, pages 23826–23854. Curran Associates, Inc., 2023. doi:10.52202/075280-1035.
[21] H. Trivedi, T. Khot, M. Hartmann, R. Manku, V. Dong, E. Li, S. Gupta, A. Sabharwal, and N. Balasubramanian. AppWorld: A controllable world of apps and people for benchmarking interactive coding agents. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 16022–16076. Association for Computational Linguistics, 2024. doi:10.18653/v1/2024.acl-long.850.
[22] C. Ma, J. Zhang, Z. Zhu, C. Yang, Y. Yang, Y. Jin, Z. Lan, L. Kong, and J. He. AgentBoard: An analytical evaluation board of multi-turn LLM agents. In Advances in Neural Information Processing Systems (NeurIPS), volume 37, pages 74325–74362. Curran Associates, Inc., 2024. doi:10.52202/079017-2365.
[23] Y. Zhu, J. Wong, A. Mandlekar, R. Martín-Martín, A. Joshi, K. Lin, A. Maddukuri, S. Nasiriany, and Y. Zhu. robosuite: A modular simulation framework and benchmark for robot learning. arXiv preprint arXiv:2009.12293, 2020. URL https://arxiv.org/abs/2009.12293.
[24] E. Todorov, T. Erez, and Y. Tassa. MuJoCo: A physics engine for model-based control. In IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), 2012. doi: 10.1109/IROS.2012.6386109.
[25] B. Hui, J. Yang, Z. Cui, J. Yang, D. Liu, L. Zhang, T. Liu, J. Zhang, B. Yu, K. Lu, K. Dang, Y. Fan, Y. Zhang, A. Yang, R. Men, F. Huang, B. Zheng, Y. Miao, S. Quan, Y. Feng, X. Ren, X. Ren, J. Zhou, and J. Lin. Qwen2.5-Coder technical report. arXiv preprint arXiv:2409.12186, 2024. URL https://arxiv.org/abs/2409.12186.
[26] D. Guo, Q. Zhu, D. Yang, Z. Xie, K. Dong, W. Zhang, G. Chen, X. Bi, Y. Wu, Y. K. Li, F. Luo, Y. Xiong, and W. Liang. DeepSeek-Coder: When the large language model meets programming – the rise of code intelligence. arXiv preprint arXiv:2401.14196, 2024. URL https://arxiv.org/abs/2401.14196.
A Experimental Details
A.1 Tasks, APIs, and evaluation sets
We evaluate text-only code generation with privileged state in robosuite 1.5.2 and MuJoCo 3.3.5 using a simulated Panda arm. Python programs run through a documented position-control API in isolated subprocesses with a 60 s timeout. The primitive API includes lift and place_on; the position-only API omits them. The tasks are cube lifting, stacking, cube-to-zone, and place-in-bin, with additional evaluations on nut insertion and door opening.
The evaluation sets, retry instructions, and outcome measures are summarized in Table A1. The primary dataset contains 360 Qwen2.5-Coder-7B programs (18.9% initial success). Its 292 failures unrelated to infrastructure errors are divided into 40 development and 252 evaluation failures by initial-program hash.
Within each study, eligibility requires initial success in the predefined range [10%, 70%]. The combined generalization estimate weights the 354 initial failures from seven eligible settings equally. Settings outside this range and separately designed studies are reported separately.
Table A1: Evaluation sets and endpoints. Comparisons pair conditions within each study. Original and neutral instructions are reproduced in Appendix B.4.
| Study | Model and evaluation set | Retry instruction | Main endpoint |
|---|---|---|---|
| Primary | Qwen2.5-Coder-7B; 252 held-out failures, lifting and stacking | Neutral | Recovery within five retries |
| Generalization | Qwen2.5-Coder-3B/7B; 354 failures across seven eligible settings, four tasks | Original | Recovery within five retries |
| Earlier end-to-end | Qwen2.5-Coder-7B; 700 fresh scenes, lifting and stacking | Original | Overall success within six executions |
| Static-from-Start | Qwen2.5-Coder-7B; 700 separate fresh scenes, lifting and stacking | Neutral | Overall success within six executions |
A.2 Decoding, metrics, and statistical analysis
After an initial failure, each condition receives at most five retries from the original scene. Within a study, conditions share the model, task, API, decoding settings, and retry cap. Unless stated otherwise, generation uses temperature 0.7, top- 0.95, a 1,024-token completion limit, and a 768-whitespace-token feedback cap. Reflection calls allow 256 completion tokens.
Conditional recovery@k is the fraction of initial failures solved within sequential retries. Task success is checked by an independent final-state geometric predicate. Valid programs compile, call only documented functions, and finish before timeout. An execution counts as a safety violation if it leaves an object off the table.
Confidence intervals for paired differences use 10,000 bootstrap replicates. Exact McNemar tests assess significance at the final retry, with Holm correction within each predefined comparison group. Intervals are 95% unless an earlier secondary result is marked 90%. The primary analysis treats each stored initial failure as one observation. An exploratory bootstrap over the 159 task-API-scene clusters accounts for dependence within scene configurations and retains the +17.1 pp Compiled-Resample difference (95% CI [+10.1, +24.2]).
Fixed-token analyses replay logged calls in order. Each call's prompt and maximum completion allowance must fit within the remaining budget. Token use includes prompts, completions, and reflection calls. The budgets are 2,000, 5,000, and 9,500 tokens. No call fits within the original 1,000-token budget. In end-to-end studies, tokens per solved episode is total token use across all scenes, including attempt 0 and unsolved scenes, divided by the number of solved episodes.
A.3 Reproducibility notes
Development and evaluation contain distinct initial programs but share 24 of the 159 evaluation scene configurations. The earliest core comparisons pair stored initial failures, though a placement-sampler seeding limitation allowed retry layouts to differ. Later studies seed every reset, and the subsequent evaluation with the original generation instruction uses rebuilt software. Each comparison uses a single software build. Seeding does not guarantee bitwise deterministic simulation.
The generalization question was revised after the core results, with settings and analysis fixed before generation for that study. The Static-from-Start study was also specified before generation. Fixed Task Template was selected on development data, so its first held-out comparison is exploratory. Later studies reused this fixed text. Direct+Compiled was selected in a separate 116-failure pilot.
Failure labels were audited on scripted faults, without human audits of natural failures. Oracle-hint performance and template-authoring cost were not measured.
B Feedback and Prompt Construction
B.1 Failure labels and template selection
The labeler checks execution errors, safety events, absence of API calls, and task subgoals in a fixed priority order to assign one of 14 failure labels. The lookup COMPILE(label, variant) returns a diagnosis and MUST/NEVER instructions. Three templates vary across APIs, yielding 17 label-specific texts. All templates, API substitutions, and the generic fallback are reproduced in Appendix D.
Compiled adds one feedback record after each failure. Records are ordered newest first, with duplicate instruction lines removed and the shared feedback-length limit applied. Attempt indices remain in the headers, so repeated labels can appear under different attempt headers.
B.2 Reset-and-retry algorithm
Regeneration with Compiled, mismatched feedback, and fixed guidance is described in Algorithm 1, with selection rules in Appendix B.3. Each failure record includes its label and the information used to match source episodes.
Algorithm 1 Reset-and-retry regeneration with condition-specific feedback
Require: original scene , initial failure record , API variant , condition , retry cap , feedback cap 1: ▷ evaluated episode's failures 2: for to do 3: ▷ empty for Resample 4: ▷ newest first; deduplicate instructions 5: 6: ▷ previous program hidden 7: 8: if success then 9: return SUCCESS 10: end if 11: 12: end for 13: return FAIL
B.3 Control definitions
Regeneration prompts omit the previous program (Table A2). Direct+Compiled and Reflection Repair include it and request a revision, changing both code exposure and the generation instruction.
Table A2: Prompt inputs for each feedback and editing condition. Source-episode selection and prompt construction are specified below.
| Condition | Feedback supplied to program generation |
|---|---|
| Resample / Compiled | No feedback / accumulated templates for the observed labels. |
| Other-Episode Feedback | Accumulated feedback from a matched source episode. |
| Different-Label Feedback | Feedback from another failure, prioritizing a different label. |
| Permuted Labels | A fixed permutation replaces every observed label with a different label. |
| Cross-Task Feedback | A fixed assignment of source episodes from a different task. |
| Fixed Task Template | One fixed development-selected template per task, reused after failure. |
| Static-from-Start | The complete Fixed Task Template retry prompt from attempt 0 onward. |
| Initial-Label Only | The initial failure's template, unchanged across retries. |
| All-Template Union | Goal-compatible templates ordered by development frequency. |
| Static Prior | One fixed task-independent text per model, without accumulation. |
| Placebo / Repeated API Rules | Length-matched generic instructions / existing API execution rules. |
| Direct+Compiled | Previous program and accumulated feedback templates. |
| Reflection | Accumulated model-written critiques; previous program hidden. |
| Reflection Repair | Previous program, latest critique, and truncated execution log. |
Other-Episode Feedback selects feedback from another episode matched by task, API variant, and initial task-progress bin. Progress is the fraction of ordered subgoals completed before the first unmet subgoal, grouped into four equal-width bins over [0, 1]. Source histories are limited to the evaluated episode's failure count.
Different-Label Feedback selects one source record per observed label from the same task, preferring a different label in the same progress bin. If none is available, the progress-bin match is relaxed before allowing the same label; the task match is always retained. In the primary evaluation, all 627 selected records had a different failure label from the corresponding observed failure. Both controls use Compiled's feedback ordering, deduplication, and length limit.
Fixed Task Template uses the most frequent failure label with task-compatible guidance for each task, selected from the fixed 40-failure development set. Static-from-Start also reuses the retry instruction and historical failure header (Appendix C.2).
Following Reflexion [2], Reflection uses a separate critic call that receives the previous program and truncated log. Generation receives only the accumulated critique.
B.4 Prompt construction
A generation prompt concatenates four blocks:

The API and task blocks below are the primitive-tier stacking example; only the feedback block varies across regeneration conditions.
API documentation and execution rules (identical in every condition and attempt at a given tier)
# API
Code-as-policy API (privileged state, position control; all positions are (x, y, z)
tuples in metres in the world frame):
get_object_pose(name, return_bboxExtent=False) -> (x, y, z)
# object centre position; with return_bboxExtent=True returns
# ((x, y, z), (ex, ey, ez)) where e* are half-extents of the object
get_gripper_pose() -> (x, y, z) # current gripper fingertip position
goto_pose(position, quat=None, z_approach=0.10)
# move the gripper to 'position', approaching from z_approach metres above;
# orientation is fixed top-down (quat is accepted but ignored)
open_gripper()
close_gripper()
check_grasped(name) -> bool
execute_waypoints(waypoints)
lift(name, height=0.1)
# open the fingers (release)
# close the fingers (grasp whatever is between them)
# True if 'name' is currently held
# goto_pose each position in the list, in order
# raise the HELD object by height metres
place_on(source, target) # move the HELD source above target and release it
Execution rules:
- These functions are ALREADY DEFINED in the execution environment. Do not import anything and do not define or redefine any of these functions yourself.
- Top-level code runs directly; if you wrap steps in a helper function you must call it.
- To grasp an object: goto_pose to its centre position, then close_gripper().
- Success is checked on the FINAL state of the scene: a lifted object must still be held at the end (do not call open_gripper() after lifting unless the task says to release); to place an object, move it above the target and open_gripper().
- place_on(source, target) positions the held object on the target and releases it automatically; do not call open_gripper() after place_on.
Task and objects
# Task
Stack the red cube on top of the green cube.
# Objects
red_cube, green_cube
For the primitive API tier, releasing a lifted object produces the following exact block:
Condition-specific feedback example
# Repair plan
attempt 0 failed: released_after_lift - The object was lifted but then released, so it was no longer → held at the end.
MUST: do NOT open the gripper after lifting; keep holding (or place on the target first): use → place_on(source, target) as the final action (it releases)
NEVER: open_gripper immediately after lifting
The primary evaluation used the following instruction for regeneration conditions:
Condition-neutral generation instruction
# Write a COMPLETE fresh Python program using ONLY the API above, following the same execution rules (→ no imports, no redefining API functions, call any helper you define). Follow every instruction → present in this prompt. Output only code.
The position-only tier removes lift and place_on from the API block. Earlier runs used a suffix that referred to a “repair plan,” must_change items, and a verification checklist even when those fields were absent. We therefore repeated the core comparisons with the neutral instruction above; the main paper reports that evaluation. The original generation instruction was:
Historical generation instruction
# Using the repair plan above (compiled from a previous failed attempt), write a COMPLETE fresh Python → program using ONLY the API above, following the same execution rules (no imports, no redefining API → functions, call any helper you define). Satisfy every must_change item and the verification → checklist. Output only code.
In the primary evaluation, Direct+Compiled uses the following editing instruction:
Neutral editing instruction
# Revise the previous program above into a COMPLETE corrected Python program using ONLY the API above, → following the same execution rules (no imports, no redefining API functions, call any helper you → define). Follow every instruction present in this prompt. Output only code.
The previous program is included only in the editing prompt. Reflection uses a separate call with the instruction “In at most 6 sentences, reflect on why the program failed the task and what to do differently next time. Output only the reflection.” Serialized prompts and model revisions are recorded in the experiment artifacts.
C Additional Analyses
C.1 Feedback content and failure matching
(a)

(b)

Figure A1: (a) Recovery with feedback and editing conditions in earlier evaluations. (b) A task-independent prompt improves recovery on stacking but reduces it on lifting.
We detect no advantage from matching the coarse failure label in the primary evaluation. The paired recovery difference between Compiled and Different-Label Feedback is -0.8 pp (95% CI [-6.3, +4.8]). Earlier comparisons using the original generation instruction also show little benefit from updating the initial label or preserving the label mapping (Table A3). These intervals do not establish equivalence.
In these earlier comparisons, recovery is lower with content-free instructions and All-Template Union than with concise, task-compatible feedback (Figure A1). The exploratory Repeated API Rules control also yields lower recovery than Resample in the primary evaluation (61.1% versus 68.3%).
Table A3: Additional controls test feedback content and label matching. Comparisons using the original generation instruction on 252 held-out failures. p-values are Holm-adjusted within predefined groups of secondary comparisons.
| Contrast | Δ (pp) | 95% CI | p |
|---|---|---|---|
| Reflection Repair – Resample | -45.2 | [-53.2, -36.9] | |
| All-Template Union – Resample | -36.1 | [-44.0, -27.8] | |
| Compiled – Initial-Label Only | +0.4 | [-4.0, +4.8] | 1.0 |
| Compiled – Permuted Labels | +1.6 | [-3.6, +6.7] | 1.0 |
| Placebo – Resample | -29.8 | [-37.7, -21.8] |
Reflection achieves 56.0% recovery in the earlier core evaluation, compared with 70.6% for Resample, and uses more completion tokens and wall-clock time. In the subsequent evaluation using the original generation instruction, recovery is 25.0% for Reflection Repair and 21.4% for Direct+Compiled, compared with 89.7% for Compiled. Editing produces smaller program changes than fresh generation. Because the editing comparisons change code exposure and instruction together, the cause of the lower recovery remains unresolved.
C.2 Static guidance from the first attempt
The Static-from-Start study compares overall success across 700 shared fresh scenes, using six executions per condition, neutral retry instructions, and fixed template text (Table A4). Resample, Compiled, and Fixed Task Template share attempt 0 and its 565 failures, whereas Static-from-Start has 442 initial failures. Conditional recovery is therefore reported descriptively.
The standard initial prompt ends with “Write a Python program using ONLY the API above.” Static-from-Start instead uses the complete retry prompt, including the longer neutral instruction in Appendix B.4 and the historical “attempt 0 failed” header. It changes initial guidance and the generation instruction together. Their individual contributions remain unresolved.
Table A4: Static-from-Start increases initial success and reduces tokens per solved episode. Results on 700 fresh scenes with neutral retry instructions. Success and recovery are percentages; recovery uses different initial-failure subsets.
| Condition | Initial | Overall@6 | Recovery@5 | Tok/solved |
|---|---|---|---|---|
| Static-from-Start | 36.9 | 92.4 | 88.0 | 2,087 |
| Fixed Task Template | 19.3 | 90.1 | 87.8 | 2,564 |
| Compiled | 19.3 | 89.6 | 87.1 | 2,578 |
| Resample | 19.3 | 73.1 | 66.7 | 3,623 |
Static-from-Start achieves +2.9 pp higher overall success than Compiled (95% CI [+0.0, +5.7], Holm-adjusted p=0.13). Its advantage over Fixed Task Template is +2.3 pp ([-0.4, +5.0], unadjusted p=0.13). An exploratory replay under fixed token budgets gives an advantage over Compiled of +17.6 pp at 2,000 tokens ([+13.0, +22.1]) and +4.6 pp at 5,000 ([+1.1, +8.0]).
The earlier end-to-end study uses 700 separate scenes and the original generation instruction. Attempt 0 succeeds on 147 scenes, leaving 553 shared failures. Compiled reaches 92.9% overall success, compared with 73.1% for Resample and 95.6% for Fixed Task Template. The template comparison is exploratory.
C.3 Generalization and failure cases
Across the seven eligible Qwen2.5-Coder-3B/7B settings, Compiled improves recovery over Resample by +18.1 pp (95% CI [+13.3, +22.9]). Its difference from Other-Episode Feedback is smaller, at +2.3 pp ([-1.1, +5.6]). The additional studies below are excluded from this combined estimate.
Recovery gains vary across API and perturbation settings. With the position-only API, Compiled improves recovery over Resample by +30.0 pp on cube-to-zone. Both methods reach 93.3% recovery on place-in-bin. Across three generation seeds, Compiled exceeds Resample in all six tested seed-setting pairs (+10.7 to +26.7 pp). With 5 mm pose noise, the difference is +16.7 pp on lift and +10.0 pp on stack, with only the lift interval excluding zero. At temperature 0.2 on lift with pose shift, Compiled's recovery is 19.6 pp lower than Resample's (90% CI [-28.6, -10.7]).
The model-specific results cover different levels of initial success (Figure A2). DeepSeek-Coder-6.7B falls below the minimum initial-success rate required for inclusion on both tasks. Its combined recovery is 50.8% for Compiled and 41.7% for Resample (; difference +9.2 pp, [-1.7, +20.0]). The separate door-opening study has 1.3% initial success and also falls below the minimum required for inclusion.
With Qwen2.5-Coder-32B, all 80 lift scenes succeed initially. On stack, 105 of 160 initial attempts succeed, and Compiled and Resample solve the same 52 of the remaining 55 failures (94.5%). The paired interval has zero width because the methods produce identical outcomes on these 55 failures. Equivalence on other evaluation sets remains untested.

Figure A2: Recovery differences between Compiled and Resample across model-specific studies. Each point compares Compiled with Resample within a separately evaluated model and task set.
On nut insertion, Compiled recovers 82.5% of initial failures, compared with 97.5% for Resample (; -15.0 pp, 95% CI [-27.5, -2.5]). The decrease is consistent with the center-grasp instruction conflicting with the required rim grasp. Other-Episode Feedback reaches 62.5% recovery. Attempt validity remains similar for Compiled and Resample (85.1% and 84.9%).
D Language Feedback Templates
The following schema-3.0 texts are extracted directly from src/roborepair/plan/constraints.py. All 14 label-specific templates, the generic fallback, and both API-variant substitution blocks are included.
| syntax_error | Diagnosis: The previous program did not compile.MUST: write a complete syntactically valid programNEVER: truncated statementsNEVER: markdown or prose inside the code |
|---|---|
| timeout | Diagnosis: The previous program exceeded the execution time budget.MUST: remove unbounded loops and retry/polling logic; write a short direct sequence of API callsNEVER: while-loops that wait or retryNEVER: sleep or polling |
| invalid_api | Diagnosis: The previous program called functions that do not exist.MUST: use ONLY the documented API functions, already defined (no imports, no redefinitions)NEVER: import statementsNEVER: calling functions not in the API docNEVER: redefining API functions |
| no_api_calls | Diagnosis: The previous program executed but made no API calls.MUST: make the API calls execute at top level; call any helper function you defineNEVER: defining functions without calling them |
| target_not_localized | Diagnosis: The previous program never located the target object.MUST: look up each object with get_object_pose(name) and move using the returned positionNEVER: referencing objects not in the sceneNEVER: guessing positions |
| missing_grasp | Diagnosis: The previous program never attempted a grasp.MUST: grasp the object before lifting/placing: goto_pose to the object's centre position, then → close_gripper()NEVER: lifting or placing before a successful grasp |
| failed_grasp | Diagnosis: The grasp was attempted but did not secure the object.MUST: grasp at the object's CENTRE: goto_pose to the object's centre position, then close_gripper(), ↔ with the gripper emptyNEVER: closing the gripper away from the object's centre |
| grasp_without_goto | Diagnosis: The gripper closed while positioned away from the object.MUST: move the gripper to the object's centre BEFORE closing: goto_pose to the object's centre position →, then close_gripper()NEVER: close_gripper without first moving to the object |
| grasp_while_holding | Diagnosis: A grasp failed because the gripper was still holding another object.MUST: grasp only ONE object; move the held object to its destination instead of grasping anotherNEVER: closing the gripper while already holding an object |
object_not_lifted
Diagnosis: The object was grasped but never lifted. MUST: after the grasp, LIFT the object: {lift_hint} NEVER: ending the program with the object still on the table
released_after_lift
Diagnosis: The object was lifted but then released, so it was no longer held at the end. MUST: do NOT open the gripper after lifting; keep holding (or place on the target first): {place_hint} NEVER: open_gripper immediately after lifting
bad_placement
Diagnosis: The object was lifted but not placed correctly on the target. MUST: place the object ON the target: {place_hint} NEVER: releasing the object away from the target
unsafe_path
Diagnosis: An object was knocked off the table. MUST: approach objects from above with z_approach; avoid sweeping motions near objects NEVER: motions that knock objects off the table
door_not_opened
Diagnosis: The handle was grasped but the door was never pulled open. MUST: after gripping the handle, PULL it sideways away from the door frame: pull('door_handle', dx, dy) ↔ with a horizontal vector of at least 0.15 m NEVER: releasing the handle without pulling it NEVER: lifting the handle instead of dragging it sideways
unknown_failure (fallback)
Diagnosis: The task did not succeed. MUST: fix the cause of failure and complete every task step
API tier M substitutions
lift_hint: call lift(name, height=0.1) after the grasp place_hint: use place_on(source, target) as the final action (it releases)
API tier P substitutions
lift_hint: after closing the gripper, goto_pose to a position 0.15 m ABOVE the grasp point with ↔ z_approach=0 (the object moves with the gripper) place_hint: while holding, goto_pose above the target position, then open_gripper()