Evaluating LLM Coding Agents for Complex Refactoring: Capability and Cost
This article uses a viewport-driven downsampling refactor in a plotting component library as a case study to assess coding agents along two dimensions: closed-loop task capability and total cost. It covers task definition, multi-agent orchestration, observed strengths and limitations, token cost composition, and practical controls such as layered model routing, context compression, task-level budgets, human checkpoints, and observability. The goal is to help teams move from “the agent can complete the task” to “the agent can complete it reliably, controllably, and economically.”
1. Background: Why Single-Generation Quality Is Not Enough
When evaluating coding agents, a common approach is to ask them to answer algorithm questions, generate a function, or fix an error message. Such evaluations are valuable, but they struggle to reflect the complexity of real engineering tasks. Real projects often involve cross-file modifications, understanding legacy code, a compile-and-test loop, visual or numerical validation, and version control commits. A single task may last tens of minutes or even hours, invoke many tools, and produce tens of millions of tokens of context exchange.
This article uses one downsampling algorithm refactor in a plotting component library as an example to discuss how to evaluate coding agents from two dimensions: closed-loop task capability and total cost. The library needs to resample data as the viewport changes, avoiding the distortion that occurred when a previous one-time downsampling approach was used during local zooming. The task itself is not large, but it involves algorithm design, adaptation to existing interfaces, caching strategy, test validation, and version commits. It is therefore a suitable observation sample for complex refactoring tasks.
2. Task Definition: Resampling Triggered by Viewport Changes
The original logic tended to perform one-time downsampling during data loading. This works reasonably well for a global view, but when a user zooms into a local region, the already downsampled data cannot recover detail, which can cause curve distortion or misjudgment. A reasonable approach is to change downsampling from one-time preprocessing to on-demand, viewport-based resampling, with caching and invalidation policies.
A reusable pseudocode structure is as follows:
on viewport_changed(new_range, pixel_width):key = make_key(new_range, pixel_width, downsample_policy)if cache.has(key):return cache.get(key)density = estimate_samples_per_pixel(new_range, pixel_width)if density > threshold:points = resample_visible(new_range, pixel_width)else:points = fetch_raw_points(new_range)cache.put(key, points)return points
The key points of this approach include: the cache key must cover the viewport range, pixel width, and downsampling policy; resampling must control the number of data points corresponding to each pixel; high-density regions should use chunking or level-of-detail strategies; and the cache should have a capacity limit and invalidation rules to prevent memory growth during interaction. Testing should verify not only whether compilation passes, but also numerical error and response latency under zooming, panning, window size changes, and extreme data density.
3. Multi-Agent Orchestration: Breaking Complex Tasks into Observable Roles
A complex refactor is not well suited to a single agent completing it linearly from start to finish. A more controllable approach is multi-role orchestration: a planner clarifies requirements and splits steps, a retriever locates relevant code and compresses context, a coder generates patches, a reviewer compiles, tests, and checks for regressions, and a reporter organizes change notes. Different roles can be routed to high-capability or lightweight models based on task difficulty.
roles:planner:duty: "Requirement clarification and solution design"model_tier: "high-capability"retriever:duty: "Code retrieval and context compression"model_tier: "lightweight"coder:duty: "Patch generation and local refactoring"model_tier: "high-capability"reviewer:duty: "Compilation, testing, and regression review"model_tier: "high-capability"reporter:duty: "Change notes and commit messages"model_tier: "lightweight"policy:clarify_before_run: truemax_rounds: 12checkpoint_every: 3require_tests: true
The advantage of this orchestration is clear responsibility and locatable failures; the cost is duplicated context and a longer call chain. Planning, execution, and review repeatedly pass code snippets, test logs, and error messages among roles, so token consumption rises quickly. Without context compression and budget control, a long task can easily move from “acceptable cost” to “tens of millions of tokens.”
4. Execution Process and Capability Observations
In one complex refactoring practice, the agent entered a long unattended run after completing necessary clarification. The task consumed tens of millions of tokens in total, with an estimated cost on the order of tens of RMB, and the time covered the full process of requirement understanding, code retrieval, patch generation, compilation and testing, and version control commit. The final code passed test validation and was committed.
From a capability perspective, several observations can be made:
Code understanding and cross-file modification are basically usable. The agent was able to locate the downsampling-related logic, understand the relationship between viewport changes and sampling density, and complete interface adaptation across multiple files. For tasks with clear test feedback, it could iterate and correct based on compilation errors and test results.
Context maintenance over long chains still fluctuates. Multi-agent collaboration introduces duplicated context, and the agent needs to maintain goal consistency across planning, execution, and review. If clarification is insufficient, subsequent plan drift or over-modification is more likely.
The test closed loop is key to amplifying capability. With compilation, testing, and version commits as hard feedback, the agent’s self-correction has a stronger basis; without executable validation, natural-language review alone can easily miss edge cases.
Compared with existing general model combinations, the coding capability observed here was broadly comparable, but the per-task cost was higher. This shows that “can complete” and “can complete economically” are two different metrics. Evaluation should not only check whether a final patch exists, but also examine token efficiency, the number of human interventions, and the failure retry ratio.
5. Cost Composition: Where Tens of Millions of Tokens Go
Token consumption in complex refactoring tasks usually comes from five parts: codebase retrieval and context injection, solution planning and clarification, patch generation, compile and test log return, and failure retries and review. Multi-agent orchestration amplifies these costs because the same code and error messages may be passed among different roles multiple times.
A simplified formula can be used to estimate task cost:
cost = input_tokens * input_price+ output_tokens * output_price+ cached_tokens * cached_price+ retry_overhead
Cache hits, context compression, and layered model routing are key to reducing cost. High-capability models are suitable for planning, complex patch generation, and final review; lightweight models are suitable for code retrieval, log summarization, change notes, and low-risk checks. If all roles use high-capability models, quality may be stable, but cost will rise significantly.
6. Optimization Recommendations: Making Capability and Cost Measurable and Controllable
First, establish task-level budgets. Set a token limit, cost limit, and maximum iteration count for each task. When a budget threshold is reached, pause and output the intermediate state, and let a human decide whether to continue, reduce scope, or terminate. A budget is not a limit on capability; it prevents long-chain tasks from running out of control.
Second, prioritize context compression. The retriever should not indiscriminately inject entire files. Instead, it should return symbol-level locations, relevant function snippets, and call relationship summaries. Test logs should also be summarized before being returned, avoiding large log blocks repeatedly occupying context.
Third, adopt layered model routing. Divide roles into high-capability, general, and lightweight tiers. Use the high-capability tier for planning, complex algorithm changes, and final review; use the lightweight tier for retrieval, log summarization, and commit messages. Through configurable role policies, spend cost on the stages that truly require reasoning.
Fourth, set human checkpoints. Set checkpoints after requirement clarification, after solution confirmation, before large-scale changes, and before the final commit. Human confirmation can reduce rework, especially for tasks with high algorithm correctness requirements and difficult visual validation.
Fifth, improve observability. Record the role, model tier, input and output tokens, latency, retry reason, and test results of each call. If the agent orchestration service is deployed on a cloud platform such as Baidu AI Cloud, logging, monitoring and alerting, and container services can be combined to provide unified observability for task-level token consumption, failure retries, and resource usage. The more complete the observability, the better teams can distinguish “insufficient model capability” from “inefficient orchestration strategy.”
7. Conclusion: Evaluate Coding Agents by Closed-Loop Quality + Total Cost
When evaluating the coding capability of newly released large models, it is not enough to look only at whether a single patch is elegant, nor is it enough to compare unit prices alone. A more reasonable framework is to observe requirement understanding, cross-file modification, test closure, version commits, and long-context stability in real engineering tasks, while also tracking token consumption, cost, latency, and human interventions. This plotting library downsampling refactor practice shows that multi-agent coding agents can already complete relatively complex feature changes and pass tests, but the cost of tens-of-millions-token tasks cannot be ignored. Compared with existing general model combinations, capability may be comparable, while cost may be higher. Teams should use layered routing, context compression, budget checkpoints, and observability to move from “can complete” to “complete reliably, controllably, and economically.”
