Controlling Token Costs on Long-Horizon AI Coding Tasks: Strong-Model Planning, Low-Cost Execution, and Test-Driven Iteration

    Long-horizon coding tasks—where an AI agent builds an entire application instead of answering a single prompt—can drain a month's subscription quota in just a couple of runs. This article explains why the cost balloons, separates planning capability from execution capability, and lays out a cost-control strategy: have a strong model produce a structured spec document, delegate implementation to lower-cost models, and drive iteration with tests. It also covers evaluation design using a spreadsheet app as a benchmark, context management, failure recovery and rollback, procedural visual generation, and a practical checklist for keeping token spend under control.

    1. The Problem: Long-Horizon Coding Tasks Devour Your Quota

    Discussion around “large models autonomously completing complex software projects” keeps heating up. Developers have had models generate a 3D first-person shooter prototype from scratch, with publicly shared API costs reaching hundreds of dollars; others tried to build a desktop operating system prototype end-to-end, with development cycles measured in days.

    Amid this wave of enthusiasm, a more practical problem is emerging: just two long-horizon tasks can exhaust a month’s subscription quota.

    This is not surprising. The cost of long-horizon agentic tasks comes mainly from three compounding sources:

    • Repeatedly loaded context: task descriptions, requirements documents, existing code, and conversation history get carried into the context round after round;
    • Reasoning resource consumption: some models output a fairly complete internal reasoning process before giving the final answer;
    • Retries after failures: compile failures, failing tests, and runtime errors all trigger a new round of fixes, and each round is a full re-entry of the context.

    At the same time, some coding subscriptions and plans use a credit or quota system, where a single long task can consume as much as dozens of ordinary Q&A exchanges. When a task scales from “a few hundred lines of script” to “an application with dozens of modules,” consumption grows by orders of magnitude. So measuring these models is not just about “can it build it”—it also means answering three engineering questions:

    1. Is the planning sound?
    2. Is execution stable?
    3. Is the cost per feature controllable?

    2. First, Separate Planning Ability from Execution Ability

    2.1 Definitions and Boundaries

    In an engineering context, a large model’s coding ability can be split into at least two layers:

    Capability Core Content Typical Failure Mode
    Planning Breaking down goals, identifying constraints, defining boundaries, designing modules and interfaces, setting milestones and acceptance criteria, anticipating risks Architecture waffling, repeatedly overturning approaches, ignoring key constraints
    Execution Writing, completing, and modifying code per an agreed plan, locating and fixing errors Local logic errors and missed edge cases, but the scope stays contained

    The key difference between the two is “the scope of error propagation.” Execution-layer errors are usually confined to a single function or file and can be quickly located and fixed through tests. Planning-layer errors affect all subsequent implementation: draw a module boundary wrong, and the interface has to be rewritten; misjudge a dependency, and the refactoring cost can rise exponentially.

    In long-horizon tasks, planning errors often surface only in the mid-to-late implementation stage—by which time a large budget has already been spent. This is precisely the real gap between a model with strong planning ability and one that merely “looks like it can write code.”

    2.2 Why Planning Should Use a Strong Model While Execution Can Be “Downgraded”

    A sensible cost structure matches real production practice:

    • The planning stage involves few calls but has a large impact, so it is worth using the most capable model, spending more budget to trade for a reliable approach;
    • The execution stage involves many calls but has a small per-call impact, so under clear specifications it can be handled by lower-cost models—even divided across tiers: batch implementation goes to mid-tier models, while mechanical changes like renaming, adding comments, and formatting go to lightweight models.

    The benefits are twofold:

    • Concentrate most of the budget on the stage that “determines global quality”;
    • Force the team to distill implicit knowledge into explicit documents—and that document itself is a reviewable, reusable, handoff-ready engineering asset.

    3. Evaluation Design: How to Scientifically “Probe” Coding Ability

    3.1 Choosing Representative Evaluation Targets

    The evaluation target should satisfy four conditions:

    1. Sufficient complexity: it requires cross-module collaboration and is not a single-file script;
    2. Clear boundaries: its functionality can be precisely described and turned into automated tests;
    3. Layered acceptance: it can be verified module by module, rather than judged only as a whole;
    4. Localizable failures: when something goes wrong, you can tell whether it is a planning mistake or an execution mistake.

    Spreadsheet-type applications are a typical fit, with complexity that can roughly be decomposed into these layers:

    1. Data model: using sparse storage to manage cells, so a sheet with millions of cells does not exhaust memory;
    2. Formula computation: including lexing, parsing, evaluation, and dependency tracking, while handling circular references and range references;
    3. Rendering and interaction: efficiently rendering large numbers of cells, plus selection, editing boxes, and frozen panes;
    4. File compatibility: reading and writing common spreadsheet file formats without losing styles and formulas;
    5. Extensibility: advanced features such as charts, pivot tables, and formatting rules.

    By code size, mainstream desktop operating systems run to tens of millions of lines; spreadsheet software has no public figures, but industry estimates suggest at least a million lines. So while spreadsheets are somewhat lower in complexity, they are enough to test a model’s planning and implementation ability in long-horizon tasks to a large extent.

    Beyond the desktop-OS example, spreadsheets have another clear advantage: results can be verified quantitatively. For instance, given a spreadsheet containing formulas, whether the program’s computed results match the expected values can be judged directly with automated tests.

    Note that there is a significant gap between a “prototype” and a “full product.” Take formula computation: a demonstrable prototype usually only needs basic operations and simple references, while a real product must also consider:

    • Precision and rounding rules;
    • Error propagation and display;
    • Circular reference handling;
    • Range references;
    • Implicit conversion of text, dates, and booleans;
    • Performance with massive numbers of formulas.

    Therefore, evaluations should clearly define “prototype-level” versus “production-level” acceptance criteria, to avoid mistaking a working prototype for product-level quality.

    3.2 Controlling Variables: Let Planning and Execution Each Own Their Part

    To avoid “one model doing everything” and making results impossible to attribute, this practice uses the following flow:

    1. Planning phase: the planning model reads the task description, produces a structured spec document, and saves it to disk—not just left in the conversation;
    2. Review phase: humans check module division, interface definitions, milestones, and the risk list;
    3. Execution phase: the execution model uses the spec document as its primary basis, implements code milestone by milestone, and runs the tests;
    4. Regression phase: update the spec document based on execution results, forming a “plan—execute—feedback” loop.

    Compared with “generate the final result from a single sentence,” this approach is closer to a real R&D process and makes the core question—“how strong is the planning?”—observable: the quality of the planning document is the most direct evidence of planning ability.

    4. Planning Phase: From Requirements to an Executable Spec Document

    4.1 What the Spec Document Should Contain

    A qualified spec document should answer at least six questions:

    • What to do and what not to do: clarify goals and scope boundaries, and list non-goals;
    • What constraints exist: tech stack, runtime environment, and performance and resource limits;
    • How to divide modules: each module’s responsibility, dependencies, and external interfaces;
    • How data flows: core data structures and their lifecycle;
    • How to accept: completion criteria for each milestone, ideally auto-executable checks;
    • Where it might go wrong: a risk list and fallback plans.

    Below is an illustrative spec document fragment, in a structured format so the execution model can read it directly:

    1. # spec.yaml — structured spec document produced in the planning phase (illustrative)
    2. project: "Spreadsheet application prototype"
    3. goal: "Support cell editing, formula computation, and basic formatting"
    4. non_goals:
    5. - Macros and scripting
    6. - Pivot tables
    7. - Real-time multi-user collaboration
    8. constraints:
    9. stack: ["TypeScript", "Pure front-end implementation with no backend dependency"]
    10. perf:
    11. recalc_budget_ms: 200 # Full-recalc budget for 1000 formulas
    12. render_budget_ms: 16 # Per-frame rendering budget
    13. modules:
    14. - id: grid-model
    15. responsibility: "Sparse cell storage and coordinate addressing"
    16. public_api: ["getCell(addr)", "setCell(addr, value)"]
    17. - id: formula-parser
    18. responsibility: "Parse formula text into an abstract syntax tree"
    19. public_api: ["parse(text) -> Node"]
    20. - id: calc-engine
    21. responsibility: "Dependency analysis and topological evaluation; detect circular references"
    22. public_api: ["recalculate(cells)"]
    23. - id: sheet-view
    24. responsibility: "Render the sheet and handle selection and editing interaction"
    25. public_api: ["render(cells)"]
    26. milestones:
    27. - id: m1
    28. name: "Grid read/write"
    29. acceptance: "100,000 random reads/writes all correct, time < 100ms"
    30. - id: m2
    31. name: "Formula evaluation"
    32. acceptance: "Pass rate >= 95% across 200 cases, no infinite loops"
    33. - id: m3
    34. name: "Rendering and interaction"
    35. acceptance: "Frame rate >= 50fps while scrolling and editing"
    36. risks:
    37. - "Circular reference causing infinite recursion -> topological sort + visit-state marking"
    38. - "Large-sheet rendering lag -> virtualized rendering, only render the visible region"
    39. budget:
    40. max_tokens_per_milestone: 2000000

    4.2 Modularity and Interface-First

    One of the most valuable things in planning is turning vague requirements into clear interface contracts. Take the formula computation module: dependency analysis typically uses topological sort. The illustrative code below detects circular references before evaluation to avoid runaway recursion:

    1. def recalculate(cells, deps):
    2. """Topologically sort by dependencies and evaluate in order; raise an exception when a circular reference is detected."""
    3. WHITE, GRAY, BLACK = 0, 1, 2
    4. color = {addr: WHITE for addr in cells}
    5. order = []
    6. def visit(addr, stack):
    7. if color[addr] == GRAY: # Gray means currently being visited
    8. cycle = " -> ".join(stack + [addr])
    9. raise ValueError(f"Circular reference: {cycle}")
    10. if color[addr] == BLACK: # Black means already finished
    11. return
    12. color[addr] = GRAY
    13. for dep in deps.get(addr, []):
    14. visit(dep, stack + [addr])
    15. color[addr] = BLACK
    16. order.append(addr)
    17. for addr in cells:
    18. visit(addr, [])
    19. values = {}
    20. for addr in order: # Dependencies are evaluated before their dependents
    21. values[addr] = cells[addr](values)
    22. return values

    Worth noting: constraints like “circular dependencies must be handled explicitly” often have to be actively identified by the planning model before the execution model can implement them stably. Whether such hidden difficulties can be anticipated during the planning phase is an important signal that distinguishes planning quality.

    4.3 Milestones and Acceptance Criteria

    Each milestone should have a “runnable, verifiable” deliverable:

    1. M1 data layer: correct cell read/write, with 100,000 random reads/writes completing within 100ms;
    2. M2 formula layer: a pass rate of at least 95% across 200 formula cases, with circular references correctly detected;
    3. M3 view layer: a frame rate of at least 50fps in scroll and edit scenarios;
    4. M4 integration layer: the end-to-end flow works, e.g., modifying A1 automatically updates all related cells.

    Breaking goals into small steps that are “verifiable at every step” is the core of keeping long-horizon tasks from spinning out of control.

    5. Execution Phase: Landing Reliably with Low-Cost Models

    5.1 Context Management: Docs First, Load on Demand

    The most common cause of failure in the execution phase is “context pollution”: early trial-and-error code, overturned approaches, and error messages all remain in the context and easily mislead the model.

    The recommended approach:

    • Files as the single source of truth: put spec documents, interface definitions, and test cases in the project directory, not just in the conversation;
    • Layered loading: load only the modules and tests relevant to the current milestone, rather than the entire codebase;
    • Periodic compression: after each milestone, distill the conversation history into a short status summary.

    5.2 Test-Driven Iteration and Failure Recovery

    Each milestone advances through a small “implement—run—fix” loop with a clear failure limit. Illustrative code:

    1. MAX_ATTEMPTS = 3 # Max number of consecutive fixes for the same milestone
    2. for milestone in spec.milestones:
    3. attempts = 0
    4. while attempts < MAX_ATTEMPTS:
    5. agent.implement(milestone) # Implement code per the spec
    6. report = run_tests(milestone.tests) # Run this milestone's tests
    7. if report.passed:
    8. agent.update_spec(milestone, report) # Write back the execution results
    9. break
    10. attempts += 1
    11. agent.fix(report.failures) # Local fix based only on failure info
    12. else:
    13. # Limit exceeded: pause and hand to a human to judge whether it is a spec or execution problem
    14. escalate_to_human(milestone, report)

    This loop has three key design points:

    1. Fixes rely only on the failure information and do not re-diverge the approach, avoiding the model starting over;
    2. A failure limit is set to prevent getting trapped in a “the more you fix, the messier it gets” attrition;
    3. When the limit is exceeded, a human judges the root cause—whether planning went wrong or execution ability fell short.

    5.3 Rollback Mechanism

    If the execution model introduces a serious problem at some step, it should be able to quickly return to the last runnable state. Specific practices include:

    • Record a version snapshot after each milestone completes;
    • On a problem, roll back first, then analyze the cause;
    • Avoid repeatedly “patching” the same messy codebase.

    5.4 Dedicated Edge-Case Testing

    In spreadsheet-type applications, the following issues are easily overlooked by models and should be written into the test list during the planning phase:

    • Empty cells participating in computation;
    • Cross-sheet references;
    • Circular references;
    • Floating-point precision;
    • Summing very large ranges.

    These cases should serve as a fixed regression test set, automatically run after each execution.

    6. Aesthetics and Visual Generation: Making Code “Draw” Usable Scenes

    Beyond practical software, another capability worth attention is visual generation: using code to generate visual content.

    6.1 From “Generating Images” to “Generating Scenes”

    Developers have previously used procedural methods to draw hundreds of thousands—even more—of brush strokes and produce highly realistic images. Such cases demonstrate the model’s potential in organizing visual parameters and iterative optimization, but they are closer to one-off “tech demos.”

    A more practically valuable approach is to bring procedural drawing into specific scenes. Take a Metroidvania-style dungeon scene, which involves these technical points:

    1. Composition and layout: procedurally generate terrain and building structures, ensuring spatial coherence;
    2. Light, shadow, and tone: a unified palette to create atmosphere;
    3. Detail layering: the layering and depth relationships among the far, mid, and near ground;
    4. Parametric iteration: treat brush stroke count, light direction, and color shift as adjustable parameters for continuous fine-tuning.

    Illustrative code:

    1. def render_city(width, height, palette, strokes=700_000):
    2. """Illustrative framework for procedurally drawing a dungeon scene."""
    3. canvas = Canvas(width, height)
    4. layout = generate_layout(width, height) # Procedurally generate the layout
    5. for layer in ["far", "mid", "near"]:
    6. for _ in range(strokes // 3): # Allocate an equal number of strokes to each depth layer
    7. x, y, angle = sample_stroke(layer, layout)
    8. color = sample_color(layer, palette) # Far tends cool, near tends warm
    9. canvas.draw_stroke(x, y, angle, color)
    10. return canvas

    6.2 Dimensions for Evaluating Aesthetic Ability

    Aesthetics are hard to fully quantify, but can be observed along these dimensions:

    • Composition reasonableness: is the subject prominent, and are the spatial relationships clear;
    • Light-shadow consistency: are the light direction, shadows, and tone unified;
    • Detail richness: is there repetitive texture or obvious blank space;
    • Style stability: do multiple generations maintain the same style;
    • Controllability: after adjusting parameters, does the effect change as expected.

    Among these, “controllability” is the key to combining aesthetic ability with engineering ability. Generation that can precisely adjust the effect on command is more practically valuable than accidentally producing one good-looking image.

    7. Cost Control: Spend the Budget Where It Counts

    The essence of cost control in long-horizon tasks is reducing “valueless context shuttling.” It can be approached from these angles:

    1. Plan-execute separation: a strong model does only the planning; execution is handed to low-cost models;
    2. Modular context: load only the modules and tests relevant to the current task;
    3. Compression and summarization: periodically compress conversation history while keeping key decisions;
    4. Caching and reuse: put stable spec documents and interface definitions into cacheable context to reduce repeated transmission;
    5. Failure limit: set a maximum fix count per milestone to avoid endless consumption;
    6. Budget guardrails: set a token limit per milestone, and pause and switch to human decision-making when the limit is reached;
    7. Parallelism and scheduling: independent milestones can advance in parallel, but watch API rate limits to avoid instantaneous peaks triggering throttling.

    When estimating cost in practice, count “planning-phase investment” separately from “execution-phase cumulative consumption” to judge whether planning quality genuinely delivers cost benefits.

    8. Conclusion and Practical Recommendations

    Back to the initial question: where exactly does a model’s long-horizon coding ability lie?

    The practice gives this answer:

    • Planning ability sets the ceiling: whether you can break complex requirements into clear, verifiable modules determines how far a task can go;
    • Execution ability sets the floor: under clear specifications, low-cost models can also reliably complete most of the implementation;
    • Engineering method determines cost-effectiveness: docs first, test-driven iteration, failure limits, and budget guardrails are the keys to keeping long-horizon tasks controllable.

    For developers who want to validate or use coding agents, start with a small but complete project—for example, implementing a spreadsheet prototype with basic formulas. Through the “strong-model planning, low-cost-model execution, test-driven verification” flow, you can both observe the model’s planning quality and gain reusable engineering assets at a controllable cost.