ontoloji.orgOpen Reference Hub
ERP & SQL Ontology13 min read·Updated: 2026-12-05·Türkçe sürüm →

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.

Executive Summary — Key Takeaways
  • 01Frontier LLMs trained overwhelmingly on public Python and TypeScript corpora 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 & NetOpenX COM/STA wrappers), and 3,000–8,000 line T-SQL / PL/SQL stored 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 AST parsing 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, TROIA services).

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, BAPI Wrappers & Implicit Enhancements): Real SAP business rules hide inside ENHANCEMENT-POINT hooks, legacy internal tables WITH HEADER LINE, CONVERSION_EXIT_ALPHA_INPUT zero-padding routines, stateful SY-SUBRC return-code mutations, and strict ENQUEUE_E_* -> BAPI_* -> BAPI_TRANSACTION_COMMIT Logical Unit of Work (LUW) sequences that LLMs routinely drop or reorder.
  • Canias ERP TROIA (Proprietary 4GL Dialog & Table State Scripts): TROIA has virtually zero public training footprint. Its execution model mutates in-memory UI grid controls, session globals, and IAS* composite-key tables inside BEFORE / AFTER dialog triggers. Prompted to translate or generate TROIA, 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 in Delphi, invoking Win32 COM Single-Threaded Apartment (STA) wrappers such as Logo Objects (UnityObjects.UnityApplication) and Netsis NetOpenX, alongside business validation buried in TDataSet.BeforePost / OnCalcFields events and embedded Firebird PSQL triggers.
  • 3,000–8,000 Line T-SQL & PL/SQL Stored Procedures (sp_*): Decades of consultant patches accumulate into monolithic procedures driven by nested cursors, session-scoped #temp table state machines, @@TRANCOUNT savepoint gymnastics, dynamic sp_executesql strings, and cascading AFTER UPDATE triggers. 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.

