LLM Code Iteration in Practice: Diagnosing Failures and Choosing the Right Tool
This article presents an illustrative workflow for recording multi-round LLM-assisted code iterations, from initial prompt design and acceptance criteria to failure classification, model comparison, cost per successful task, multi-agent tradeoffs, and tool selection checks. All cases, tables, and numbers are templates rather than real model-performance claims; readers should rerun the process with their own models, projects, and logs and base conclusions on measured records.
The cases, tables, and numbers in this article are illustrative templates only. They do not represent the performance of any real model. You need to rerun the tests with your own model, project, and logs, and base your conclusions on actual records.
1. Illustrative Case: Iteration Log for a Financial Report Monitoring Page
This case shows how to record multiple rounds of correction for a long task. It is not a directly reproducible experiment because it lacks key information such as model version, dependency versions, and sample logs. Follow the steps below to produce your own reproducible record.
Experiment Environment
- Frontend: Vue 3 and Vite
- Backend: Node.js 20 and Express
- Data: local SQLite database with 200 simulated financial report records
- Model: record the full model name and version number
- Dependency versions: record the exact versions of each dependency in
package.jsonand the lockfile - Data structure: record the SQLite table schema and the request parameters and response fields of the
/api/reportsendpoint - Sandbox permissions: allow read and write only in the project directory; allow only
npm install,npm run build, andnpm run dev; allow network access only to local ports and the specified package source; prohibit deletion commands
Input Prompt
Please build a financial report monitoring page using Vue 3 and Express. The page should include: a table filtered by company ticker and reporting period, with sortable columns; a line chart showing year-over-year revenue changes; and filter button interactions that take effect in real time. The backend should provide an /api/reports endpoint, with data from local SQLite. Generate the complete project and make sure npm run build passes.
The prompt should remain complete. The more specific the requirements are, the easier it is to determine the cause when something fails. If you only write “build a financial report page,” it will be hard to attribute later errors.
Iteration Process
The table below shows the recording format. Error signatures, exit codes, elapsed time, and token usage should be filled in with actual measured values.
| Round | Symptom | Error Signature | Exit Code | Elapsed Time | Token Usage | Correction Action |
|---|---|---|---|---|---|---|
| Round 1 | Build failure | Chart component incompatible with Vue version | Fill in measured value | Fill in measured value | Fill in measured value | Change dependency version and rebuild |
| Round 2 | Fourth table column truncated | Screenshot comparison shows column width overflow | Fill in measured value | Fill in measured value | Fill in measured value | Adjust table-layout and minimum column width |
| Round 3 | Filter button does not respond | Event binding is undefined |
Fill in measured value | Fill in measured value | Fill in measured value | Fix event name and the component’s emit declaration |
| Round 4 | Startup failure | Port 5173 is already in use | Fill in measured value | Fill in measured value | Fill in measured value | Switch to 5174 and document it in the README |
For every round, save three types of material: a summary of the input context, the complete logs returned by tools, and the code diff after correction. Without these records, you cannot determine what a correction actually fixed.
Acceptance Criteria
npm run buildreturns exit code 0- The page loads in the browser without console errors
- Every requirement in the prompt has a corresponding screenshot or test record
- The total elapsed time from task start to a runnable page and the total number of iteration rounds are recorded
2. Four Causes of Long-Task Failure
When a long task fails, many people only see that “the output was not good.” In practice, failures usually fall into four categories. Each has different diagnostic criteria and fixes; treating them together wastes many rounds.
1. Context Window Overflow
The number of input tokens exceeds the model’s context window limit. A typical sign is that early requirements are forgotten later, and generated code conflicts with earlier agreements—for example, the same API field has different names in different parts of the context.
How to diagnose: check the token usage returned by the API, or search tool logs for truncation messages.
How to fix:
- Split requirements into file-level tasks.
- Maintain a project notes file such as
PROJECT_NOTES.mdto record API contracts, field names, ports, and completed items. - Put only the relevant files into the context each round.
- Set a context budget. A reasonable starting point is to keep the project notes plus the files for the current task within half of the window, leaving the rest for model output and tool logs. Teams should adjust this after testing their own tasks.
2. Tool-Call Timeout
A build, dependency installation, or test command exceeds the timeout configured for the tool. Logs usually contain timeout, or the process is forcibly terminated.
How to diagnose: check the exit code and elapsed time in the logs. A nonzero exit code with an elapsed time close to the timeout threshold usually indicates a timeout.
How to fix: split long commands into several steps; enable caching for npm install; or raise the timeout threshold based on actual elapsed time. Set the threshold to about twice the historical successful run time, not an unlimited value.
3. Retry Exhaustion
The model repeatedly modifies the same error and exceeds the preset maximum number of retries, after which the task is terminated. A typical signal is the same error message appearing three or more times in a row while each change fails to reduce the error.
How to diagnose: count occurrences of the same error signature.
How to fix: set the maximum retry count to 3. After that, save the complete error context and hand it to a human instead of letting the model keep trying.
4. Sandbox Crash
Memory or process count exceeds the sandbox limit, and the process is killed by the system.
How to diagnose: in a container environment, use docker inspect to check the OOMKilled field in the container status; on a host machine, check kernel logs for OOM records.
How to fix: increase the sandbox memory limit or reduce the number of concurrently running processes.
Truncated tool output or a dropped connection can also look like a “lost task.” In such cases, first check whether the logs are complete, then determine whether the problem is in the model or the infrastructure.
3. Side-by-Side Comparison: Evaluate by Dimension, Not by Brand
Directly comparing “which model is stronger” usually does not produce useful conclusions. A more reliable approach is to use the same prompt, the same sandbox, and the same acceptance criteria, and record each of the following dimensions.
| Dimension | Check Method | Recording Basis |
|---|---|---|
| Instruction following | Check style and interaction requirements in the prompt one by one | Omitted items ÷ total requirements |
| Code style | Run lint tools | Warnings per 100 lines of code |
| Resource consumption | Record input and output tokens for each task | Total tokens per task |
| Failure modes | Count occurrences of the four failure types in Section 2 | Failures ÷ total rounds |
| Cost | Calculate using vendor unit prices | See the formula in Section 4 |
| Elapsed time | Record time from task start to a runnable page | Minutes |
Testing method:
- Run the same task at least 5 times for each model. With too few samples, the median is unstable, so save the raw result of every run.
- Before testing, disable the model’s memory feature or clear the conversation history so that each run is independent.
- Define what counts as “success” first. A suggested definition is: passes all acceptance criteria and requires no manual code fixes during the process.
- Save the logs of every run for later review.
Conclusions from this method are valid only for your task type and your environment. If you change the tech stack or the type of requirement, the conclusion may change.
4. Cost and Stability: Calculate per Successful Task
A model with a low unit price is not necessarily cheap. Failures and retries also incur costs, so a more reasonable metric is the average cost per successful task:
Average cost per successful task = total spend ÷ number of successful tasks
Total spend here includes all model fees for failed tasks and retried tasks. If the team also performs manual review, the review time converted into money should also be included in total spend.
The following uses two hypothetical numbers to demonstrate the calculation. The numbers themselves do not represent any real model:
- Model A: cost per task CNY 0.5, success rate 60%. Average cost per successful task = 0.5 ÷ 0.6, about CNY 0.83.
- Model B: cost per task CNY 1.0, success rate 95%. Average cost per successful task = 1.0 ÷ 0.95, about CNY 1.05.
Under these assumptions, Model A has the lower cost per successful task. Model B has a higher success rate, but its unit price is twice that of A, and the success-rate advantage is not enough to offset the price gap. Even if Model B reached a 100% success rate, its average cost would still be CNY 1.0, higher than Model A’s CNY 0.83.
For Model B to win with these numbers, its per-task cost would need to be below 0.83 × 0.95, or about CNY 0.79. This threshold can serve as a reference when comparing prices.
Similarly, average elapsed time should be calculated as “total elapsed time ÷ number of successful tasks.” Do not look only at the time of a single run, because waiting caused by retries also counts.
Quota and Concurrency Checks
- Whether the monthly quota covers projected usage with at least a 20% margin
- The concurrency limit during peak periods, such as concentrated CI runs, and the 90th percentile of queue time
- Whether the system degrades gracefully or simply interrupts tasks when rate limiting is triggered
Stability Tests
- Run the same prompt 10 times and count the proportion that passes acceptance
- Input abnormal content and observe whether the model gives a clear warning instead of generating incorrect code. Examples include:
- Empty requirement: only “build a page”
- Extremely long requirement: paste a requirement document of several thousand words and observe whether later requirements are omitted
- Special characters: company names containing quotation marks, angle brackets, or SQL metacharacters
- Before connecting the model to an automated pipeline, run the full regression test in an isolated environment
5. Multi-Agent Collaboration: When Is Splitting Worth It?
The multi-agent approach assigns tasks to different roles, such as a data acquisition agent, cleaning agent, analysis agent, and aggregation agent. The agents communicate through a message queue or shared context.
Splitting brings benefits in concurrency and division of labor, but it also introduces three types of cost:
- Communication overhead: context must be passed at every handoff, and more handoffs consume more tokens
- State inconsistency: two agents may have different understandings of the same data
- Debugging difficulty: one error may require tracing logs across multiple agents
By default, do not split. Splitting is worth trying only when the following conditions are all met. These thresholds are starting values; teams should adjust them based on their own test results:
- At least two subtasks can run independently without sharing mutable state.
- A single agent takes longer than the team’s acceptable limit to complete the whole task, for example 30 minutes.
- Each subtask has a clear input and output format, such as a fixed JSON structure.
- The content of a single handoff can be kept to about 2,000 tokens or less.
- When one subtask fails, only that subtask can be rolled back without affecting the results of other subtasks.
To estimate communication overhead, multiply the number of handoffs by the average number of tokens per handoff. If this number approaches or exceeds the token usage of a single agent completing the task, splitting is usually not cost-effective.
Environment Awareness and Sandbox Boundaries
When letting agents automatically run application test cases, you must limit them to a controlled environment:
- Run in an isolated container or virtual machine, separated from the developer’s host machine and production systems
- Mount only a copy of test data; do not connect to the production database
- Use temporary tokens to access external services; do not put long-term credentials in the sandbox
- Set allowlists for operations such as dependency installation, port occupation, and file deletion
- Critical operations such as releases, data deletion, and permission changes must require human confirmation
When dependency conflicts occur, the agent should first resolve them in an isolated environment, record all changes to the lockfile, and then have a developer review them before merging into the main branch. During review, check newly added or upgraded dependencies, the size of version changes, license types, and whether the number of changed lines in the lockfile matches the requirement.
When a port is occupied, the agent may switch ports on its own, but it must write the change to PORTS.md, recording the service name, old port, new port, reason, and date. This prevents other services that still depend on the old port from failing silently.
6. Tool Selection Checklist
When choosing an intelligent coding tool, you can check the following items one by one. The thresholds are suggested starting points; teams should adjust them to their own situation.
- Quota: projected monthly usage does not exceed 80% of the quota
- Concurrency: record the 90th percentile of peak-period queue time and set a limit acceptable to the team
- Failure recovery: whether a task can resume from the most recently completed round after interruption. Verify by intentionally interrupting a task once
- Observability: whether logs, token usage, and tool-call records for each round can be retained; at least 30 days is suggested
- Cost control: whether per-task limits and monthly budget circuit breakers are supported. It is suggested to alert at 80% of budget and stop new tasks at 100%
- Retry limit: whether it can be configured; a recommended value is 3
- Permissions: whether least-privilege configuration and sandbox isolation are supported, and whether command allowlists can be set
- Compliance: whether code and data will be used for model training. Check the terms of service and record the review date and terms version
Conclusion
With a controlled environment, explicit permissions, and complete logs, LLMs can handle repetitive development work such as scaffolding, error repair, and style adjustments. They cannot replace requirement review and code review. Teams should test with their own tasks and judge whether a tool is worth adopting by its cost per successful task and its stability.
