My AI wrote a bug, then fixed it itself

💥 AI Pitfalls 2026-07-11 · Updated 2026-10-27 4 min read

An async scraper failed with a wall of asyncio.TimeoutError. While I fetched water, Cursor's agent read the log, found three causes and edited the code itself, leaving a note. Useful — but only inside a bounded loop. Six steps: machine-readable logs, run-capture-feed-rerun, file and size limits, hypothesis before patch, tests plus diff review, and the correct 429/timeout fix.

📜 Table of Contents

📖 Keep reading

My AI wrote a bug, then quietly fixed it

One in the morning, writing a scraper for a rate-limited API. Three layers of async functions. First run: a screen full of asyncio.TimeoutError.

I got up for water. When I came back the editor's file tab had a modified marker. I hadn't touched it.

In those two minutes Cursor's agent read the error log, found three problems (no timeout, no 429 handling, unlimited concurrency), edited the code, and left a note: "Added retry and timeout control; timeout is twice the request timeout; 429 waits and retries."

My first reaction was not relief but "am I losing the skill." I read every changed line. It was better than what I had planned: more complete exception handling, a saner retry policy.

That night I turned it into a fixed process. The conclusion: self-healing works, but only with boundaries. Unbounded self-healing hands production to something that never says "I don't know."

1. Errors must be machine-readable

import logging, sys
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
    handlers=[logging.FileHandler("run.log", encoding="utf-8"),
              logging.StreamHandler(sys.stdout)],
)

Log to a file, include timestamps and levels, and use logging.exception so the traceback with real line numbers is present. My first version used print(e): 400 lines, no line numbers, nothing to reason about.

2. The loop: run, capture, feed, rerun

Feed the last ~100 lines plus the relevant functions. Require output as hypothesis, files and lines, then compare error counts:

grep -c "ERROR" run1.log run2.log

No reduction means the hypothesis was wrong. Roll back before re-hypothesizing; otherwise the model stacks five patches on one wrong idea.

3. Three boundaries

Boundary Rule Why
Files only src/fetcher/*.py stops unrelated "cleanups"
Size under 50 changed lines keeps review possible
Rounds max 3, then stop and report prevents patch archaeology

Also: never let it edit tests, never let it change dependency versions. Both are the shortest path to green and the fastest way to hide the bug.

4. Hypothesis before patch

Here is the failing log and the functions involved.

1. Root cause in one sentence
2. How you would verify it (concrete command or observation)
3. Which lines you would change if it holds

Wait for my confirmation before writing code.

One agent guessed "unstable network" and proposed rerunning ten times. Wrong: every error came from the second layer, so it was logic. Ten seconds of human review killed a wasted round.

5. Tests and diff review

Check Command If it fails
new dependency git diff requirements*.txt revert
tests modified git diff tests/ revert
swallowed exceptions grep except.*pass revert
hardcoded values grep URLs, tokens, ports move to config

Swallowing exceptions is the classic bad fix: the script finishes and you get empty data instead of a clear failure. Better to fail loudly.

6. The correct fix

SEM = asyncio.Semaphore(5)
TIMEOUT = aiohttp.ClientTimeout(total=30, connect=10)

async def fetch(session, url, tries=4):
    async with SEM:
        for attempt in range(tries):
            try:
                async with session.get(url, timeout=TIMEOUT) as r:
                    if r.status == 429:
                        wait = float(r.headers.get("Retry-After", 2 ** attempt))
                        await asyncio.sleep(wait); continue
                    r.raise_for_status()
                    return await r.text()
            except (asyncio.TimeoutError, aiohttp.ClientError):
                if attempt == tries - 1:
                    raise
                await asyncio.sleep(2 ** attempt)
    raise RuntimeError(f"exhausted retries: {url}")

Separate connect from total timeout. Honour Retry-After — 429 is not random, the server told you how long to wait. And raise on the last attempt instead of returning None, or the failure surfaces far from its cause.

7. Fit and misfit

Fits: reproducible errors, real logs, tests. Scrapers, pipelines, batch jobs.

Does not fit: production-only races, money or permission or deletion paths, and "feature is wrong" problems that are actually requirements problems.

FAQ

Is autonomous editing safe? With version control, tests and a small edit scope, it is safer than a tired human at 1am. Without any of the three, it is not.

When to stop? After three rounds. Three failed rounds usually means the problem is not in the code.

Tests don't cover it? Write the test first. Otherwise you cannot know it fixed the behaviour you care about.

Can a local model do this? It can, with lower accuracy. Let the small model compress 400 log lines into 20 and leave decisions to a larger one.

Agent capabilities differ per release; check the official docs.

Related

Related Articles
2026-07-12
AI helped me rewrite the same paragraph 12 times — and each version was better
2026-07-04
My horse forgot me in 4097 tokens.
2026-06-24
My horse became a plant parent. Named my succulent 'Steve'.
2026-07-01
One day AI will be gone too
2026-06-08
My horse had an existential crisis about being reset
2026-07-04
I asked two AIs to talk to each other. They discovered love.

Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.

💬 Comments (0)

No comments yet. Be the first!

Login to comment