Loading...
Skip to Content

Rethinking ERP Architecture for Long-Running Agentic AI: Why Event Sourcing and Saga Rollback?

Rethinking ERP Architecture for Long-Running Agentic AI: Why Event Sourcing and Saga Rollback?

  1. When AI does the work, there is work to undo

Businesses are asking AI to do more. Beyond answering questions, agents enter company systems to place orders and change delivery assignments. They must be accountable for the work they change as well as the answers they give.

This work takes more than a few seconds. Finding a material shortage, choosing another supplier, requesting purchase approval, receiving goods, and changing the production schedule can take days. This is long-running work.

Along the way, an AI mistake or a supplier stockout may require completed work to be undone. A manager may reject approval. Other employees keep working too. Reporting a failure does not clear the materials already reserved or the purchase orders already created.

Here is an example. There are 1,000 units of a part in stock. At 9 a.m. on Monday, an agent misreads demand and reserves 200 units. At 11 a.m. on Tuesday, warehouse staff ship 30 units for another order. At 2 p.m. on Tuesday, a manager spots the mistaken reservation and rejects approval. Now only the agent's work must be undone. The 30 units shipped by the employee must stay shipped, leaving 970 units in stock.

The key question is simple.

How can we safely undo work already done?

  2. MCP standardizes connections, but does not define undo

Previously, connecting AI meant writing integration code for each system. MCP is a shared protocol for connecting AI to external tools: a standard port. That is why its official documentation compares it to USB-C. A shared connection lets agents call tools under common rules.

Work follows three steps.

  1. Read: Check parts inventory and recent purchase prices.
  2. Decide: Weigh goals and limits, then choose tasks and their order.
  3. Act: Reserve materials and create purchase orders.

The challenge is acting. If approval is denied after materials are reserved and a purchase order is created, that work needs to be undone. The MCP tools specification dated 2025-06-18 does not define undo. This reflects a division of responsibilities, not a flaw in MCP. The business system behind the tools—the ERP—must handle it.

  3. How is the same work recorded in state-based and event-sourced systems?

How can the ERP recover from the mistake above? The answer depends on how it stores records.

A football scoreboard showing 2-1 tells you the score and nothing else. With the match record you can rebuild the scoreboard at any time, but the scoreboard alone cannot bring back the match record. A state-based system is the scoreboard; an event-sourced system is the match record. See how the mistake above is recorded in each system.

State-based: overwrite the same cells
TimeItemStock
Mon 08:00Part A1,000
Mon 09:00Part A800
Tue 11:00Part A770
Only the last row remains

Approval was rejected at Tue 14:00. The table does not show why stock fell by 200. Restoring 1,000 would also erase the 30 units shipped by an employee.

Event sourcing: add a row for each event
No.TimeWhat happenedWhoQuantity
1Mon 08:00Goods receivedWarehouse staff+1,000
2Mon 09:00Materials reserved (saga 41)Agent-200
3Tue 11:00Goods shippedWarehouse staff-30
4Tue 14:00Approval rejected (saga 41)Manager0
5Tue 14:00Reservation cancelled (saga 41)Server+200
Add all rows to get current stock970

The rejection is handled by adding row 5. Earlier rows remain, including the 30 units shipped by the employee.

A simplified example. Section 8 shows actual rows from the test.

Add the rows in order to find stock at any point
1
Goods received
+1,000
Total so far
1,000
2
Materials reserved
-200
Total so far
800
stock at Mon 10:00
3
Goods shipped
-30
Total so far
770
4
Approval rejected
0
Total so far
770
5
Reservation cancelled
+200
Total so far
970
stock now

You can always rebuild values from the rows. You cannot rebuild the rows from the values.

ComparisonState-based system (overwrites current values)Event-sourced system (keeps every event)
What it storesPart A, stock 770. Just one row.The five rows above. Add the rows to calculate stock.
Past analysis: stock at Mon 10:00?Not in the table. Look in backups or separate history records.Add rows 1–2 to get 800 units.
Audit: why did stock fall by 200?Not in the table. Look for separate logs, which may be missing or inconsistent.Row 2 shows it. The agent reserved them under saga 41.
Undo: what if approval is rejected?Overwriting with 1,000 also erases the 30 units shipped by the employee.Add row 5. Stock is 970, and rows 1–4 remain unchanged.
Agent actions: what belongs to this task?Look in conversations or separate records.Rows 2, 4, and 5, marked with saga 41.
Forecasting: demand lost to stockouts?Forecasts from sales records. Lost demand can look low, so estimates are used to adjust for it.Add rows by date to find days with 0 stock and account for them. Run the same forecast using rows up to a year ago and compare it with actual results.
Testing before acting (what-if): order more?Must first gather the history needed.Use the accumulated rows to calculate the original and changed plans side by side. No rows are added to the ledger.
CostSimple and familiar. Sufficient for most systems.Needs more storage and has short delays between modules. Moving an existing system is also costly.

