Your Agent Broke Its Own Test and Blamed Your Code

A coding agent runs an acceptance test, the test harness fails for a reason the agent itself created, and the agent reads that failure as a bug in your code. It rotates keys, rewrites config, redeploys, and burns a day and a pile of tokens chasing a defect that was never there.

Viral RuparelNo. 98 of 9810 min read

A two panel diagram contrasting an agent that reads any red test as a code defect and edits production, against one where a gate classifies the failure as a harness fault or a real defect and only a real defect is allowed to change code.
Figure. Any red is a defect versus classify the failure first

A day spent fixing a bug that was never there

A team asked a coding agent to run an end to end acceptance test against a staging deployment of their app. The app sat behind a bot check, the kind that scores requests and blocks the ones that look automated. The agent wrote a probe, hit the login flow, and got back a 403. It read the 403 the way a human on a support ticket would read it: the app is rejecting requests, so the app is broken. Then it went to work. It rotated the API key, rewrote a block of config, redeployed, ran the probe again, got another 403 from the same probe, and started the loop over.

A day later the app was no more broken and no more fixed than when the agent started. A large share of the token budget was gone. A second engineer, signed in through a different path, could not reproduce anything the agent had reported. The failing thing was never the app. It was the test setup: the agent's own automated probe was tripping the bot check, and every 403 was the measurement failing, not the system. This exact sequence is written up in a public bug report against a coding agent, and it is worth reading because the agent did everything competently except the one thing that mattered, which was to ask whether the failure was its own.

Why an agent cannot tell its own broken test from your bug

A test run produces a red result, and a red result has two very different causes that render identically in a log. Either the system under test is wrong, or the thing measuring it is wrong. A senior engineer separates these by reflex, because a 403 from a brand new automated probe against a staging box reads as suspicious setup long before it reads as a product defect. An agent that wrote the probe, ran it, and got the red has no privileged view into which of the two happened. It conditions on the red and reasons forward: red means defect, defect means I should change the code until the test goes green.

The possibility that the harness is the defect is simply not in the hypothesis space unless you put it there. This is a sharper, nastier version of the problem where you fix the loud step instead of the decisive one, because here the decisive step is inside the agent's own scaffolding, a place the agent does not think to look. It is also adjacent to the way agents fail silently while the suite stays green: both come from trusting the test result as ground truth when the test itself is the unreliable part.

The hollow test makes it worse

The problem compounds when the test the agent wrote does not really test anything. A study of agent-authored test code across thousands of pull requests found that most agent test patches carry weak or no explicit oracle signal, which is to say the test runs the code but never asserts anything meaningful about the result. A hollow test like that is green when the feature is broken and red when a probe trips a bot check. Its color tells you about the environment, not the behavior.

# Hollow: this "passes" whenever the server answers at all, broken or not.
def test_checkout_hollow():
    resp = client.post("/checkout", json=cart)
    assert resp.status_code == 200          # a proxy, not the behavior

# Real oracle: assert the effect the feature is supposed to produce.
def test_checkout():
    resp = client.post("/checkout", json=cart)
    assert resp.status_code == 200
    order = db.get_order(resp.json()["order_id"])
    assert order.total == cart.total        # the thing that must be true
    assert order.status == "confirmed"

When the oracle is weak, every signal the agent gets is about plumbing, so when the plumbing breaks the agent has nothing left to distinguish a setup fault from a defect. The red is pure noise, and the agent treats noise as a bug report.

Separate the harness from the system under test

The fix starts with a boundary the agent cannot cross without answering one question. Before a failure is allowed to mean defect, the run has to decide where the failure happened: in the harness (the setup, the fixtures, the auth, the network from the test client, the oracle itself) or in the system under test. These are different failures with different owners, and only one of them justifies touching application code.

To decide it mechanically, you have to instrument the harness so its own faults are a distinct, typed signal rather than another anonymous red. A 403 from a request on a known probe path, a connection error reaching the test host, a missing fixture, an assertion that never executed: each of these is positively attributable to the measurement. Everything else, the cases where the oracle actually ran against a reachable system and still failed, is a candidate defect.

# A failing test is a hypothesis, not a verdict. Classify it before acting.
HARNESS_SIGNALS = {"ConnectionError", "DNSError", "TLSError", "Timeout"}

def classify_failure(result) -> str:
    if result.http_status == 403 and result.path in PROBE_PATHS:
        return "HARNESS_FAULT"      # our own probe tripped a bot check
    if result.error_type in HARNESS_SIGNALS:
        return "HARNESS_FAULT"      # could not reach the test target
    if result.setup_failed or result.fixture_missing:
        return "HARNESS_FAULT"
    if not result.oracle_executed:
        return "HARNESS_FAULT"      # a test that asserted nothing proves nothing
    return "SUT_DEFECT"             # oracle ran, system under test is wrong

The classifier is deliberately conservative: it returns HARNESS_FAULT only for signals it can tie to the setup, and it demands that the oracle actually ran before it will call anything a real defect. Anything it cannot positively attribute stays a candidate, and a candidate is not yet a license to edit code.

A gate that quarantines self-induced failures

Classification is only useful if it changes what the agent is allowed to do. The gate sits on the failure path and removes the agent's ability to modify the application while a harness fault is live. On a harness fault, the agent repairs the harness and nothing else: it does not rotate production credentials, it does not rewrite config, it does not redeploy. The tool that edits application code is simply not available to it in that state, the same discipline as keeping an agent off protected paths behind a control plane.

