AI Modernization on Legacy ERP Languages: ABAP, TROIA, Delphi & Stored Procedures
Why frontier LLMs trained on Python and TypeScript hallucinate on SAP ABAP, Canias TROIA, Delphi COM wrappers, and 5,000-line T-SQL/PL/SQL procedures—and how Ontology Extraction modernizes them safely.
- 01Frontier LLMs trained overwhelmingly on public
PythonandTypeScriptcorpora hallucinate heavily on low-resource, stateful enterprise ERP stacks:SAP ABAP(Z*custom programs & implicit enhancements),Canias ERP TROIA(proprietary 4GL scripts),Object Pascal / Delphi(Logo Objects&NetOpenXCOM/STAwrappers), and3,000–8,000lineT-SQL/PL/SQLstored procedures. - 02Attempting to "rip-and-rewrite" legacy stored procedures and ERP modules into microservices using AI code translation silently breaks lock-ordering invariants, VAT penny-allocation loops, undocumented export/withholding tax branches, and cascading audit triggers.
- 03Production modernization follows "Extract Semantics, Keep Tested Kernel Execution": combining static
ASTparsing with runtime SQL/RFC traces to lift buried business rules into declarative Ontology Objects, Join Contracts, Status Dictionaries, and Action Preconditions. - 04AI agents execute zero-hallucination analytical reads over zero-copy ERP read replicas via compiled ontology SQL while routing governed writes exclusively through the ERP’s battle-tested official business-object APIs (
BAPI,Logo Objects,NetOpenX,TROIAservices).
1. The Low-Resource ERP Code Reality: ABAP, TROIA, Delphi & 8,000-Line Stored Procedures
Vendor demos of AI-assisted legacy modernization almost always showcase clean Java or Python repositories with high unit-test coverage. Real industrial, automotive-tier, textile, food, and distribution enterprises across EMEA run on a completely different substrate: low-resource, stateful, proprietary ERP languages that barely exist in public open-source pretraining datasets.
Across brownfield manufacturing and distribution groups, twenty years of pricing formulas, multi-level BOM costing, statutory e-Invoice tax rules, and warehouse lot allocations live inside four tightly coupled layers: SAP ABAP custom namespaces (Z* / Y*), Canias ERP TROIA proprietary 4GL dialog scripts, Object Pascal / Delphi desktop add-ons and Win32 COM wrappers, and 3,000 to 8,000 line T-SQL / PL/SQL stored procedures.
When engineering teams paste these artifacts into a frontier LLM with the prompt "translate this into a clean TypeScript or Python microservice," the model does far worse than emit syntax errors—it hallucinates runtime semantics. Code that compiles cleanly in CI routinely corrupts general-ledger subledgers, lot traceability, or statutory tax filings at month-end close.
SAP ABAP(Z*Reports,BAPIWrappers & Implicit Enhancements): Real SAP business rules hide insideENHANCEMENT-POINThooks, legacy internal tablesWITH HEADER LINE,CONVERSION_EXIT_ALPHA_INPUTzero-padding routines, statefulSY-SUBRCreturn-code mutations, and strictENQUEUE_E_*->BAPI_*->BAPI_TRANSACTION_COMMITLogical Unit of Work (LUW) sequences that LLMs routinely drop or reorder.Canias ERP TROIA(Proprietary 4GL Dialog & Table State Scripts):TROIAhas virtually zero public training footprint. Its execution model mutates in-memory UI grid controls, session globals, andIAS*composite-key tables insideBEFORE/AFTERdialog triggers. Prompted to translate or generateTROIA, frontier LLMs invent nonexistent keywords or conflate stateful dialog cursors with stateless SQL.Object Pascal / Delphi(Logo Objects,NetOpenX,Firebird&BDE): Custom plant-floor weighbridge, barcode, subcontracting, and rebate extensions are heavily written inDelphi, invoking Win32COMSingle-Threaded Apartment (STA) wrappers such asLogo Objects(UnityObjects.UnityApplication) and NetsisNetOpenX, alongside business validation buried inTDataSet.BeforePost/OnCalcFieldsevents and embeddedFirebirdPSQL triggers.3,000–8,000LineT-SQL&PL/SQLStored Procedures (sp_*): Decades of consultant patches accumulate into monolithic procedures driven by nested cursors, session-scoped#temptable state machines,@@TRANCOUNTsavepoint gymnastics, dynamicsp_executesqlstrings, and cascadingAFTER UPDATEtriggers. Context-compressed LLMs silently elide "rare" conditional branches.
2. Why "Rip-and-Rewrite Stored Procedures With AI" Fails Financial & Tax Invariants
Feeding a 6,500-line sp_CloseSalesInvoice procedure or custom ABAP / TROIA pricing routine into an AI coding agent to generate a greenfield Node.js or Python service treats legacy ERP code as pure data transformation. In production, a battle-tested ERP procedure is simultaneously a pessimistic lock coordinator, a statutory penny-reconciliation engine, and a regulatory audit-trail emitter.
Automated code translation reproduces the surface-level SELECT and UPDATE statements while destroying four invisible invariants that were hardened over decades of tax audits and peak concurrency incidents.
| Enterprise Invariant Class | Legacy ERP / SQL Mechanism | Naive AI Microservice Rewrite | Financial & Statutory Blast Radius |
|---|---|---|---|
| Implicit Lock-Ordering & Concurrency | Deterministic lock acquisition order (UPDLOCK, HOLDLOCK, SELECT FOR UPDATE, SAP ENQUEUE) | Async ORM calls (await Promise.all) with optimistic app-layer checks | Negative warehouse inventory, double-allocated ATP stock lots, and production deadlock storms |
| Rounding & VAT Penny-Allocation Loops | Cursor loop allocating 0.01 header-vs-line tax/FX rounding residuals onto the largest invoice line | Independent per-line Math.round() or IEEE-754 floating-point math | Government e-Invoice (UBL / e-Fatura) XML checksum rejection and subledger-to-GL penny drift |
| Undocumented Tax & Export Branch Flags | Line 4,720 IF branches for customs export regimes, free-zone VAT exemptions, or cumulative withholding (Tevkifat) thresholds | Model summarizes or drops "edge-case" branches during context-window compression | Illegal tax calculation on export/withholding invoices and severe statutory audit penalties |
| Cascading Triggers & Side-Effect Ledgers | AFTER INSERT/UPDATE triggers populating cost-accounting journals, lot genealogy, and EDI outboxes | Half the trigger logic duplicated in service code while database triggers remain active (or get bypassed) | Double-posted general ledger journal entries or broken quality lot-recall genealogy |
An ABAP BAPI, TROIA posting kernel, Logo Objects COM engine, or T-SQL closing procedure that has settled billions in audited invoices is an asset, not disposable boilerplate. Modernize by extracting its hidden business semantics into a declarative ontology while keeping tested kernel execution intact.
3. The Ontology Extraction Pattern: "Extract Semantics, Keep Tested Kernel Execution"
Rather than translating legacy ERP procedures into fragile greenfield microservices, high-reliability engineering teams apply the Ontology Extraction Pattern. Under this architecture, ABAP, TROIA, Delphi, and T-SQL / PL/SQL codebases are treated as ground-truth mining inputs rather than translation targets.
By combining static AST and control-flow analysis (ABAP syntax trees, TSqlParser ASTs, TROIA class exports, Delphi .pas/.dfm trees) with runtime execution traces (SQL Server Extended Events, SAP ST05 / SAT traces, COM invocation logs), hidden invariants are lifted into four declarative ontology primitives: (1) Canonical Ontology Objects, (2) Verified Join Contracts, (3) Status & Bitmask Dictionaries, and (4) Kinetic Action Preconditions.
Once extracted, read and write paths cleanly bifurcate: AI agents answer complex cross-departmental questions by compiling deterministic SQL against zero-copy CDC / read replicas using verified ontology definitions. When an agent proposes an operational mutation, the ontology deterministically checks all preconditions, enforces a human-in-the-loop approval gate, and executes the write exclusively through the ERP’s official business-object API—never via raw INSERT or UPDATE statements against underlying ERP tables.
- Lifting Implicit Joins into Join Contracts: Zero-padded
SAP ALPHAdocument keys,Canias IAS*compositeCLIENT + COMPANY + BUSAREAkeys, and polymorphicLOGICALREFlinks inLogo/Netsisare extracted once from legacy code and enforced automatically by the ontology compiler. - Lifting Magic Constants into Status Dictionaries:
Delphi.pasconstants (const stShippable = 4) and buriedT-SQLpredicates (TRCODE IN (7, 8) AND CANCELLED = 0) become governed semantic metrics (VerifiedNetWholesaleInvoice), preventing agents from ever counting cancelled or proforma rows as revenue. - Lifting Deep Validation into Precondition Gates: Credit-exposure formulas, closed fiscal-period locks, and quality-hold checks buried deep inside stored procedures are surfaced as declarative preconditions so agents catch policy violations before invoking slow
BAPIorCOMtransactions.
// ontology/contracts/sales-order-release.contract.ts
export const SalesOrderReleaseContract = {
entity: 'SalesOrder',
version: '2026.12.1',
// 1. Read-replica projection mined from sp_CheckOrderCreditExposure (lines 1420-1890) & Delphi BeforePost
readReplicaProjectionSql: `
SELECT
o.LOGICALREF AS order_id,
o.FICHENO AS order_number,
c.CODE AS customer_code,
-- Extracted from legacy Pascal constants: TRCODE=1 (Sales Order), STATUS=4 (Shippable), CANCELLED=0
CASE o.STATUS
WHEN 1 THEN 'PROPOSAL_PENDING'
WHEN 2 THEN 'UNSHIPPABLE_HOLD'
WHEN 4 THEN 'SHIPPABLE_APPROVED'
END AS canonical_order_status,
-- Penny-exact credit risk: Open AR Ledger + Uncleared Portfolio Cheques + Approved Open Orders
CAST(r.OPEN_LEDGER_TRY + r.PORTFOLIO_CHEQUE_TRY + r.OPEN_SHIPPABLE_ORD_TRY AS NUMERIC(18,2))
AS total_credit_exposure_try,
CAST(r.CREDIT_LIMIT_TRY AS NUMERIC(18,2)) AS credit_limit_try
FROM erp_replica.LG_301_01_ORFICHE o
JOIN erp_replica.LG_301_CLCARD c ON c.LOGICALREF = o.CLIENTREF
JOIN ontology_views.v_customer_realtime_risk r ON r.client_ref = c.LOGICALREF
WHERE o.TRCODE = 1 AND o.CANCELLED = 0
`,
// 2. Deterministic preconditions evaluated BEFORE the agent can propose a write action
kineticAction: {
name: 'release_order_from_credit_hold',
requiresHumanApproval: true,
approverRoles: ['FINANCE_CONTROLLER', 'CREDIT_COMMITTEE_LEAD'],
preconditions: [
{
code: 'FISCAL_PERIOD_OPEN',
check: 'order_date > erp_system.closed_fiscal_lock_date',
failMessage: 'Cannot mutate sales orders dated inside a closed fiscal period.',
},
{
code: 'EXPOSURE_WITHIN_TOLERANCE',
check: '(total_credit_exposure_try + order_net_try) <= credit_limit_try * 1.05',
failMessage: 'Total credit exposure exceeds the 5% credit-committee tolerance band.',
},
],
// 3. Raw SQL UPDATE FORBIDDEN: Dispatch strictly via serialized official ERP business-object kernel
kernelExecutionTarget: {
adapter: 'ERP_OFFICIAL_KERNEL_QUEUE',
method: 'SalesOrderKernel.ApproveOrderStatus',
idempotencyKeyFields: ['order_id', 'ontology_version', 'approval_ticket_id'],
},
},
} as const;4. 4-Step Brownfield Extraction Blueprint: AST Slicing & 0.00-Penny Shadow Reconciliation
Attempting to reverse-engineer every Z* report, TROIA dialog, and sp_* procedure in a twenty-year-old ERP landscape stalls modernization programs indefinitely—especially because 50–70% of custom objects in mature ERPs are dormant historical artifacts from retired campaigns or superseded tax regimes.
Combining runtime trace harvesting with shadow financial reconciliation lets small engineering teams bring core finance, procurement, inventory, and production domains onto an AI-ready ontology within 4–6 weeks with zero operational disruption.
- Step 1 — Live Execution Trace Harvesting (
ST05/Extended Events): Capture 90 days of production read/dialog traces to isolate the active15–30%of tables,Z*includes, andsp_*code branches actually executed in current fiscal periods. - Step 2 — Static Control-Flow Slicing (
ASTLineage): Parse activeABAP,TROIA,Delphi, andT-SQLunits into pure read/calculation lineage graphs (#temptable DAGs) separated cleanly from lock-acquiring state mutations. - Step 3 — Shadow Reconciliation Gate (
0.00Penny Parity): Execute compiled ontology SQL views side-by-side against legacyZ*/sp_*baseline outputs across12closed fiscal months; block promotion until row counts and net/VAT totals match to0.00. - Step 4 —
STA / COM&BAPIWorker Queue Isolation: Isolate single-threadedDelphi COM(Logo Objects,NetOpenX), statefulTROIAsessions, andSAP RFC/BAPIcommits behind dedicated, idempotency-keyed worker queues so async AI agent servers never triggerRPC_E_WRONG_THREADcrashes or orphaned ERP sessions.
-- Verify 0.00 penny drift between legacy sp_CustomerNetRevenue_v4 and compiled Ontology metric view
WITH legacy_sp_snapshot AS (
SELECT
fiscal_period,
customer_code,
CAST(net_invoiced_try AS NUMERIC(18,2)) AS legacy_net_try,
CAST(vat_allocated_try AS NUMERIC(18,2)) AS legacy_vat_try
FROM audit_staging.legacy_sp_monthly_revenue_baseline
WHERE fiscal_period BETWEEN '2026-01' AND '2026-11'
),
ontology_compiled AS (
SELECT
fiscal_period,
customer_code,
CAST(SUM(line_net_after_header_discount_try) AS NUMERIC(18,2)) AS onto_net_try,
CAST(SUM(line_vat_with_penny_alloc_try) AS NUMERIC(18,2)) AS onto_vat_try
FROM ontology_metrics.v_verified_wholesale_invoice_lines
WHERE fiscal_period BETWEEN '2026-01' AND '2026-11'
GROUP BY fiscal_period, customer_code
)
SELECT
COALESCE(l.fiscal_period, o.fiscal_period) AS fiscal_period,
COALESCE(l.customer_code, o.customer_code) AS customer_code,
l.legacy_net_try,
o.onto_net_try,
(COALESCE(o.onto_net_try, 0) - COALESCE(l.legacy_net_try, 0)) AS net_penny_drift,
(COALESCE(o.onto_vat_try, 0) - COALESCE(l.legacy_vat_try, 0)) AS vat_penny_drift
FROM legacy_sp_snapshot l
FULL OUTER JOIN ontology_compiled o
ON o.fiscal_period = l.fiscal_period
AND o.customer_code = l.customer_code
WHERE COALESCE(o.onto_net_try, 0) <> COALESCE(l.legacy_net_try, 0)
OR COALESCE(o.onto_vat_try, 0) <> COALESCE(l.legacy_vat_try, 0);
-- CI Release Gate: Any non-zero row count fails ontology deployment immediately.Frequently Asked Technical Questions
Why not fine-tune an open-weight LLM on our internal ABAP, Canias TROIA, and T-SQL repositories instead?
Fine-tuning teaches a model surface syntax style, not deterministic runtime truth. It cannot guarantee which Z* enhancement is active for a specific company code (BUKRS), enforce pessimistic lock ordering, or prevent a 1% token-sampling error on a tax-rounding loop. Business rules belong in deterministic, version-controlled ontology contracts—not probabilistic model weights.
Why do Delphi COM wrappers like Logo Objects and NetOpenX deadlock or crash when called from async Node.js or Python agent servers?
Win32 COM ERP libraries almost universally require Single-Threaded Apartment (STA) execution with thread-affine message pumps and heavy in-memory session state. Dispatching concurrent async calls from a multi-threaded web worker corrupts COM reference counts, throws RPC_E_WRONG_THREAD exceptions, and leaks zombie ERP processes. Always isolate STA/COM adapters inside single-threaded, timeout-guarded queue workers behind the ontology action gateway.
How do you extract clean ontology SQL from a 6,000-line T-SQL stored procedure chained across 15 #temp tables and cursors?
Rather than translating line-by-line imperatively, parse the procedure with TSqlParser to build the #temp table data-lineage DAG. Most legacy cursors exist only to compute running balances or distribute header discounts/pennies written prior to modern SQL window functions. Replace read-side staging pipelines with set-based window functions (SUM() OVER, ROW_NUMBER()), prove 0.00 penny equivalence via shadow reconciliation, and leave the transactional write procedure untouched behind the kinetic action wrapper.
How do we prevent ontology drift when ERP consultants deploy an emergency ABAP transport or alter a production stored procedure?
Pair versioned ontology contracts with two automated drift guards: (1) DDL triggers and SAP transport hooks hash upstream sp_* / Z* source objects (SHA-256) and flag mapped ontology entities DRIFT_REVIEW_REQUIRED whenever code changes, and (2) nightly shadow reconciliation jobs diff legacy report totals against ontology views before the morning shift begins.
Glossary Concepts Referenced in This Guide
FOREIGN KEY constraints—common across mature ERP and manufacturing databases.ORDER_LINES and PAYMENTS) in one flat SQL query, multiplying totals silently.UPDATE/INSERT statements on ERP/CRM databases, requiring typed action proposals validated against preconditions and approved by a named human role.Free to reference in engineering docs, ADRs, articles, and course syllabi with attribution.
[AI Modernization on Legacy ERP Languages: ABAP, TROIA, Delphi & Stored Procedures — Ontoloji.org](https://ontoloji.org/en/guides/legacy-erp-languages-ai-abap-troia-delphi-and-stored-procedures)