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. Beyond Chatbots: Long-Running Agentic AI That Executes Business Work

What businesses want AI to do is changing. Answering questions and summarizing reports is no longer enough. They expect agents to detect material shortages, find alternative suppliers, request purchase approval, and handle receipts and payments. Agents are entering enterprise systems to execute real business work.

Waiting for supplier responses, approvals, and goods receipts takes hours or days. Agents move across ERP, SCM, WMS, and MES, read earlier results, and choose the next tool. This is the work of long-running agentic AI.

While an agent waits, other employees reserve materials and warehouses ship goods. The agent may make a wrong decision, a partner may run out of stock, or a manager may reject the purchase. The assumption that everything will finish as planned can quickly break down.

“Processing failed” is not an adequate response. What happens to the materials already reserved, purchase orders already issued, and entries already recorded in the books?

Before giving an agent authority to act, check how it can safely undo work it has already performed.

  2. Why MCP Emerged and How It Works

Building custom integrations for each system increases maintenance work as an agent gains tools. MCP is a common protocol connecting AI applications to external tools. Its official documentation explains: “Think of MCP like a USB-C port for AI applications.” The analogy is a USB-C port for AI applications.

An agent's work follows this flow.

  1. Observe and query (Read): Read component inventory and recent supplier prices to understand the current situation.
  2. Decide and plan (Plan): Choose the tools and call sequence needed to meet the goal within its constraints.
  3. Act and execute (Exec): Reserve materials, create purchase orders, and request shipping.

What if approval is rejected after materials have been reserved and a purchase order created? Explaining the last error does not resolve the effects of earlier steps.

The 2025-06-18 version of the MCP tools specification does not define tool transactions, rollback, or compensation. It also states that tool annotations should not be trusted unless they come from a trusted server. A tool description is not sufficient evidence of safety.

MCP defines how to call tools, but does not define how to undo their effects. The system behind each tool must handle that. This is a division of responsibilities, rather than a flaw in MCP.

  3. Why Traditional ERP That Overwrites Data (CRUD) Breaks Down with Agents

ERP is a System of Record (SoR) for business operations. Agents need to read both the current numbers and the changes they made, along with the reasons. An overwrite-based design without sufficient history has three problems.

Current Values Cannot Identify an Agent's Work

Suppose inventory changes from 1,000 units to 800. Reading the current inventory of 800 does not tell you which order caused the reduction of 200. The number does not say whether those units were reserved or shipped, or whether an agent or an employee performed the action.

A request to “undo what you did then” must not change the books based on guesses from a conversation. The actual execution record must identify the items, quantities, and linked documents. CRUD systems can do this with separate history. The problem arises when the latest state is treated as the source of truth and execution context as supplementary information.

Other Work Continues While an Agent Waits

Materials may be reserved on Monday morning and approval rejected on Tuesday afternoon. ROLLBACK cannot undo a committed transaction. A database transaction rollback and withdrawal of completed business work the next day are different operations.

Restoring an earlier inventory snapshot can cause lost updates by overwriting other employees' reservations and shipments. The agent must reverse the effect of its own reservation without affecting those operations.

Erasing Mistakes Also Erases Evidence of Their Resolution

Deleting an incorrectly posted voucher makes it harder to explain what the agent did and how it was reversed. The person responsible needs to see who acted, why, and how the problem was resolved, as well as the final numbers.

For covered records, the US FDA's 21 CFR 11.10(e) requires secure audit trails that independently record the date and time of creation, modification, and deletion, and specifies that changes must not obscure previous records. Event sourcing fits these requirements well. However, the regulation does not mandate a particular storage method, and adopting event sourcing does not by itself ensure compliance. Operational policies and access controls for agent activity records are also necessary.

  4. The Solution: Combining Event Sourcing with Saga Rollback

Event Sourcing: A Digital Ledger That Retains What an Agent Did