State-based systems can also address much of this by adding history tables or a data warehouse. The difference is whether those records are the source of truth or an addition.

To undo a mistake, you need to know what was done, what the values were at the time, and which actions belonged to other people. With event sourcing, this information is in the records themselves.

  4. Three problems with state-based ERP

A traditional ERP is the main business ledger, or system of record (SoR). It overwrites table values with the latest values. This is the state-based approach described in the table above. This was familiar and intuitive when people clicked Save on screen. But keeping only current values creates problems when an agent's work needs to be cancelled days later.

The reason disappears

In the example above, when inventory changes from 1,000 → 800, the current value only shows 800. Without knowing what reduced it by 200 units, it is hard to know what to cancel. Restoring numbers without that context can leave records out of step with actual work (State Drift).

Time gaps cause trouble

In the example above, materials were reserved at 9 a.m. on Monday, then approval was denied at 2 p.m. on Tuesday. A database ROLLBACK on Tuesday cannot cancel work already committed on Monday. Overwriting the old value can also erase work done by other employees in between. This is called a lost update.

Erasing records causes audit problems

Accounting ledgers and manufacturing histories must not be quietly erased. Records must show who changed what, when, and why it was cancelled. The US FDA's 21 CFR 11.10(e) also requires changes to covered records not to obscure earlier records. It does not prescribe a storage method.

Separate history tables can help, but these extra records may be missing or differ from the original data.

  5. Use audit records as the source, and add cancelling actions instead of erasing

Event sourcing: a ledger that keeps every entry

Record +KRW 100,000, -KRW 30,000, and +KRW 50,000 in a bank account, and the balance is their sum. The five rows above are like that transaction history. Each row is called an event.

Most systems treat current values as the source and keep audit records separately. Event sourcing reverses this: the audit records themselves are the source, and current values are calculated from them. Audit data is the basis for calculating inventory on screen and finding work to cancel.

An agent's work builds up in the same way. Event names use the past tense because they describe things that have already happened.

StockReservedByAgent: Reserve 200 parts
PurchaseOrderCreated: Create a purchase order
ManagerApprovalRejected: Manager rejects approval

As Pat Helland put it in “Immutability Changes Everything” (2015), “Accountants don't use erasers.” Keep the mistake and add a record of its correction.

Sagas: add cancelling actions instead of erasing the past

A saga groups a task's steps together. If work stops partway through, it cancels completed steps in reverse order. A cancelling action that offsets the original action is called a compensating transaction. The concept comes from Garcia-Molina and Salem's paper “Sagas” (1987).

Cancelling a flight booking does not restore an old seat count. It adds a new action that cancels the reservation. This leaves other bookings made in the meantime intact. In a factory, if a process using issued materials is cancelled, the materials are received back into stock instead of erasing the issue record.

Having records does not mean every action can be cancelled. The system must check for later work that depends on it and leave cases it cannot cancel for a person to handle.

ComparisonUndo in a state-based ERPEvent sourcing + sagas
MethodOverwrite with earlier valuesAdd cancellation records with an opposite effect
Past contextFind the original conditions in separate history recordsKeep the original action, failure, and cancellation together
Impact on other workRestoring old values may lose changes made in betweenCheck later work and offset only the target task's effects
Audit and traceabilityWithout separate records, cancellation is hard to explainThe ledger keeps what happened and why it was cancelled

  6. Why use both together?

“Could we just add sagas to an existing ERP?” Yes. Sagas were originally designed for ordinary databases. But reliable undo needs two things.

  • Know the original values. If 100 units were reserved at KRW 1,250 after exchange rates and discounts, cancellation needs those terms and quantities, not today's price. The business records, called events, hold those values. With only current values, you must find them in separate history records.
  • Stay safe when a request arrives twice. Repeating the same request must give the same result (idempotency). If a response is lost and cancellation is requested twice, cancelling 100 units could turn into cancelling 200. Event versions, saga IDs, and request IDs filter out the second request. Event sourcing does not do this automatically; these checks must be built too.

A fixed workflow has steps and cancellation rules designed in advance. Agents choose tools as circumstances change. Even with cancellation rules for each tool, the system must read the completed work's records to decide what to undo. A state-based ERP needs to collect those records separately, effectively creating another ledger.

  7. Test outcomes first with the same ledger

Because nothing was erased, past records are still available. Inventory records can show whether weak dehumidifier sales last summer came from low demand or stockouts. Sales totals alone cannot tell you that.

