cd /news/ai-agents/your-ai-agent-failed-halfway-who-und… · home › topics › ai-agents › article
[ARTICLE · art-178727] src=pub.towardsai.net ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Your AI Agent Failed Halfway. Who Undoes the Charge?

A Medium Towards Artificial Intelligence post demonstrates that a saved intent journal, not an in-memory list, is needed to unwind multi-step AI agent tool calls when a step fails mid-chain. In the author's Python/SQLite test of four services, the in-memory design handled one of four failure modes — clear refusal, lost reply, slow request, and process crash — while the journal recovered all but the slow-request case, where a booking arrived after rollback. The author's fix has the service itself close each step's ID so late requests are refused, citing Microsoft's saga-pattern guidance that compensating transactions reverse rather than restore state.

recommendation

Record each tool call's intent in a durable journal and close the step's ID in the service so late or duplicate requests are refused; the author's in-memory list handled 1 of 4 failure cases, the journal 3 of 4.

more in playbook: Designing agent systems
read7 min views7 publishedNov 30, 2026

An AI agent often does a job in several steps, each one a “tool” call that changes something. Part 1 looked at one call that ran twice. This part looks at a chain of calls that stops in the middle.

A customer of a fictional bookstore wants a different, pricier book. The agent has four steps:

Step 3 gets no answer. The agent apologizes and stops.

The error message is honest, and the order is still broken. The customer has paid, a book is off the shelf, and no one has said whether a van is coming.

A single database can protect you here with a transaction: all the changes happen, or none do. Four separate services give you no such shared switch. Each step is already saved by the time the next one fails.

The usual answer is the saga pattern: run a series of separate transactions, and if one fails, run compensating transactions that reverse the earlier ones [1]. A compensating transaction is simply a second action written to counter the first.

“Counter” matters. Microsoft’s guidance says a compensating transaction does not necessarily return data to its starting state [2]. In my test, a refunded order ends with two entries in the payment record, a charge and a refund. The balance is back to zero, and the history is not.

The email cannot be unsent, so it runs last. Microsoft’s saga guidance calls the point of no return a pivot [1].

Sort your own tools into these three groups before writing any rollback code. A tool with no entry in the “how to undo it” column needs a place at the end of the chain, or a person’s approval.

I built the four services in Python as one SQLite event table, using only the standard library. The “agent” is a scripted workflow. I left the language model out because the test is about what happens after a call fails.

I compared four designs:

Then I made step 3 fail in four ways: a clear refusal, a lost reply (booked, then silence), a slow request (booked after the undo), and a process crash just after the booking.

The in-memory list is the version many people would write first, and it handled one case out of four.

The saved journal fixes both because it records intent. “I was about to book a pickup” tells the recovery code to check, whether or not a reply ever came. Undoing something that never happened has to be harmless, so my undo acts only if it finds the step.

I also ran this one for real: a child process was killed right after step 3, with the services and journal in files on disk. A different process, with only those files to go on, read the journal and cleared all three steps. Without a journal, there was nothing to read.

The saved journal still lost one case.

The agent gives up on a slow booking and cancels it. The courier truthfully replies that nothing is booked. Then the original request arrives, and the pickup is created after the rollback has finished.

This is the same gap as “check, then retry” in Part 1, seen from the other side. The fix is also in the same place: the service decides.

def do(self, order_id, step):    """Run a step once. Refuse it if its ID has been closed."""    with self.db:        self.db.execute(            "INSERT OR IGNORE INTO events SELECT ?, ?, 'do', ? WHERE NOT EXISTS "            "(SELECT 1 FROM closed WHERE order_id = ? AND step = ?)",            (order_id, step, f"{order_id}:{step}:do", order_id, step))def close(self, order_id, step):    """Close the step's ID so a late request is refused, and undo it if it happened.    For the final step, report 'done' if it already happened."""    with self.db:        # Take the write lock first, so the check below and the write are one unit.        self.db.execute("INSERT OR IGNORE INTO closed VALUES (?, ?)", (order_id, step))        if step == FINAL:            if self.happened(order_id, step):                return "done"            return "not done"        self._write_undo(order_id, step, f"{order_id}:{step}:undo")    return "undone"

Closing writes a marker even when there is nothing to undo. A request that shows up later finds the marker and does nothing. I raced the two calls on separate database connections 200 times, and no run left the step in place.

The idea has a history. A 2022 Apache Seata blog post describes the same problem in its TCC transaction mode, where a cancel runs before a delayed first request, and solves it by recording the branch as suspended so the late request is rejected [3].

The same method handles the email. Rollback runs newest first, so it asks about the email before undoing anything. If the email already went out, the order stands. If not, closing its ID stops it from leaving later.

An undo is another network call. It can time out, and then you retry it.

I made a refund succeed, lost its reply, and retried. Without a key on the undo, the customer got two refunds. With one key per undo, one. Azure’s guidance asks for compensating steps that are safe to repeat [2], and Part 1 shows how to get that.

Next I ran 10,000 fictional orders at several failure rates. Each call, including each undo, could fail, and every call also had a 1% chance of crashing the process. These rates are settings in my simulation, not measurements. A given call failed the same way under every design.

An order counted as half-done if, at the end, some steps remained in place but not all four.

At a 20% failure rate:

At 30%, the last design left 14 half-done orders. All 14 were marked for review, after repeated attempts got no confirmation.

Clean is not the same as successful. At the 20% rate, the strongest design completed 4,237 orders and rolled back 5,762. I did not retry failed steps before rolling back. A real workflow should retry with the same ID first, and undo only when it gives up.

Keep this logic in ordinary code. I would let a model choose what to attempt, and keep it out of deciding what gets undone.

If a service cannot close an ID, delayed requests remain a risk. Compare its records with your journal after the longest delay you expect, and correct what you find.

The agent is a script, so this says nothing about how a model behaves when a step fails. One SQLite table stands in for four services, and their “close” operation is my design: check whether your real services offer anything like it. Journal writes never fail in the simulation. Slow requests are delayed by a few calls in the volume test, and until the end in the single-failure test. Recovery restarts until it finishes. I did not test two workflows changing the same order, other people seeing the half-finished state, or how long closed IDs must be kept. A saga does not hide intermediate states from others [1].

Write down each step before you take it, and close its ID before you undo it.

The code, tests and raw output are here: https://github.com/bmdayal/blog-agent-failure-drills/tree/main/part2-rollback. Run python3 rollback.py, add a fifth step, and decide where it goes.

Agent Failure Drills: the series

Part 1 · The Refund Worked. The Agent Sent It Again.

Part 2 · Your AI Agent Failed Halfway. Who Undoes the Charge?? (this article)

Part 3 · AI Agent Memory: How Stale Facts Drive Wrong Actions.

Part 4 · AI Agent Permissions: Whose Access Is It Using?

Part 5 · You Deleted the Record. Can Your AI Agent Still See It?

Part 6 · Data Lineage for AI Agents: Trace Any Answer to Source.

Your AI Agent Failed Halfway. Who Undoes the Charge? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

── more in #ai-agents 4 stories · sorted by recency
── more on @microsoft 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/your-ai-agent-failed…] indexed:0 read:7min 2026-11-30 · —