Event sourcing records business events as the source of truth instead of storing just the current value. Like a bank account that records deposits and withdrawals in sequence and calculates the balance, it builds current inventory and accounting states from accumulated events.

An agent's reservation, purchase order, and rejected approval are recorded as events like these. This is an illustrative example.

StockReservedByAgent: 200 parts reserved
PurchaseOrderCreated: purchase order written
ManagerApprovalRejected: manager refused approval

In “Immutability Changes Everything,” Pat Helland writes: “The truth is the log. The database is a cache of a subset of the log.” In this view, the log holds the truth and the database caches part of it. The same paper's analogy, “Accountants Don’t Use Erasers,” fits this context. Resolving an agent's mistake should add a record of the correction rather than erase the original record. ([Source](https://www.cidrdb.org/cidr2015/Papers/CIDR15_Paper16.pdf))

The Saga Pattern: Undo Effects Through Actions, Without Erasing What Happened

Event sourcing records what happened; a saga addresses how to resolve the effects of work that stopped partway through. It executes compensating transactions to release reservations and cancel purchase orders. Saga rollback here means compensation appropriate to the business operation, rather than ROLLBACK of an already committed database transaction.

Garcia-Molina and Salem's “Sagas” (1987) describes compensation as undoing the effects of earlier actions in business terms. It does not necessarily return the database to its state before those actions began. Canceling an airline reservation should reduce the reservation count by one. Restoring the seat count from the time of booking would ignore reservations made in the meantime. The same principle applies when an agent cancels a material reservation.

The paper's guarantee is execution of all of T1…Tn, or execution of T1…Tj followed by compensation Cj…C1. Since the entire long-running operation is not locked, compensation conditions, retries, and human exception handling also need to be designed.

ComparisonUndo Based on Current Values and Past SnapshotsEvent Sourcing + Saga Compensation
Evidence of agent executionTargets and conditions must be found in separate historyOriginal events provide facts from the time of execution
Cancellation methodRestoring previous values risks overwriting intervening changesNew events offset the effects of the operation itself
Relationship to other workSnapshots alone make subsequent work difficult to distinguishCausality and versions are checked to determine whether compensation can proceed
Review by the responsible personOriginal execution and cancellation records are compared separatelyLinked execution and compensation records explain what happened

  5. Why Event Sourcing Matters for Reliable Saga Rollback

“Could we add a saga orchestrator on top of an existing CRUD ERP?” Yes. Sagas were originally designed for conventional databases in 1987 and can be built on ERP systems that overwrite data. Event sourcing is not a prerequisite storage method for implementing a saga.

But when agents become the main executors, the starting point for design changes.

In a classical saga, developers design the steps and compensation in advance. An agent's work is not designed in advance.

A fixed workflow defines its steps and failure compensation ahead of time. Agents choose tools according to the situation. This time an agent uses an existing business partner; next time it starts by creating one. Even with predefined compensation rules for each tool, the actual combination, sequence, and reasons for execution must be established from the records afterward.

Evidence of Execution Must Remain Even When Plans Change

Suppose an agent applies exchange rates and discounts to reserve 100 units of raw material at 1,250 won per unit. Cancellation requires the conditions applied at that time and the quantity actually reserved, rather than today's unit price. The system must also know which purchase order the reservation was linked to and whether it subsequently led to receipt or payment.

Implementing this on an overwrite-based ERP requires separate change history, call group identifiers, versions, retry keys, and causal tracing. Building these records amounts to recreating an event log. Supplementary records may be missing or inconsistent when managed separately from actual changes. In event sourcing, those records are themselves the source of truth. The numbers on the current screen and the basis for reversal come from the same business facts.

Retries and Compensation Must Be Part of the System Contract

An agent that receives no response may request the same cancellation again. Without a retry key, a request to cancel 100 units could execute twice and cancel 200. Event sourcing does not automatically prevent duplicate execution. Saga identifiers, operation identifiers, version checks, and duplicate-request handling must work together.

A transactional outbox can address the dual-write problem in which a database write succeeds but message publication fails; this benefit is not exclusive to event sourcing. What matters is a structure that makes it possible to determine what has finished and what needs to be retried, from the agent's request through processing by downstream modules.

Oracle's “When AI Agents Meet Enterprise Reality” (2026) explains that durable execution withstands infrastructure failures, compensation patterns resolve partial business effects, and reliable enterprise automation needs both. In that article, developers also define business compensation logic in advance. An agent's ability to plan does not mean it should invent compensation rules as it goes.

The Zavora paper also proposes a reference architecture with agents as the main operators, storing significant actions as immutable events for commitments, obligations, evidence, and settlement. It should not be read as proven production results. It is a design proposal for the records and controls that should support agent execution.

  6. Read the Past and Simulate Before Acting with the Retained Ledger

To work in ERP, agents need somewhere to ask questions before acting, as much as they need execution and cancellation. Current values cannot answer “What will sell most in each quarter next year?”, “How much revenue will we make?”, or “What happens if we change this?”

Read History That Today's Numbers Do Not Contain

Today's inventory number does not show how many days dehumidifier stock was at 0 last summer. If the system cannot distinguish low sales caused by stockouts from low demand, it will forecast too little, order too little, and run out again. The ledger lets it recalculate inventory for that day. An overwrite-based system can do similar work with separate history or a data warehouse. The distinction is whether that record is the source of truth or a supplement.

Agents can also reconstruct what the system knew at a given time. Running the same forecast with the ledger as it stood 1 year earlier and comparing it with subsequent actual results validates predictions against the company's own records. Facts learned later do not leak into the historical forecast.

Run What-If Analysis Without Writing to the Ledger

The agent runs the baseline and proposed change side by side with the same demand and lead times, presenting the difference as an interval. If the interval includes 0, it answers “cannot distinguish.” Nothing is recorded in the ledger, and when evidence is insufficient, it explains what is missing instead of supplying a number.

The LLM does not invent the numbers. It translates the question into a choice of model and inputs. The same model used by the ERP screen calculates results from ledger facts, so people and agents receive consistent answers. Access rights are the same: an agent cannot receive an answer calculated from documents it cannot read.

What Tests with Synthetic Companies Established

Using ledgers through early November 2025 from 60 generator-created synthetic companies, we forecast the four quarters of 2026 and compared them with actual outcomes. In this synthetic company test, the median quarterly revenue error was 6.6%, and 80% intervals contained actual revenue in 91% of cases. The predicted top product for a quarter matched the actual demand leader in 75% of cases.

We separately tested what-if analysis looking 1 year ahead. Across 30 synthetic companies, we doubled summer-product order quantities by a factor of 2, discontinued products, or increased lead times by a factor of 1.6. The direction of change was correct in every case, with errors in the size of the change of 10~13.5%. However, 80% intervals contained actual outcomes in 53~80% of cases, below their stated level. The model therefore warns that prediction intervals are too narrow for horizons beyond 180 days.

In the same synthetic company test, top-product accuracy was 98% in the summer quarter and 47% in the 4th quarter, when two products were closely matched. The model's stated probabilities of ranking first were 98% and 44%, respectively: it reports uncertainty when it does not know.

For synthetic companies with frequent stockouts, reading sales records directly produced a summer demand error of 32% and understated demand by 30%. Including inventory history reduced the error to 9.5%. Treating gaps in sales as stockouts and excluding them gave similar results, so inventory history is not the sole approach. But one approach relies on inference and the other on records. Since the generator and estimator share assumptions, results for real companies should be expected to be worse.

Responses Beyond the Records Remain Assumptions

How many customers leave after a price change is not read from the records. For “What if we raise the selling price by 10%?”, the model gives the break-even point—revenue stays the same even if volume falls by 9.1%—without predicting a direction. If given an assumption, it labels it as an assumption and calculates accordingly. New products, promotions, and market changes are not included.

We have implemented the flow in which a person asks and an agent answers. Having agents simulate independently and make decisions is the next step.

Simulate first, execute, and undo if something goes wrong. All three draw on the same ledger.

  7. A Working Example: Execution and Reversal with Our Agent and ERP

The uEngine ERP app and source are public, and the Process GPT Lite integration has completed testing and will be released soon.

We connected our event-sourced uEngine ERP to our Process GPT Lite agent through MCP and ran it. Accountant Jeong at the synthetic company Gaon Appliances handles the process from file input through execution and cancellation. The product screens shown are in Korean.

Scenario: Upload a Tax Invoice

The whole flow on video (Korean UI and narration)

1. Upload: Attach a file without a message. Accountant Jeong attaches a tax invoice file to the Process GPT Lite chat. The agent reads the file for clues about the work to start.

Just the tax invoice file, no words (Korean UI)

Just the tax invoice file, no words (Korean UI)

2. Ask: Reading does not trigger immediate execution. Lite identifies the supplier as Hanbit Parts Co., Ltd., the approval number as 20261103-41000000-00001234, and the amount as 1,100,000 won, then asks, “Shall I process this in ERP?” If the document is unsuitable for voucher processing, it does not offer to process it; if the amounts do not match, it explains the discrepancy.

Lite reads the file and asks whether to process it in the ERP

Lite reads the file and asks whether to process it in the ERP

3. Workflow: Acceptance starts work across modules. Through MCP, the agent looks up business partners and products, creates missing records, and handles voucher posting and payment through a single voucher-entry command. The server groups every call in this process under saga identifier dbf3657a…. Inventory, accounting, and tax modules subscribe to the events and create goods receipts, accounting vouchers, and VAT reporting aggregates. The system traces derived results to determine the scope of cancellation.

Once accepted, the work runs over MCP and the steps show

Once accepted, the work runs over MCP and the steps show

4. Results: Report verified facts. Success of the first request does not mean the entire operation is declared complete. The agent waits for subscribers to finish processing events, then reports confirmed results such as voucher BILL/2026/11/0001 and payment PAY/2026/00001. The ERP screen shows the same results.

The result is reported only after the subscribers have finished

The result is reported only after the subscribers have finished

The same result seen in uEngine ERP

The same result seen in uEngine ERP

5. Cancel in words: Request “Cancel what you just did.” The user identifies the work to cancel, and the agent links the request to the saga identifier. Compensation is not delegated to the LLM. The server reads the execution scope and linked results and checks whether compensation is allowed. It directly performs two compensating actions—canceling the payment and posting a credit note—in reverse execution order. Subscribers respond to those events by creating inventory returns, reversing entries, and reporting aggregates. For products using average costing, the unit cost changed at receipt is also restored. The system also warns that a revised tax invoice must be requested from the supplier, because compensation inside ERP does not correct external tax documents.

"Cancel that" runs the compensation, and the net change comes out as zero

"Cancel that" runs the compensation, and the net change comes out as zero

6. Ledger: Verify through numbers, beyond the agent's words. Both the original execution and compensation remain, with no records deleted. Calculating the net inventory change by location and the net accounting change by account for this saga and its compensation gives 0 in every case. This means the effects of this operation have been offset; it does not refer to the company's total balances.

The ledger keeps both the original work and the compensation

The ledger keeps both the original work and the compensation

ItemNet Change on ProcessingNet Change After Reversal
Bank deposits-1,100,000 won0
Input VAT+100,000 won0
Merchandise+1,000,000 won0
Air circulator motors+20 units0

7. When to stop: Check conditions that prohibit cancellation. If goods have since shipped, the accounting period is locked, or someone else has continued the work, compensation does not proceed. The server explains the blocker and who must handle the follow-up. In this implementation, a compensation request proceeds in full or not at all. It does not skip blocked operations and arbitrarily cancel the rest. This behavior must not be generalized into an atomicity guarantee across arbitrary external systems.

When it must not proceed, it says why and changes nothing

When it must not proceed, it says why and changes nothing

The work, under one saga id
Find supplier and product→Post voucher and pay→Receipt (inventory subscribes)→Entry (accounting subscribes)→VAT entry (tax subscribes)
Cancel that
Cancel payment→Post credit note→Return (inventory subscribes)→Reversing entry (accounting subscribes)→VAT offset (tax subscribes)
Ledger: both remain, and the net change in stock and accounts is 0

Compensation runs in reverse order, and subscribers follow from the events

Scenario: Ask a Question in Chat

Forecast and what-if asked in chat, on video (Korean UI and narration)

This time, the synthetic company has 3 years of history. The user asks a question in the usual Process GPT Lite chat window, without finding a menu or completing a form.

1. “What will sell most in each quarter next year?” Cards show each quarter's top product, quantity interval, and probability of ranking first. For the synthetic company, air circulators are forecast to lead sales in the 3rd quarter of 2027 at around 6,457 units. The 80% interval is 5,352~8,077 units, with a probability of at least 99% of ranking first that quarter. Humidifiers, forecast to lead in the 4th quarter, have a probability of just 39%. The answer explains that basic air purifiers have a similar chance.

Ask in the chat and it gives the top product per quarter and how likely that is

Ask in the chat and it gives the top product per quarter and how likely that is

2. “How much revenue will we make next year?” The answer separates the synthetic company's next-year revenue into a scenario with current supply and one where all demand is met. In hundreds of millions of won, the estimates are around 61.4 and 70.3, respectively; the difference of 8.9 is revenue lost to stockouts. Calculating air circulator demand for the 3rd quarter from sales records alone gives 3,972 units. Accounting for 146 stockout days over the past 1 year, identified from inventory history, raises the estimate to 6,545 units.

Revenue if supply stays as it is, and if all demand is met

Revenue if supply stays as it is, and if all demand is met

3. “Can I trust this forecast?” The agent runs the same calculation on the ledger as it stood 1 year earlier and compares it with actual results. For the synthetic company, it checks predictions based on facts known through November 2, 2025. Actual revenue for all 3 completed quarters fell within the prediction intervals, and the top product was correct in 2 of those quarters. In the 2nd quarter, the forecast placed basic air purifiers first, but air circulators actually sold the most.

The same forecast from the ledger of a year ago, held against what happened

The same forecast from the ledger of a year ago, held against what happened

4. “What happens if we increase order quantities for that product by a factor of 1.5?” The agent runs a what-if analysis for the product in the previous answer. For the synthetic company, increasing air circulator order quantities by a factor of 1.5 is forecast to increase revenue over the next 1 year. Expressed in tens of thousands of won, the estimated increase is around 4,664, with an 80% interval of +694~+9,535. Stockout days summed across product and warehouse combinations are forecast to fall by around 33 days, while inventory value rises by around 772, also in tens of thousands of won.

A what-if on the product from the previous answer

A what-if on the product from the previous answer

5. “What if we raise the price by 10%?” The answer explains the break-even point instead of predicting the direction of change. For the synthetic company, profit stays the same even if sales volume falls by 19.4%. Revenue stays the same even if volume falls by 9.1%. If the user supplies an assumption for price elasticity, the agent labels the calculation as based on that assumption and presents the result.

How customers respond is not on record, so it gives the break-even

How customers respond is not on record, so it gives the break-even

6. This conversation created 0 events in the ledger. It queried the synthetic company's ledger without making changes.

What the MCP Calls Look Like

There are 4 MCP tools, and they also handle reversal. The first call reads the plan without making changes. A change request then uses the mode determined by the server and the plan hash, followed by checks on subscriber processing and net changes.

// Inspect what will be reversed and how. Nothing changes
const plan = await call('erp_read', { rollback: { correlation_id: saga_id } })
// plan.mode: rollback | compensate | blocked

await call('erp_create', {
  type: 'rollback',
  values: { correlation_id: saga_id, plan_hash: plan.hash },
  reason: 'Cancel that',
})

// Check that subscribers have finished and the net change is 0
const status = await call('erp_read', { saga: saga_id })

Calculations run on the caller's side. ERP's MCP supplies facts, and the agent-side server runs the same model used by the screen.

// Read facts through MCP. Read the historical ledger through the same route
const rpc = (fn, args) => call('erp_read', { analytics: { fn, args } })
const now = buildPanel(await loadLedger(rpc))
const then = buildPanel(await loadLedger(rpc, { asOf: '2025-11-03' }))

quarterOutlook(now)            // Next year's quarterly leaders and revenue
quarterBacktest(now, then)     // Repeat with facts known then; compare with actual results
whatIfPolicy(now, { changes }) // Run baseline and proposed change side by side
ModeProcessing Determined by the Server
rollbackIf nothing blocks it, reverse the entire target operation. Original records remain.
compensateOffset work that cannot be deleted, such as posted vouchers, with opposing transactions.
blockedExplain why the operation is prohibited and make no changes.

What Testing Established and What It Has Not

We tested the final code with a real LLM and real MCP. Voucher processing passed 5 out of 5 runs, conversational cancellation passed 5 out of 5, and question-and-answer conversations passed 5 out of 5. In a run of the version immediately before the final code, part of a test supplier's name was omitted once when reading it. When the model gateway stalled for a few minutes, the response asked the user to resend, without displaying a card. The supplier name is not checked twice, so a person must verify it on the card. These are test results from a synthetic company in a local environment, not production results.

Permissions are also limited. An agent may compensate for its own MCP work when no one else has built on that work. An administrator handles other cases. Integration keys cannot exceed the member's permissions.

Tax-related screens have not yet undergone expert review. The app does not directly issue electronic tax invoices or submit electronic tax filings.

Because ledger records cannot be deleted, sensitive information is kept outside the ledger.

Our Industrial Solutions

Here are uEngine's event-sourced industry solutions with reversible operations and related integration samples. WMS differs from ERP and MES in implementation and scope.

SolutionCurrent Scope and Release Status
uEngine ERPImplements event sourcing and MCP reversal. Provides agents with next-year quarterly outlooks and what-if analysis. It is free to use by connecting your own Supabase. The app and source are public. Installing on real Supabase cloud has not been tested yet.
uEngine MESA demonstration reference implementation of an event-sourced manufacturing execution system. Source code is private; contact us for a demonstration. There is no human-facing undo screen, and exec functions have compensation counterparts.
uEngine WMSA Process GPT sample app with 83 MCP tools and public source code. It uses audit logs rather than event sourcing and has no reversal feature.

  8. Conclusion: Adopting AI Agents Requires Modernizing the Backend SoR

Start by understanding the costs. Not every system needs event sourcing. Microsoft's Event Sourcing pattern also explains that traditional data management is sufficient for most systems and their components. Migrating an existing system is costly, and adoption constrains later design choices. Read projections are eventually consistent with original events, so the design must specify when agents read which state and how they determine completion.

The same document explains that cancellation adds compensating events. Start where there is a clear reason to accept the cost: the SoR where agents change real transactions, inventory, and payments. Examine work with substantial accountability first.

Do not base adoption decisions just on the latest LLM's performance and prompts. Can you ask what will change before execution? Can you explain what the agent did in ERP? Can it undo its work without interfering with someone else's? Can it stop and hand the issue to a responsible person when reversal cannot proceed?

Success depends on an architecture that can handle mistakes, beyond the model's intelligence.

To expand autonomy along the execution path MCP opens, systems need event-sourced records, saga compensation, human approval, and access controls. Build a flow that simulates first, executes, and reverses mistakes using the same ledger.

uEngine addresses this beyond the storage design of a single ERP. We provide the broader agentic AI architecture: processes where agents work, reversible business records, semantic connections between systems, and discovery of work suitable 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 workshops

  References