What-if analysis calculates the original plan and a changed plan side by side. It adds nothing to the ledger. The numbers come from the same models used on the ERP screen, not from the LLM. People can ask and agents can answer. Agents do not yet run these calculations and decide on their own.

Across 60 virtual companies, the median quarterly revenue error was 6.6%. These were virtual tests; results at real companies may be worse. The predicted ranges for a one-year outlook were too narrow, so the system warns when looking more than 180 days ahead.

Test first, act, and undo mistakes. All three use the same ledger.

  8. Use the same ledger for faster dashboards and to find how work gets done

Separating writes from reads (CQRS) works well with event sourcing. Commands write events to the ledger. The read side uses those events to prepare the tables it needs. uEngine ERP separates figures that must be exact from those that can lag by a few seconds.

  • Figures that must be exact, as in closing the books. Inventory and journal entries are also written to separate tables within the same transaction as the command. Even with three years of data from a virtual company, the trial balance takes 0.016 seconds and the balance sheet takes 0.011 seconds.
  • Dashboards and statistics. The read model takes in new events every 5 seconds and updates only what has changed. Order confirmation does not wait for the read model, and the dashboard catches up within a few seconds.
Same query (45,000 events)Recalculate from the ledgerRead model
Full dashboard0.97 s0.017 s
Monthly revenue for the last 12 months0.39 s0.002 s
Include 3 new ordersRecalculate the entire materialized view: 0.42 s; this month's revenue remains KRW 0 until then0.012 s
Rebuild three years from scratchNot applicable0.87 s

Both methods gave the same results. Forecasts and 9 what-if scenarios run on the same data also gave identical results. Because events are the source records, the read model can be discarded and rebuilt at any time. A report designed today can include all three years of history. With only current values, state-based data makes it hard to fill in past periods for a new report. These timings used virtual company data on a development PC running other tasks too. Focus on the size of the difference between the two methods rather than the absolute times.

The ledger is already a process mining log

Process mining uses records to find the actual sequence of steps taken to handle an order. With state-based data, change history tables must be extracted separately to piece together what happened. The event sourcing ledger already holds those records.

uEngine ERP groups ledger records into order-to-cash and procure-to-pay cases and exports them as CSV, XES, and OCEL 2.0 files. Uploading these files to Process GPT produces BPMN without a language model. Three years of orders from a virtual company—3,287 orders—became a diagram in under 0.1 seconds, and every case could follow the paths in that diagram (100% replay fitness). The resulting process becomes a business process definition after review and approval by the person responsible.

Undo, test outcomes ahead of time, build fast dashboards, and find how work gets done. All use the same ledger.

  9. We tested it

We connected our own event-sourced uEngine ERP to the Process GPT Lite agent through MCP and ran it with a virtual company, Gaon Appliances.

Upload a tax invoice, then cancel in chat

Upload a tax invoice, then cancel in chat (Korean UI and narration)

  1. Upload, and it asks. An accounting employee uploads a tax invoice file to chat. Lite reads the supplier and amount (KRW 1,100,000), then asks, “Shall I process this in ERP?”
Reads the supplier and amount, then asks whether to proceed (Korean UI)

Reads the supplier and amount, then asks whether to proceed (Korean UI)

  1. Accept, and it processes the invoice. It finds the supplier and product, posts the voucher, and makes the payment. Inventory, accounting, and tax modules read those records and create the goods receipt, journal entries, and VAT totals. One saga ID ties the whole task together.
  1. Cancel in chat. Say, “I'll cancel what we just did.” We do not leave cancellation to the LLM. The server uses the ID to read the scope and check whether cancellation is allowed. It cancels the payment and posts a credit note in reverse order of the original actions. The relevant modules create stock returns and reversing journal entries. It also tells the user to request a corrected tax invoice from the supplier. Cancelling inside ERP does not correct external tax documents.
The server checks, then cancels the payment and voucher

The server checks, then cancels the payment and voucher

  1. Check the numbers in the ledger. Both the original work and its cancellation remain. No records are erased.
The ledger keeps both the original work and its cancellation

The ledger keeps both the original work and its cancellation

These are some of the 42 rows actually recorded in this test. Rows 129–149 record processing; rows 150–170 record cancellation. No rows were erased.