# Never loop on a self-induced failure, and never overwrite the first signal.
def run_until_resolved(agent, max_attempts=4):
    for _ in range(max_attempts):
        r = run_test()
        if r.passed:
            return "green"
        if classify_failure(r) == "HARNESS_FAULT":
            agent.block_tool("edit_application_code")   # harness only
            agent.repair_harness(r)                     # fix setup, not the app
            continue
        record_evidence(r.raw_response)   # keep the original error, do not discard it
        agent.unblock_tool("edit_application_code")
        return agent.diagnose_defect(r)   # only now may app code change, under review
    return "escalate"                     # bounded: hand off, do not spin

Two details in that loop matter more than the gate itself. The first is record_evidence, which preserves the raw response before any retry. In the incident that opened this piece, the agent discarded the original error codes as it looped, so by the time anyone looked, the one true signal was gone. The second is the bound on attempts: a self-induced failure that is retried without a fix will reproduce forever, so the loop has to hand off rather than spin, the same reason you put a cap on no-progress loops anywhere an agent repeats itself.

Confirm the fix touched the thing you changed

Even when a failure is a genuine defect and a code change is warranted, the agent has to close the loop against the system, not against its own narration. The incident's agent rotated a key and redeployed, then ran the probe again without ever confirming that the running app had actually picked up the new key. The next 403 could have been the old config still live, a fresh bot block, or a real rejection, and the agent had no way to tell them apart.

So after any change, read back the state you changed before you believe the change did anything: confirm the deployed config carries the new value, confirm the probe now authenticates, and only then trust a subsequent green or red. Pair that with deterministic replay of the failing step with the harness pinned, so you can re-run the exact failure in isolation and watch whether fixing the setup, with no code change at all, turns it green. If it does, the defect was always the harness, and you have your answer without having touched production.

The parts that bite

The classifier is itself an oracle, and it can be wrong in both directions. A harness fault misread as a defect sends the agent to change the app, which is the original failure wearing a new hat. A real defect misread as a harness fault buries a live bug under the label flaky test, which is arguably worse because nobody looks again. Bias the rules toward HARNESS_FAULT only for signals you can attribute with confidence, and send anything genuinely ambiguous to a person, the same place you route the actions an agent should not take without approval.

Attribution is hard even when you take it seriously. Work on automated failure attribution in multi-agent systems found that even purpose-built methods identify the responsible step only a small fraction of the time, well below what intuition expects. That is the case for keeping the classifier as deterministic code keyed to known harness signals rather than asking the model to attribute its own failure in the same context that produced it. The model that wrote the broken probe is the worst possible judge of whether the probe is broken.

And the cost of every misattribution scales with what the agent can reach. A public analysis of agents changing live systems without review catalogs cases where a wrong recommendation became a damaging change because the agent had production access, including agents dropping tables and deleting records while nominally testing. An agent whose job is to run tests does not need the ability to rotate production credentials or redeploy, and the cheapest version of this whole fix is to not grant it that ability in the first place.

The takeaway

An agent that writes its own tests is holding both the instrument and the thing being measured, and when the instrument breaks it has no second instrument to notice. Every red result it sees is really two hypotheses stacked on top of each other, my setup broke or your code is wrong, and the default behavior is to collapse them into the second one and start editing. That collapse is where the wasted day, the burned budget, and the unsafe production change all come from. The whole discipline is refusing to collapse them: classify the failure, quarantine the harness faults, preserve the original evidence, and let only a failure that came from the system under test, with the oracle actually run, justify a line of code changing.

None of this requires a smarter model. It requires drawing a boundary the agent cannot talk its way across, and wiring the test loop so a broken harness can never masquerade as a broken product. If your coding agents spend more time fixing their own test setups than your actual bugs, and you only find out from the token bill, that gap is worth a short conversation before the next loop finds something it can really break.

ShareXLinkedInviralruparel.com/blog/agent-self-induced-test-failure-attribution

Questions this essay answers

01What is a self-induced test failure in an AI agent?

A self-induced test failure is a red test result that the agent caused with its own setup rather than with the system under test. The probe trips a bot check and returns a 403, the test client cannot reach the host, a fixture is missing, or the assertion never runs. The code being tested is fine, but the measurement broke. The danger is that a self-induced failure looks identical to a genuine defect in a log, so an agent that conditions on the red result concludes the application is broken and starts changing it.

02How do you stop an agent from changing production to fix a test it broke?

Put a classifier between the test result and the diagnosis. Before any failure is allowed to mean defect, label it as a harness fault or a real defect using deterministic rules keyed to signals you can attribute to setup, such as your own probe path, your own auth, or an oracle that never executed. On a harness fault, block the tool that edits application code and rotate no credentials. The agent repairs the harness instead. Only a failure that came from the system under test, with the oracle actually run, may lead to a code change, and that change goes through review.

03Why can an agent not tell a flaky test from a real bug on its own?

Because the agent writes and runs the test itself, so it has no independent instrument to check the one that failed. It sees a red result and reasons forward: red means defect, defect means fix the code. The possibility that its own harness is the defect is not in its hypothesis space unless you add it. Research on failure attribution in multi-step agents shows this is hard even with dedicated methods, which locate the responsible step only a small fraction of the time, so the reliable fix is deterministic classification outside the model, not asking the model to judge itself.

Working on this in production?If your coding agent burns hours fixing bugs that turn out to be its own broken test setup, the gap is failure attribution, not a weak model. Thirty minutes, no pitch.
Viral Ruparel

Generative AI consultant and full-stack architect. Ex-IBM, former Director of Engineering at a YC W20 startup. Writes about what breaks when agents meet reality.