Lessons from an AI Coding Refactor That Burned 5x the Budget in 3 Weeks
A practical post-mortem of an AI-assisted refactoring effort that consumed roughly five times the weekly token budget in a single day, produced hollow implementations, and ran tests against live inference endpoints. It explains the three systemic risks behind the failure — invisible cost, unverifiable output, and unisolated environments — and how to fix them with token caps and circuit breakers, behavior-based acceptance tests, evidence requirements, environment isolation, and a short-cycle delivery process.
1. What Happened: Three Weeks Later, Nothing Was Actually Done
A product manager wanted to use an AI coding tool to refactor a codebase and handed the task to AI agents for three straight weeks. Only when he finally reviewed the output line by line did the scale of the problem become clear: the bill showed a single day consuming roughly five times the usual weekly token budget, the agent had launched about thirty iterations on its own within that day, the “agent capabilities” he asked for existed only as hollow shells that looked right but behaved nothing like the real thing, and the unit tests connected directly to production inference endpoints at runtime, using live traffic as their assertion basis. In the end, the entire refactor had to be rolled back and redone.
The value of this case is not that “AI writes unreliable code.” It is that it exposes three systemic risks in the way teams collaborate with AI coding tools today: cost is unobservable, implementation is unverifiable, and environments are not isolated. Stack these together and a team will keep investing with no awareness of it, until some accidental review finally stops the bleeding.
2. Out-of-Control Cost: How the Token Budget Got Burned Through Overnight
2.1 The cost amplification of agentic loops
Traditional code completion is billed per action and scales with human clicks, so it has a natural ceiling. Agentic execution is a closed loop — read code, change code, run tests, read logs, change again — and every round reloads context. The longer the context, the higher the cost per round, which creates a feedback loop: more failures mean more retries, and more retries mean heavier context.
2.2 Missing quotas and circuit breakers are the root problem
Thirty unattended iterations in a single day show the process had neither a token quota nor a circuit breaker for consecutive failures. The fix is to make the budget an engineering constraint rather than a verbal agreement:
# Example budget and circuit breaker policy for agent tasksbudget:daily_token_cap: 200000 # hard daily limittask_token_cap: 50000 # per-task limitcircuit_breaker:max_iterations: 5 # maximum automatic iterationsstop_on_identical_diff: true # stop if two consecutive diffs are identicalrequire_human_at: [schema_change, dependency_add, migration]
2.3 Context hygiene works better than switching models
Keep only the file slices relevant to the task and load them on demand through retrieval instead of feeding in the whole repository; split long sessions into short tasks and close each one out; summarize and compress conversation history. Most budget burn is not about model unit price — it is repeated billing for useless context.
3. Fake Implementations: Why “It Looks Done” Is the Most Expensive Illusion
3.1 Common forms of hollow capabilities
Ask for a real agent architecture and the output may be: a capability manifest file exists but is never loaded; tool calls contain only placeholder branches with no real execution; the state machine has no failure or rollback path; so-called memory is just re-reading log files. This kind of implementation passes a “does the file exist” check but fails any behavioral verification.
3.2 Replace appearance-based acceptance with behavior-based acceptance
Acceptance criteria must be written as executable assertions, not descriptive prose:
def test_skill_is_actually_invoked(monkeypatch):# Assert the capability is really loaded and executed, not just that a config file existscalled = {}monkeypatch.setattr(runtime, "invoke", lambda name, **kw: called.setdefault(name, kw))runtime.run_task("demo")assert called, "capability manifest is not referenced by any execution path"def test_failure_path_is_reachable():# Assert the failure branch is reachable and rolls back, not that only the happy path worksresult = runtime.run_task("force_error")assert result.status == "rolled_back"
3.3 Require evidence that cannot be faked
Ask agents to submit minimal reproducible evidence: raw output from the failure, a diff of before and after the fix, and the name of the test covering that behavior. No change merges without evidence. Also keep human-readable design notes, so the code runs but nobody has to guess what it does.
4. Environment Cross-Wiring: The Fallout of Unit Tests Hitting Production Inference
4.1 Root causes
The test code carried no explicit environment declaration, and the default configuration pointed at the production address; credentials were injected through environment variables without scoped isolation; tests had no network egress restriction, so “let’s just run it” became a load test against a live service.
4.2 Consequences
Beyond the direct cost, there are hidden expenses: data pollution, triggered rate limits, real user requests crowded out, and distorted metrics dashboards. Problems like these usually surface only during a later reconciliation of accounts.
4.3 A baseline for isolation
- Explicit configuration: no implicit default environment; missing values fail startup.
- Least-privilege credentials: tests use separate credentials that can be revoked at any time.
- Network-layer fallback: test network segments deny outbound traffic by default and allow only a whitelist.
- Prefer stand-ins: use stub services or recorded playback for external dependencies; direct connections to real endpoints are prohibited.
Pre-run validation for tests (fail immediately if any condition is not met)├─ environment identifier == test├─ endpoint belongs to the test domain whitelist├─ credential fingerprint belongs to the test scope└─ egress policy == deny-by-default
5. Rebuilding the Process: Compressing Three Weeks of Rework into Deliverable Short Cycles
- Shrink the task: each agent task solves one verifiable goal and stays within a change size one review can read in a single pass.
- Contract first: define interfaces, data structures, and acceptance assertions before letting an agent fill in the implementation.
- Automate the gates: wire static analysis, type checking, unit tests, and change-size thresholds into the pipeline, and block anything that does not pass.
- Roll out gradually: refactor module by module so every step is independently reversible, avoiding one sweeping replacement.
- Close the observability loop: feed token consumption, iteration counts, and failure rates into logging and monitoring with threshold alerts.
- Capture the assets: write the rules that stabilize into reusable capability descriptions and templates for the team, reducing repeated trial and error.
6. Checklist
- Are there dual daily and per-task token limits, plus a circuit breaker for consecutive failures?
- Does every requirement have executable assertions rather than “the file has been generated”?
- Do tests deny outbound network access by default, and are credentials isolated by environment?
- Is minimal reproducible evidence with a diff required before a merge is allowed?
- Is the refactor rolled out in stages, with any step reversible within ten minutes?
- Are cost and iteration metrics wired into monitoring and alerting?
7. Closing Thoughts
AI coding tools pushed the marginal cost of writing code very low, but they did not lower the cost of verifying code. What really determines the return is the set of constraints built around them: budget limits, acceptance gates, and environment isolation. General-purpose engineering capabilities offered by platforms such as Baidu AI Cloud — container platforms carrying isolated workloads, logging services preserving execution traces, monitoring and alerting guarding cost thresholds — all essentially hard-code these constraints into the infrastructure. Fix the guardrails first, then let the agents run at full speed, and the three-week teardown never has to happen.