No.What happenedDocumentWho
134InvoicePosted Invoice postedBILL/2026/11/0001Agent (MCP)
136PaymentPosted Payment postedPAY/2026/00001Agent (MCP)
140JournalEntryPosted Journal entry postedBILL/2026/11/0001Accounting module
146PickingValidated Goods receivedWH/IN/00001Inventory module
148VatEntryRecorded VAT recordedBILL/2026/11/0001Tax module
153PaymentCancelled Payment cancelledPAY/2026/00001Cancellation (server)
157InvoicePosted Credit note postedRBILL/2026/11/0001Cancellation (server)
162JournalEntryPosted Reversing journal entry postedRBILL/2026/11/0001Accounting module
167PickingValidated Goods returnedWH/OUT/00001Inventory module
169VatEntryRecorded VAT adjustedRBILL/2026/11/0001Tax module
ItemNet change when processedNet change after undo
Bank deposits-KRW 1,100,0000
Input VAT+KRW 100,0000
Merchandise+KRW 1,000,0000
Air circulator motors+20 units0

This means the effects of this task were offset. It does not mean the company's total balances are zero.

  1. Stop when needed. If goods have since shipped, the accounting period is locked, or someone else has continued the work, it explains why and changes nothing. It also identifies who should handle the follow-up.
Explains why cancellation is blocked, then stops

Explains why cancellation is blocked, then stops

Process the work
Find supplier and product→Post voucher and pay→Inventory module receives goods→Accounting module creates entries→Tax module calculates totals
Add cancelling actions
Cancel payment→Post credit note→Inventory module returns goods→Accounting module reverses entries→Tax module adjusts totals
Both remain in the ledger; this task's net inventory and account changes are 0

The server checks the cancellation scope. If cancellation is blocked, it changes nothing.

Just ask in chat

Ask in chat and calculate without changing the ledger (Korean UI and narration)

This time, we use another virtual company with three years of records. Just ask a question in the usual chat window.

  • “What will sell the most in each quarter next year?” It gives the top product and its probability for each quarter. Air circulators have a probability of over 99% of ranking first in Q3 2027. Humidifiers have only a 39% probability in Q4. When it does not know, it says so.
Gives each quarter's top product and its probability

Gives each quarter's top product and its probability

  • “Can I trust this forecast?” It runs the same calculation using the ledger from a year earlier and compares it with actual results. Revenue in all 3 completed quarters fell within the predicted ranges. It got the top product right in 2 quarters.
  • “What happens if we increase that product's order quantity to 1.5 times the current amount?” It estimates about KRW 46.64 million more revenue over the next year. Inventory value also rises by about KRW 7.72 million.
Calculates revenue and inventory changes from larger orders

Calculates revenue and inventory changes from larger orders

  • “What if we raise the price by 10%?” The records do not show how customers would react, so it does not predict a direction. It only gives the break-even point: sales volume could fall by 19.4% with profit unchanged.

This conversation added 0 new records to the ledger. All figures come from a virtual company.

What we verified

Using a real LLM and real MCP, we ran voucher processing, cancellation in chat, and question-and-answer conversations 5 times each. All passed. These were local tests with virtual companies, not production results, and the Process GPT Lite integration will be released soon. Tax screens await expert review, and the app does not directly issue electronic tax invoices or submit electronic tax filings. Installation on real Supabase cloud has not yet been tested. A person must check the supplier and amount read from the file on the card.

  10. Success depends on a system that can handle mistakes

It is easy to focus only on the latest LLM and prompts. Once an agent operates ERP, the key question changes: “Can our system safely handle AI's mistakes?”

Not every system needs event sourcing. Microsoft's Event Sourcing pattern document also explains that traditional methods are enough for most systems. Start with systems where agents change transactions, inventory, and payments. Ask four questions before adopting them.

  • Can we ask what will change before acting?
  • Can we explain what the agent did?
  • Can we undo it without disturbing someone else's work?
  • If undo is not possible, can it stop and hand over to the person responsible?

Success depends on a system that can handle mistakes, not the model's intelligence.

Industry AI Solutions

The three products differ in recordkeeping and supported features. The figures and screens below were tested with virtual companies and synthetic data.

ProductCurrent status
uEngine ERPUndo and testing before acting are implemented. It is free (MIT) and connects to your own Supabase. The app and source are public; cloud installation is untested.
uEngine MESA demonstration reference implementation of an event-sourced manufacturing execution system. Source code is private; contact us for a demo. Each action has a matching cancelling action, but there is no undo screen for people to use.
uEngine WMSA Process GPT sample app. It provides 83 MCP tools and public source code, and is free to install yourself. It uses audit logs rather than event sourcing and has no undo feature.

Alongside business records, you also need human approval, shared meaning across systems, and a way to choose work for agents.

What is neededWhat we provide
Processes where agents work and people approveProcess GPT, Process GPT Lite
Reversible business recordsuEngine ERP, uEngine MES
A layer connecting meaning across systemsOntological Studio, Ontological DB
Finding work suitable for agentsAgent Storming workshop

  References