Multi-Agent Coding Cost Governance: A Viewport-Driven Downsampling Refactor in Practice
This article examines the cost governance of multi-agent coding through a real refactoring task: reworking viewport-based downsampling in an open-source plotting library. It explains why one-time downsampling distorts curves when the view changes, why multi-agent collaboration fits this kind of cross-cutting task, and how a viewport-driven adaptive resampling design solves the problem. Drawing on a task that consumed roughly 48 million tokens, it breaks down where that spend goes, offers a concrete cost-governance checklist, and defines the boundaries within which agentic coding stays reliable. Readers will learn how to match roles to model tiers, control context growth, automate verification, and measure cost per unit of effective output.
Introduction: A Real Refactor Sparked by a “New Model” Release
On April 25, 2025—the day after a new generation of inference models shipped—a developer took an AI coding agent’s terminal tooling, paired it with a custom multi-agent orchestration setup, switched every role over to the new model, and used it to refactor a plotting library’s core algorithm. When the task finished, three numbers stood out: roughly 48 million tokens, close to 60 RMB, and every test passing with the change committed to the repository.
Put together, those numbers are interesting. Sixty RMB is about the price of a cheap takeout meal, yet it funded a complete development task involving a core algorithm refactor: code across multiple modules compiled and passed tests, and the changes were committed to version control automatically. The 48 million tokens are a reminder that this was not a matter of “generating a function from a single sentence” but the accumulation of extensive reading, exploration, trial and error, and verification. According to the author’s account, once the task was handed off he went to make dinner; after eating he came back and it still hadn’t finished, so he read some news, and only then had the task completed.
The lesson is that the new model’s coding ability is on par with the previous generation’s top-tier models, but its unit cost is higher. This conclusion is worth unpacking, for three reasons:
- First, it comes from a real, medium-to-large engineering task, not a short single-turn Q&A;
- Second, it has the verifiable outcome of “all tests passing,” not a subjective impression;
- Third, it exposes the most easily overlooked problem in agentic coding: when quality is close, cost is the real dividing line.
If the original post’s core is “reviewing a new model,” the more worthwhile questions are really three general ones:
- Is the new model worth migrating to?
- Where does the cost of a multi-agent coding task actually go?
- At the engineering level, which practices genuinely bring cost down?
Using a real task—“refactoring the viewport-change resampling in an open-source plotting widget library”—as the main thread, this article explains three things in turn: what algorithmic problem needs to be solved, why multi-agent coding is a good fit for this kind of task, and what a task of nearly 50 million tokens teaches us about cost and governance.
Root Cause: Why “One-Time Downsampling” Is Bound to Distort
Downsampling in Essence: Screen Pixels Are a Scarce Resource
A plotting library draws curves within a limited screen area. Suppose the visible window is 1200 pixels wide; with 2x scaling, that’s roughly 2400 physical pixels, while the raw data in the window can reach tens of thousands or even millions of points. Drawing point by point means far more redundant data than the screen can show, with two direct consequences:
- Render time grows linearly with data volume, and panning and zooming become visibly janky;
- When multiple data points fall on the same pixel, later-drawn points overwrite earlier ones, producing shimmer and flicker.
Downsampling reduces the number of points to be drawn while preserving visual information. Common industry approaches include:
- Even sampling (decimation): simplest to implement, but prone to missing short spikes;
- Bucket min/max: divide the data into buckets and keep only the minimum and maximum of each. It preserves the envelope shape completely and is a common choice for real-time plotting;
- LTTB (Largest-Triangle-Three-Buckets): selects points by measuring visual significance via triangle area, and performs well at preserving the look of the curve.
None of these algorithms is inherently better or worse; the question is what premise they operate under.
Where the Distortion Comes From
The old implementation used “one-time downsampling”: when the view first becomes visible, the data within the current range is downsampled once, the result is cached on the curve object, and reused directly afterward.
As long as the view doesn’t change, this strategy is correct and efficient. The real trouble appears when the view changes:
- The user zooms in on a locally flat-looking stretch of a curve. Before zooming, that region’s bucket contained many raw points, and the bucket kept only the min and max—the raw points weren’t actually lost. But as long as subsequent drawing keeps using the old cache, or the downsampling is done at the wrong spatial scale, that bucket’s output is a single point, and after zooming in it shows up as a straight line segment.
- The user zooms out to an overview, then wants to check the exact value of a spike. One-time downsampling kept no raw points and can’t rebuild at the new scale, so it can only fall back to “full rendering,” and the performance advantage disappears.
The root cause is that the downsampling scale is decoupled from the view scale: downsampling happens once at some fixed scale, while the view keeps changing. Whether zooming in or out afterward, the sampling density can’t match the new scale.
It’s worth noting that if the raw data is retained and re-downsampled at the new scale after each view change, the distortion itself is controllable. The bucket min/max method never drops extrema at any bucket width; the algorithms that really do drop extrema are certain ones that select a fixed number of points. If one mistakenly equates “downsampling” with “data compression / discarding raw points,” an easily fixable sampling problem turns into an irreversible data problem. The new design does exactly the latter: moving from “one-time downsampling” to “re-sampling as the viewport changes.”
This Is Not Just a Bug, but an Architectural Problem
The old implementation couples data, view, and rendering in the same cache:
// Old approach (illustrative): sampling is done once "when visible" and never updatedstruct Curve {const std::vector<Point>& source; // raw data (read-only)std::vector<Point> sampled; // one-time downsampling result, reused thereaftervoid onVisible(Rect viewport) {if (sampled.empty()) { // key flaw: computed only on first visibilitysampled = downsample(source, viewport); // scale is "frozen" at the first sample}}const std::vector<Point>& points() const { return sampled; }};
To truly solve the problem, three layers need to change at once:
- Data layer: make the raw data explicitly read-only, with downsampled results treated only as derived artifacts;
- View layer: treat viewport changes as first-class events, not side effects of the render flow;
- Render layer: obtain a sampling result that matches the current scale before drawing each frame.
Non-functional requirements also need headroom:
- Performance: re-sampling must stay within the frame budget;
- Correctness: there must be quantifiable, automatable verification.
The refactor must also preserve backward compatibility. Existing interfaces may be re-implemented internally, but their semantics must not change, or a large amount of caller code would be affected. So this is a “constrained refactor,” far harder than “writing a new function.”
Why Multi-Agent Collaboration Suits This Kind of Task
Tasks like this have these characteristics:
- You need to locate the relevant implementation in an unfamiliar codebase;
- They span algorithms, caching, the rendering pipeline, and tests;
- They require repeated compilation, running tests, and iterating based on failure messages;
- The workload per session is large, and someone needs to maintain overall direction.
These characteristics map neatly onto a few design principles of multi-agent orchestration.
Role Division: Perspectives a Single Agent Can’t Cover
| Role | Main responsibilities | Outputs |
|---|---|---|
| Orchestrator | Clarify requirements, break down tasks, coordinate roles, hold the acceptance bar | Task plan, final integration |
| Planner | Evaluate options, weigh trade-offs, produce a design draft | Technical design document |
| Explorer | Locate relevant code and call chains, map dependencies | Code map, impact list |
| Implementer | Make code changes, run builds and tests, iterate on fixes | Code changes, test records |
| Reviewer | Review correctness, edge cases, and performance risks | Review comments, issue list |
| Writer | Prepare change notes and design docs | Change notes, documentation |
A single agent can of course handle every stage, but it easily ends up “being both the player and the referee”: the implementer writes the code, judges it, and declares it done, so defect patterns tend to be masked by the same mental habits. An independent reviewer examines the same code from a different angle and can spot missed edge cases and hidden overheads earlier.
Heterogeneous Models: Matching Capability to Task Nature
Different tasks place different demands on model capability:
- Retrieving files, finding symbols, and reading configs is essentially “search plus lightweight comprehension,” with modest reasoning demands;
- Understanding architectural constraints, designing a sampling strategy, and reviewing code require stronger reasoning and code comprehension.
So routing retrieval work to a lightweight model and core reasoning to a high-capability model is more cost-effective. The config below is illustrative:
{"agents": {"orchestrator": { "model": "provider/reasoning-large", "effort": "high" },"planner": { "model": "provider/reasoning-large", "effort": "high" },"explorer": { "model": "provider/general-fast" },"retriever": { "model": "provider/general-fast" },"implementer": { "model": "provider/reasoning-large", "effort": "high" },"reviewer": { "model": "provider/reasoning-large", "effort": "high" },"writer": { "model": "provider/general" }}}
The effort field in the config is a generic illustrative knob for controlling reasoning depth; the exact parameter name may differ across platforms. This config has two key points:
- Most roles’ call volume concentrates in implementation and verification, so the choice of main model directly determines the order of magnitude of cost;
- The exploration and retrieval roles have large workloads and frequent calls, so a lightweight model suffices.
More broadly, whether an orchestration setup is “pro-heavy” isn’t the key; what matters is whether roles match tasks.
Context Engineering: The Dividing Line Between Cost and Quality
A multi-agent setup’s effectiveness depends less on the model itself and more on “what each role is shown.” The most common problems in long sessions include:
- Context bloat: files read early on are retransmitted repeatedly;
- Key conclusions get buried by later content, and the implementer “forgets” the initial constraints;
- Different roles redundantly repeat the same retrieval work.
Common mitigations:
- Fix the design into a file: write the planning stage’s constraints, trade-offs, and acceptance criteria into a design document in the repository, readable by any role at any time;
- Have sub-agents return summaries, not full text: the explorer returns only file paths, key interfaces, and call relationships;
- Control the context budget: set caps on the number of files read and tool calls per task;
- Use context compaction: automatically compress conversation history, using the design document as the recovery basis after compaction.
Verification Loop: Untested Agent Output Can’t Be Trusted
The biggest risk in agentic coding is that it “looks done.” A reliable verification loop includes at least:
- Build/compile: run in a fixed environment with pinned toolchain versions;
- Unit tests: covering downsampling edge cases;
- Performance tests: measuring whether re-sampling time meets the frame budget;
- Diff review: a human checks the final changes, focusing on core algorithms and interface compatibility;
- Commit: commit only after verification passes, keeping a rollback checkpoint.
Refactor Design: Viewport-Driven Adaptive Resampling
Below is a design framework that can directly guide implementation. It follows two principles:
- Raw data is never discarded;
- The sampling scale changes dynamically with the view scale.
Data Structures
struct Downsampler {// Read-only raw data; using a prefix min/max index is recommended to speed up range queriesvoid setData(std::shared_ptr<const DataSource> src);// Input: current viewport; Output: sampling result matching the viewport scaleSampledCurve sample(Viewport vp) const;private:std::shared_ptr<const DataSource> src_;};struct Viewport {double xMin, xMax; // horizontal axis range in data spacedouble yMin, yMax; // vertical axis range in data space (optional; used to cull invisible segments)int pixelWidth; // physical pixel width of the viewportint maxPoints; // maximum number of points allowed per frame};
The raw data is held by a separate data source and is read-only, and the downsampler only “generates a sampling result per viewport.” This means zoom and pan simply re-invoke sample() with the new viewport parameters—there’s no possibility of “an old cache being wrongly reused.”
Sampling Algorithm: At Most Two Points per Pixel
SampledCurve Downsampler::sample(Viewport vp) const {SampledCurve out;const double span = vp.xMax - vp.xMin;// 1. Pixel-aligned bucketing: bucket width ≈ the data range per physical pixelconst int bucketCount = std::min(vp.maxPoints / 2, vp.pixelWidth);const double bucketWidth = span / bucketCount;// 2. Traverse only buckets that intersect the viewport; buckets outside the view don't participate at allfor (int i = 0; i < bucketCount; ++i) {double x0 = vp.xMin + i * bucketWidth;double x1 = x0 + bucketWidth;// 3. In-bucket extrema: ensures spikes aren't lost after local zoom-inauto [ymin, ymax] = src_->rangeMinMax(x0, x1);out.push_back({x0, ymin});out.push_back({x0, ymax});}// 4. Clip by the current viewport's output order: ensures endpoints aren't missing and no out-of-range points appearreturn out.clipTo(vp);}
Four design points:
- Bucket width follows the view: zoom changes
span, and bucket width changes accordingly. Zooming in means fewer data points per bucket, so min and max converge, and the sampling result naturally collapses to the raw curve—no more “straight line after zooming in.” - Extremum preservation: each bucket keeps its min and max, so local spikes are never averaged away at any scale.
- Budget constraint: the bucket count ceiling is controlled by
maxPoints, which together with frame-rate throttling on the render side keeps re-sampling from slowing down interaction. - Workload tied to the view: sampling only processes buckets within the viewport, independent of the total data volume. Data outside the view doesn’t enter the computation—this is the key to staying interactive with long series.
Viewport Change Handling and Caching
- Event-driven: trigger re-sampling when the window size, zoom factor, or pan offset changes, rather than computing unconditionally every frame.
- Cache key: cache the last few sampling results keyed by (data version number, viewport range, target bucket count). When data updates, the version number increments and old cache entries automatically invalidate.
- Change throttling: during continuous zoom or drag, use frame-rate throttling to limit re-sampling frequency, avoiding a full computation every frame.
- Pluggable strategy: keep the algorithm replaceable. If the business values curve appearance more, preservation-oriented algorithms like LTTB can be layered on top with the interface unchanged.
Verification System
| Verification type | What it checks | Pass criterion |
|---|---|---|
| Correctness | The sampling result contains the extrema within the original range | Matches brute-force scan results |
| Precision | Fidelity after zooming to single-pixel scale | Matches the original curve, or error within an acceptable range |
| Performance | Per-frame re-sampling time | Below the frame budget (e.g., part of the ~16 ms budget at 60 Hz) |
| Regression | Comparison with the old version’s output | No unexpected differences; any differences are explainable |
The first and third items are the most worth investing in:
- The former can be automatically verified with the assertion “the downsampled result must contain the minimum and maximum of the raw data within the same x-range,” with no need to eyeball the plot;
- The latter can directly measure re-sampling time and point counts before and after sampling—objective, comparable data.
Writing acceptance criteria as assertions is the precondition for letting agents converge on their own.
Cost Breakdown: Where Did 48 Million Tokens Actually Go
The Big Picture and Unit Cost
The original task’s numbers:
- About 48 million tokens cumulatively;
- Close to 60 RMB;
- All related code compiled and passed tests, with the change committed to version control.
From these, a couple of intuitive reference metrics can be derived:
- Blended unit price: based on total tokens, about 1.25 RMB per million tokens;
- Cost per unit of effective output: if the changed code is roughly on the order of thousands of lines, about tens of RMB per thousand lines of effective change.
These metrics aren’t industry benchmarks, because task size, model tier, prompt structure, and context strategy all significantly affect results. Their real value is providing a “comparable” way to measure:
- After switching models or configs on the same task, you can compare cost per unit of output;
- Across different tasks, you can use total tokens to gauge actual workload.
Note that unit price and task value aren’t the same thing. Nearly 60 RMB bought not “an implementation of one downsampling function” but an architectural refactor spanning the data, view, and render layers, plus complete tests and a version commit. If converted to human labor cost, this output is typically far higher than the API call cost. The cost advantage of agents shows precisely on tasks that are “constrained, cross-module, and verification-dependent.”
Cost Composition
Breaking the 48 million tokens down by purpose, they roughly fall into six categories:
- System prompt and tool definitions: carried on every call—a fixed overhead;
- Conversation history replay: with each additional turn, all prior messages are transmitted again, so cumulative input grows faster than the number of turns;
- Tool-result feedback: the return values of reading files, searching, and executing commands all enter the context—the larger the codebase and the more read per call, the higher this share;
- Reasoning consumption: high-reasoning-tier models do lengthy internal reasoning before answering, and that reasoning content also counts as tokens;
- Retries and trial and error: fix rounds after build failures or failing tests;
- Cross-role duplicate reads: multiple agents each read the same files.
Items 2, 3, and 6 are often underestimated, and they’re exactly what engineering methods can optimize most.
Cost Governance Checklist
| Strategy | Practice | Effect |
|---|---|---|
| Task splitting | Break big tasks into independently verifiable small steps | Fewer retry rounds and context replays |
| Targeted retrieval | Limit search scope by file, symbol, or directory | Keep irrelevant code out of the context |
| Structured input | Use design docs, interface contracts, and acceptance assertions instead of natural-language descriptions | Reduce ambiguity and back-and-forth confirmations |
| Tiered models | Lightweight models for retrieval, high-capability models for reasoning | Lower average unit price when quality is comparable |
| Context compaction | Auto-compress long sessions, persist key info to disk | Control context-length growth |
| Prompt caching | Keep system prompts and project context prefixes stable | Lower input cost for repeated prefixes |
| Hard budgets | Set token and call-count caps per task | Prevent runaway trial and error |
| Automated verification | Fully automate build, unit tests, and performance tests | Let agents converge on the correct solution themselves |
| Human spot-checks | Review only core algorithms and interfaces manually | Concentrate human time on high-value judgment |
Conclusions and Boundaries
The core of this governance approach can be summed up in one line: let expensive models make judgments, let cheap models do retrieval, let machines verify, and let people make trade-offs.
At the same time, be clear about the boundaries:
- Subjective experiences like visual feel and interaction responsiveness: agents can only offer candidate solutions, and a human must confirm the final choice;
- Cost data holds only for a specific task and specific config and can’t be extrapolated to other projects;
- The reliability of agentic coding depends on how complete the verification loop is; when test coverage is insufficient, its output can’t be taken as correct at face value.
For teams about to try multi-agent coding, a three-step rollout is recommended:
- First, make build, test, and code standards into an automated pipeline;
- Then split roles by task nature and assign model tiers;
- Finally, continuously measure with three metrics—total tokens, cost per unit of effective output, and first-pass rate—and tune step by step.
Seen through this framework, the original judgment—“capability on par with the previous generation’s top tier, but priced higher”—becomes clearer: model capability decides whether it can be done; engineering method decides whether it’s worth doing.