Four Enterprise Invariants Destroyed by Naive AI "Rip-and-Rewrite" Code Translation
Enterprise Invariant ClassLegacy ERP / SQL MechanismNaive AI Microservice RewriteFinancial & Statutory Blast Radius
Implicit Lock-Ordering & ConcurrencyDeterministic lock acquisition order (UPDLOCK, HOLDLOCK, SELECT FOR UPDATE, SAP ENQUEUE)Async ORM calls (await Promise.all) with optimistic app-layer checksNegative warehouse inventory, double-allocated ATP stock lots, and production deadlock storms
Rounding & VAT Penny-Allocation LoopsCursor loop allocating 0.01 header-vs-line tax/FX rounding residuals onto the largest invoice lineIndependent per-line Math.round() or IEEE-754 floating-point mathGovernment e-Invoice (UBL / e-Fatura) XML checksum rejection and subledger-to-GL penny drift
Undocumented Tax & Export Branch FlagsLine 4,720 IF branches for customs export regimes, free-zone VAT exemptions, or cumulative withholding (Tevkifat) thresholdsModel summarizes or drops "edge-case" branches during context-window compressionIllegal tax calculation on export/withholding invoices and severe statutory audit penalties
Cascading Triggers & Side-Effect LedgersAFTER INSERT/UPDATE triggers populating cost-accounting journals, lot genealogy, and EDI outboxesHalf 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
Core Modernization Principle: Never Let an LLM Rewrite a Proven Tax & Lock Kernel

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 ALPHA document keys, Canias IAS* composite CLIENT + COMPANY + BUSAREA keys, and polymorphic LOGICALREF links in Logo / Netsis are extracted once from legacy code and enforced automatically by the ontology compiler.
  • Lifting Magic Constants into Status Dictionaries: Delphi .pas constants (const stShippable = 4) and buried T-SQL predicates (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 BAPI or COM transactions.
Declarative Ontology Contract: Lifting Hidden T-SQL / Delphi / ABAP Credit & Status Rules While Routing Writes to the Official ERP Kernel
// 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 active 15–30% of tables, Z* includes, and sp_* code branches actually executed in current fiscal periods.
  • Step 2 — Static Control-Flow Slicing (AST Lineage): Parse active ABAP, TROIA, Delphi, and T-SQL units into pure read/calculation lineage graphs (#temp table DAGs) separated cleanly from lock-acquiring state mutations.
  • Step 3 — Shadow Reconciliation Gate (0.00 Penny Parity): Execute compiled ontology SQL views side-by-side against legacy Z* / sp_* baseline outputs across 12 closed fiscal months; block promotion until row counts and net/VAT totals match to 0.00.
  • Step 4 — STA / COM & BAPI Worker Queue Isolation: Isolate single-threaded Delphi COM (Logo Objects, NetOpenX), stateful TROIA sessions, and SAP RFC/BAPI commits behind dedicated, idempotency-keyed worker queues so async AI agent servers never trigger RPC_E_WRONG_THREAD crashes or orphaned ERP sessions.
SQL: Automated CI Shadow Reconciliation Gate Verifying 0.00-Penny Parity Against Legacy Stored Procedures
-- 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

Open License (CC BY 4.0) · Cite This Page

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)

More Guides in This Series

Core Architecture
How AI Uses an Ontology
9 min read
Agent Engineering
Agent Harness vs. Ontology
8 min read
Data Engineering
ERP, CRM & MES Patterns
10 min read
Strategy & Governance
30-Day Ontology Strategy
7 min read
ERP Integration
ERP Ontology Integration Guide
11 min read
ERP Data Engineering
Logo Tiger, Nebim V3 & Turkish Unicode Traps
14 min read
Agent Governance
Adversarial Verification, Permissions & Compaction
13 min read
Verification Engineering
Absence-Aware Gates & Ratio Reconstruction
13 min read
Provenance & Governance
Draft vs. Normative Provenance Hygiene
12 min read
SAP & Protocol Architecture
SAP BTP, Cloud Connector & ORD Ontology
11 min read
ERP Write-Safety
Logo REST, Nebim Integrator & UBL-TR Safety
12 min read
Platform Architecture Comparison
Cortex, Genie, dbt & Cube vs. Ontology
12 min read
Systems Engineering & Forensics
ERP Integrator Anti-Patterns & Forensics
13 min read
Platform Architecture Comparison
Fabric IQ, D365 MCP & SAP Joule vs. Ontology
12 min read
Retrieval & RAG Architecture
PageIndex Vectorless Tree RAG vs. Vector DBs
11 min read
Platform Architecture Comparison
Atlan, Stardog & Neo4j vs. Ontology
12 min read
Statutory & Financial Governance
GİB UBL-TR, VUK/TMS 29 & KVKK Ontology
13 min read
Agent Memory & Ontology Architecture
Cognee & Zep Graphiti vs. Ontology
11 min read
Protocol & Multi-Agent Architecture
MCP vs. OpenAPI & Specialist Agents
12 min read
Protocols & Standards
MCP 2026-07-28: Tasks, Events & Apps
13 min read
Agent Architecture & Governance
Agent Harness Engineering Rubric
12 min read
Agent Architecture & Governance
Multi-Agent Task Boards & Mailboxes
12 min read
Verification & Security
Generate-Evaluate-Repair & Observers
12 min read
Verification & Security
NSA MCP Security & CIMD vs. DCR
13 min read
Agent Architecture & Governance
OpenTelemetry for AI Agents & MCP
11 min read
Agent Architecture & Governance
MCP Gateway vs. Enterprise AI Ontology
12 min read
MCP & Agent Security
MCP Apps Nonces, Elicitation & Refusal Traps
13 min read
ERP & SQL Ontology
Logo Tiger STLINE, Karmakoli & UINFO1 SQL Traps
14 min read
Manufacturing, MES & OEE Ontology
TRUMPF OPC UA & Siemens Energy SQL OEE Fix
13 min read
MCP & Agent Architecture
Claude Mobile, Desktop & OpenWebUI MCP Bugs
13 min read
MCP & Agent Security
Enterprise MCP Gateway & RFC 8693 Security
14 min read
Core Ontology Specification
Operational Ontology: Action Types, Links & Interfaces
15 min read