# RFC and BAPI in depth: delivery guarantees, commits, security and their future

> Choose the right RFC variant, commit BAPI work correctly, secure RFC connections, and plan which RFC interfaces to keep, wrap or replace.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/rfc-and-bapi-in-depth/
- Updated: 2026-11-30
- Reading time: Foundational 9 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

A **remote function call (RFC)** is how one SAP system asks another system to run a function and, usually, hand back a result. A **BAPI** is a business-level function, such as "create a purchase order", that SAP built to be called that way. Together they connect SAP systems to each other, and to plant systems, spreadsheets and data warehouses, in most SAP landscapes that run ECC or S/4HANA on premise or in a private cloud.

RFC comes in several flavors. Some wait for the answer and promise to run the request **at most once**. Others store the request first and promise to run it **exactly once**, and some of those also keep requests **in order**. SAP says so plainly on its help pages for each variant ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/99b53cee2b73e7e10000000a42189b/content.htm)). Picking the wrong flavor is how a shipment gets booked twice or a status update lands out of order.

A BAPI never saves its own work. The calling program decides when to save, and must check the messages that come back first ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/4d/5b102ba1483d8fe10000000a42189e/content.htm)). Forgetting that is the most common reason an "integration that works" loses data.

SAP's clean core rules still accept BAPIs as "classic APIs", but released APIs are SAP's direction for new work, and SAP's API policy now sets rules for what may be called and by whom. The decision for a leader: **keep a register of every RFC connection, with an owner, a delivery guarantee and a plan**, and fund the move of the risky ones to released APIs.

This topic uses the course's fictional company, **Calder Pumpworks**, with its S/4HANA system for `CP10` and the ECC system that `CP20` in Augsburg still runs until July 2027.

### Why it matters to the business

RFC connections are often invisible. They were built by a project years ago, run under a technical user nobody reviews, and only show up when something breaks.

What is at stake, using Calder (all numbers are course values):

- **Wrong quantities.** Augsburg reports impeller shipments to Rockford by RFC. If a reply is lost and Augsburg's program simply calls again, Rockford can record 60 impellers in transit when 40 left the plant. Planning then trusts stock that doesn't exist.
- **Lost changes.** A planner's spreadsheet creates purchase orders through a BAPI. If the spreadsheet never sends the commit, or commits without reading the error messages, some orders exist and some don't, and the planner believes all of them were created.
- **Security exposure.** A technical user with permission to call every remote function can read or change far more than the interface needs. An RFC callback without an allowlist lets the called system run functions back in yours.
- **Policy and upgrade risk.** Custom functions that read SAP tables directly are the hardest code to keep through upgrades. SAP's API policy now ties what you may call to published APIs, with stricter rules for AI agents and bulk extraction ([SAP API Policy](https://help.sap.com/doc/sap-api-policy/latest/en-US/API_Policy_latest.pdf)).

The cost of getting this right is mostly review time: a few days to list and rate the connections, then fixes spread over the next releases.

### How SAP does it

As of November 2026, SAP offers these pieces around RFC and BAPIs:

- **RFC variants in every ABAP system**: synchronous (sRFC), asynchronous (aRFC), and background variants. SAP names **background RFC (bgRFC)** the successor of transactional (tRFC) and queued RFC (qRFC) and recommends it ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/99b53cee2b73e7e10000000a42189b/content.htm)).
- **BAPIs**, documented as interfaces of SAP business object types, with fixed programming rules: no commit inside, messages returned in a return parameter ([SAP Help Portal](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/4f424ab3ee468de10000000a42189c/content.htm)).
- **Security controls**: authorization object `S_RFC` per function group, **Unified Connectivity (UCON)**, which blocks any remote function not on an allowed list ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/c0/51e93edb9344bb92c986bd9666aecd/content.htm)), and an allowlist for callbacks ([SAP Community](https://community.sap.com/t5/additional-blog-posts-by-sap/rfc-callback-whitelist/ba-p/13227084)).
- **Cloud paths**: the SAP BTP ABAP environment can call an on-premise function through the Cloud Connector and a communication arrangement ([SAP Developers](https://developers.sap.com/tutorials/abap-env-rfc.html)). SAP Integration Suite can call RFC as a receiver; the [Cloud Integration flows topic](https://erpfde.com/topics/cloud-integration-flows-in-depth/) covers flow design.
- **Clean core rating**: SAP's levels A to D put BAPIs at **level B, "classic APIs"**: upgrade-safe in practice but without a formal stability contract. Custom functions that read internal objects sit at level C ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-extensibility-model-best-practices_e290f382-800e-40ef-a203-85a13115f487)).

### A decision guide: what to do with each RFC connection

| Situation | What to do | Why |
| --- | --- | --- |
| A read that a person or program waits for | Keep synchronous RFC; set timeouts and a narrow user | At most once is fine for a read; a retry does no harm |
| A write that must happen once (postings, quantities) | Background RFC, transactional | The request is stored with an ID, so a resend can't post twice |
| Several updates to the same object that must arrive in order | Background RFC, queued, one queue per object | Transactional units may run in any order |
| An existing tRFC or qRFC interface that works | Keep it; move to bgRFC when you change it | SAP recommends bgRFC for new applications; switching back isn't supported |
| A BAPI call from outside SAP | Keep, with commit and message handling reviewed | Level B is acceptable; the risk is in the caller |
| A custom function reading SAP tables | Plan a replacement by a released API | Level C: breaks on upgrades and sits outside the published API list |
| ODP over RFC into a non-SAP tool | Replace with an endorsed extraction path | The course's [API policy page](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) explains why |
| A connection to ECC that retires with a migration | Fix only what is unsafe; plan the switch-off | Don't rebuild what will stop in months |

> **Note** **For functional consultants.** RFC changes your test cases more than your configuration. Test what happens when the other side is down, when the same message arrives twice, and when one item in a batch fails: the business result must be either all saved or clearly reported as not saved. Ask who owns each technical user and which function groups it may call.

### Questions to ask

- Do we have a list of every RFC destination and every external caller, with an owner for each?
- Which interfaces write data, and which delivery guarantee does each use? Can any of them post twice after a timeout?
- Where does order matter (statuses, prices, corrections), and is it protected by queues?
- For every BAPI caller: does it read the returned messages and commit or roll back the whole unit?
- Do technical users have `S_RFC` limited to named function groups, or a wildcard?
- Is UCON active, and are RFC callbacks restricted by allowlists?
- Which connections use custom functions that read SAP tables, and what is the plan to replace them?
- Are any data loads into non-SAP tools running over ODP and RFC?

### Common misconceptions

- **"RFC is obsolete."** SAP's help pages still recommend background RFC for new background communication, and its clean core rules accept BAPIs as classic APIs. What changes is where new interfaces into S/4HANA should go: released APIs first.
- **"If the call returned without an error, the data is saved."** For a BAPI, nothing is saved until the caller commits. For a synchronous call, a lost reply leaves the caller unsure whether the work happened.
- **"Retrying a failed synchronous call is safe."** Only for reads or functions designed to be repeated. For a posting, a retry can create a duplicate.
- **"Transactional RFC keeps the order."** It guarantees once, not order. Order needs a queued variant.
- **"A technical user is safe because nobody logs on with it."** Its authorizations decide what any caller with its credentials can do.

### Key terms

- **RFC (remote function call):** SAP's protocol for calling a function module in another system.
- **Remote-enabled function module:** a function module marked so it can be called by RFC.
- **BAPI:** a remote-enabled function that implements a method of an SAP business object, with fixed rules for messages and commits.
- **sRFC:** synchronous RFC; the caller waits; at most once.
- **bgRFC:** background RFC; the call is stored first and runs exactly once, either in any order (type T) or in order (type Q).
- **tRFC and qRFC:** the older transactional and queued variants that bgRFC succeeds.
- **LUW (logical unit of work):** a set of changes that are saved together or not at all.
- **RFC destination:** the stored connection settings for a target system, maintained in transaction `SM59` in ABAP systems.
- **UCON (Unified Connectivity):** a framework that blocks external calls to any remote function not assigned to an allowed list.
- **RFC callback:** a call from the called system back into the caller during a synchronous RFC.

### Check yourself

1. Augsburg reports shipments to Rockford by synchronous RFC and resends on timeout. What can go wrong?
   - A. The shipments arrive in Rockford a day later than they left Augsburg
   - B. A lost reply leads to a resend, so a shipment can be booked twice
   - C. Rockford can only read the data, so the shipments aren't saved
   - D. The resend is blocked by Rockford until someone approves it

   Answer: B. Synchronous RFC runs a call at most once and stores nothing first. If the reply is lost after Rockford saved the data, a resend books it again. A background RFC unit carries an ID, so a resend is recognized.

2. Which RFC flavor does SAP recommend for new background interfaces?
   - A. Transactional RFC, because it stores each call in the database
   - B. Queued RFC, because it keeps every call in the order sent
   - C. Background RFC, the successor of transactional and queued RFC
   - D. Asynchronous RFC, because the caller never waits for a reply

   Answer: C. SAP's help pages call bgRFC the successor of tRFC and qRFC and recommend it for new applications. Existing tRFC and qRFC interfaces can stay until they are changed.

3. A spreadsheet creates purchase orders through a BAPI. What must its owner confirm?
   - A. That the BAPI saves each order as soon as it is called
   - B. That the spreadsheet runs under a planner's own user name
   - C. That the orders are created one per day to avoid locks
   - D. That it reads the returned messages, then commits or rolls back

   Answer: D. A BAPI never saves its own work; the caller ends the unit with a commit or a rollback. Committing without reading the messages can save half the orders while the planner believes all of them exist.

4. Status updates for one delivery must arrive in the order they were sent. What protects that?
   - A. Any transactional variant, because each call runs exactly once
   - B. A queued variant, with one queue for each delivery
   - C. A synchronous call, because the caller waits for each reply
   - D. A larger timeout on the RFC destination in the target system

   Answer: B. Transactional units run once but in no guaranteed order. Queued units run once and in the order they were created, so one queue per delivery keeps its statuses in sequence.

5. Where do BAPIs sit in SAP's clean core levels A to D?
   - A. Level A, because SAP has released every BAPI for cloud use
   - B. Level B, classic APIs without a formal stability contract
   - C. Level C, because they are internal objects of the application
   - D. Level D, because SAP no longer recommends calling them at all

   Answer: B. SAP's clean core lesson calls BAPIs and wrappers around them classic APIs at level B: upgrade-safe in practice but not formally released. Custom functions reading internal objects sit at level C.

6. What does Unified Connectivity (UCON) do for RFC?
   - A. It encrypts every RFC connection between two SAP systems
   - B. It replaces the authorization checks that technical users need
   - C. It blocks external calls to remote functions not on an allowed list
   - D. It turns every RFC interface into a released OData service

   Answer: C. With UCON, a remote function can be called from outside only if it is assigned to a communication assembly. Authorization checks are still needed on top; encryption is a separate setting.

7. Calder's warehouse loads sales data nightly by ODP over RFC. What is the right next step?
   - A. Keep it, because RFC is supported in private cloud systems
   - B. Move it to background RFC so that each record arrives once
   - C. Give the load user a wildcard so it never fails on new data
   - D. Plan a move to an extraction path SAP endorses, with a date

   Answer: D. SAP's API policy restricts large-scale extraction to SAP-endorsed paths, and the course's API policy page reports ODP over RFC as unpermitted for non-SAP tools. Changing the RFC variant doesn't change that; a planned replacement does.

## Deep layer

### Mental model

Every RFC interface answers three questions, and most incidents come from answering one of them by accident:

1. **How many times can this run?** At most once (synchronous, asynchronous) or exactly once (stored first, with an ID). A write that must happen once needs the second.
2. **In what order?** Any order (transactional) or creation order (queued). Updates to the same object that overwrite each other need the second.
3. **When is it saved?** A BAPI registers changes; nothing reaches the database until the caller commits. The caller owns the unit of work.

Then two governance questions: **who may call what** (`S_RFC`, UCON, callback allowlists, SNC), and **how long should this exist** (level B is acceptable, level C and ODP over RFC need a replacement plan).

### How it works

#### The variants and their guarantees

SAP's help page for RFC variants lists the ABAP statement and the service property of each ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/99b53cee2b73e7e10000000a42189b/content.htm)):

| Variant | ABAP statement | Guarantee | Stored first | Typical use |
| --- | --- | --- | --- | --- |
| sRFC | `CALL FUNCTION ... DESTINATION` | At most once | No | Reads, checks, BAPI calls where the caller waits |
| aRFC | `CALL FUNCTION ... STARTING NEW TASK` | At most once | No | Parallel work; target must be up |
| tRFC | `CALL FUNCTION ... IN BACKGROUND TASK AS SEPARATE UNIT` | Exactly once | Yes, under a transaction ID (TID) | Predecessor of bgRFC type T |
| qRFC | tRFC plus `TRFC_SET_QUEUE_NAME` | Exactly once, in order | Yes | Predecessor of bgRFC type Q |
| bgRFC type T | `CALL FUNCTION ... IN BACKGROUND UNIT` | Exactly once, any order | Yes, as a unit with a unique ID | Writes that must not duplicate |
| bgRFC type Q | same, with a queue | Exactly once, in creation order | Yes | Updates whose order matters |

The page adds three facts architects need: tRFC and bgRFC can't be used in parallel, SAP recommends bgRFC for its performance, and the data of sRFC and aRFC is not written to the database before the call. The bgRFC page adds that bgRFC can't be combined with tRFC and qRFC within one destination, that a unit is transferred whole or waits, that placing a call in several queues acts like a lock which can stop queue processing if misused, and that changing back from bgRFC to qRFC is not supported ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/927c2caa6b17cee10000000a421937/content.htm)). SAP's overview of background communication says it "strongly recommends" not using qRFC or tRFC in new applications ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/96e29a0eec3987e10000000a421937/content.htm)).

```mermaid
sequenceDiagram
  participant A as Augsburg ECP
  participant Q as bgRFC unit store
  participant R as Rockford S4P
  A->>Q: record unit with ID, at COMMIT WORK
  Q->>R: send unit
  R-->>R: run calls, save, note unit ID
  R--xQ: confirmation lost
  Q->>R: send unit again
  R-->>Q: unit ID known, ignored
```

#### Commit handling and the BAPI transaction model

SAP's BAPI rules are short and strict ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/4d/5b102ba1483d8fe10000000a42189e/content.htm), [SAP Help Portal](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/4f424ab3ee468de10000000a42189c/content.htm)):

- A BAPI doesn't run `COMMIT WORK` itself. The caller combines one or more BAPIs into a logical unit of work and ends it with `BAPI_TRANSACTION_COMMIT` or `BAPI_TRANSACTION_ROLLBACK`.
- BAPIs change the database only through the update task, because an RFC ends with an implicit database commit. Changes registered for the update task run only when the caller commits.
- Errors don't come back as exceptions. They come back in the BAPI's return parameter. Messages of type A (termination) may only be returned there, and E and A messages are never shown on a screen.
- In one unit of work, a read BAPI sees changes from a write BAPI only after the commit, and two write accesses to the same object instance are not allowed.
- A BAPI checks authorizations itself and produces no screen output.

For a caller this means: keep one session open for the unit, read every return parameter, then commit if none holds an E or A message and roll back otherwise. If the session ends without a commit, the registered changes are lost.

#### Destinations, monitoring and where stuck calls wait

In an ABAP system, outbound destinations live in transaction `SM59`; bgRFC inbound destinations are kept in `SBGRFCCONF` ([SAP Support Portal](https://support.sap.com/en/alm/sap-focused-run/expert-portal/integration-cloud-monitoring/bgrfc.html)). Where to look when calls don't arrive ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/8b/ceea3b31aac554e10000000a114084/content.htm), [SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/927c5caa6b17cee10000000a421937/content.htm)):

| Variant | Monitor | What you see |
| --- | --- | --- |
| tRFC | `SM58` | Only calls that failed or were scheduled as batch jobs. `CPICERR` (connection problem, retried per the `SM59` settings), `SYSFAIL` (usually a program error, handled one by one) |
| qRFC | `SMQ1` outbound, `SMQ2` inbound; `SMQR`, `SMQS` schedulers | Queues and their status; qRFC units are not shown in `SM58` ([SAP Support Portal](https://support.sap.com/en/alm/sap-focused-run/expert-portal/integration-cloud-monitoring/qrfc.html)) |
| bgRFC | `SBGRFCMON` (needs authorization object `S_BGRFC`) | Units from recording to processing, by inbound or outbound, transactional or queued; lock, unlock or delete units and queues |

An empty monitor is good news only if the interface runs on that variant. A synchronous call that fails leaves nothing in any of these monitors: the caller has to log it.

#### Security

Four controls, from SAP's pages:

- **`S_RFC`** checks whether the user in the call may run function modules of a given function group (field `RFC_TYPE` value `FUGR`, activity `16`). tRFC and qRFC between SAP systems also need the technical groups `ERFC` and `ARFC` ([SAP Help Portal](https://help.sap.com/saphelp_em92/helpdata/en/48/8d1bd1ae444e6ee10000000a421937/content.htm), [SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/de/48/95128d94cc73eae10000000a42189b/content.htm)). A wildcard is the classic finding.
- **UCON's RFC basic scenario.** A remote-enabled function module can be called from outside only if it is assigned to a communication assembly linked to a virtual host; everything else is blocked whatever the user's authorizations. You set it up in transaction `UCONCOCKPIT` per client ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/c0/51e93edb9344bb92c986bd9666aecd/content.htm), [SAP Help Portal](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/10/d691aafa5e4cc0bb391ba3962280f9/content.htm)).
- **Callback allowlist.** During a synchronous call, the called system can call back into the caller with `DESTINATION 'BACK'`. Since SAP Basis 7.40 each `SM59` destination has a callback allowlist under *Logon & Security*. Profile parameter `rfc/callback_security_method` decides how strictly allowlists apply: `0` ignores them, `1` (default) rejects only what active allowlists forbid, `2` logs, `3` rejects what active or inactive allowlists forbid ([SAP Community](https://community.sap.com/t5/additional-blog-posts-by-sap/rfc-callback-whitelist/ba-p/13227084)).
- **Encryption** with Secure Network Communications (SNC) on the destination; UCON can keep a separate communication assembly for calls that must use SNC.

#### RFC in the cloud

- **SAP BTP ABAP environment to on-premise.** SAP's tutorial calls `RFC_GET_SYSTEM_INFO` in an on-premise system: the Cloud Connector exposes the function as a resource, a customer-managed communication scenario holds an outbound service of type *RFC Service*, a communication system points to the Cloud Connector, and the code gets the destination from the communication arrangement with `cl_rfc_destination_provider=>create_by_comm_arrangement` before `CALL FUNCTION ... DESTINATION`. Classic structures such as `rfcsi` are not released there, so the tutorial defines its own types ([SAP Developers](https://developers.sap.com/tutorials/abap-env-rfc.html)).
- **WebSocket RFC.** SAP's blog post describes RFC over WebSocket from the ABAP platform of SAP S/4HANA 1909: TLS always, a destination of type `W` in `SM59`, UCON protection mandatory, no callbacks, and no Cloud Connector support at the time of writing ([SAP Community](https://community.sap.com/t5/technology-blog-posts-by-sap/websocket-rfc-rfc-for-the-internet/ba-p/13502531)). Check its current scope before designing on it.
- **Clean core.** BAPIs are level B, classic APIs; SAP's lesson says these are exposed for customer use in SAP S/4HANA on-premise and SAP ERP, and that level A (released APIs) aligns with the Public Edition approach ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-extensibility-model-best-practices_e290f382-800e-40ef-a203-85a13115f487)). Confirm for your edition which classic APIs you may use.
- **Policy.** SAP's API Policy defines published APIs as those on the SAP Business Accelerator Hub or in product documentation, permits custom ABAP interfaces in private cloud and on-premise as an example of documented use, and restricts AI systems that plan sequences of calls and large-scale extraction to SAP-endorsed architectures ([SAP API Policy](https://help.sap.com/doc/sap-api-policy/latest/en-US/API_Policy_latest.pdf)).

### Build it yourself: review Calder's RFC connections

You will run a small lab with two parts. **Review** checks Calder's register of RFC connections against ten course rules and gives each connection a verdict. **Simulate** shows, with a stand-in system, why the rules exist: a retry that doubles a quantity, units that run out of order, BAPI work that is lost or half saved, and a callback that runs code it shouldn't.

```mermaid
flowchart LR
  I[--init] --> D[register_draft.json]
  I --> V[register_reviewed.json]
  D --> R[review: rules RF01-RF10]
  V --> R
  R --> OUT[verdict per connection:<br/>FIX, KEEP, REPLACE, RETIRE]
  S[simulate retry, order,<br/>commit, callback] --> W[why the rules exist]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). This walkthrough needs none of the setup's trials.

> **Note** New words. **JSON** is a text format for structured data. A **register** is a list of every RFC connection with the facts the rules need; the file layout is the course's, not an SAP format. A **stand-in** is a few lines of Python that imitate the rules SAP documents; it is not SAP software. **Exit code** is the number a program returns; `2` here means at least one rule failed, which a pipeline can use to block a change.

> **Warning** The rule IDs `RF01` to `RF10`, the `Z` function names, users and values are course labels. The rules follow SAP's documented guarantees and controls, plus course choices marked as such in the table in Step 4.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`, from the setup topic.
- No account, no network and no extra libraries. The script uses built-in modules only and has no randomness, so your output matches the samples exactly.
- About 40 minutes. Everything is free.

#### Step 1: Open the course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Create the unit folder if it doesn't exist yet:

   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit26
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit26
     ```

#### Step 2: Create the script

1. In VS Code, create a new file `unit26/rfc_lab.py`.
2. Paste the code below and save.

```python
"""Review RFC connections and see RFC delivery and commit rules at work.

Course lab for Unit 26, "RFC and BAPI in depth". Built-in modules only,
no randomness, no network, no SAP system.

  python unit26/rfc_lab.py --init              write the sample registers
  python unit26/rfc_lab.py review              review unit26/rfc/register_draft.json
  python unit26/rfc_lab.py review --file unit26/rfc/register_reviewed.json
  python unit26/rfc_lab.py simulate retry      sRFC retry versus bgRFC unit
  python unit26/rfc_lab.py simulate order      transactional versus queued units
  python unit26/rfc_lab.py simulate commit     BAPI calls and the caller's commit
  python unit26/rfc_lab.py simulate callback   RFC callback and the allowlist
  python unit26/rfc_lab.py --self-test         check the built-in samples

The stand-in "systems" below only imitate the rules SAP documents for RFC
variants and the BAPI transaction model. They are not SAP software. Rule
IDs, function module names starting with Z, users and values are course
labels for the fictional Calder Pumpworks.
"""

import argparse
import copy
import json
import sys
from pathlib import Path

FOLDER = Path("unit26/rfc")
AS_OF = "2026-11-30"
ROLLOUT = "2027-07-05"  # CP20 goes live in CP10's S/4HANA (course date)

AT_MOST_ONCE = {"sRFC", "aRFC"}
EXACTLY_ONCE = {"tRFC", "qRFC", "bgRFC-T", "bgRFC-Q"}
QUEUED = {"qRFC", "bgRFC-Q"}
LEGACY = {"tRFC", "qRFC"}

SYSTEMS = {
    "S4P": {"kind": "S/4HANA Cloud Private Edition (CP10)", "ucon_rfc": False,
            "callback_security_method": 1},
    "ECP": {"kind": "ECC 6.0 EhP 8 (CP20)", "ucon_rfc": False,
            "callback_security_method": 1},
}

DRAFT = [
    {"id": "C01", "interface": "I02", "name": "MES Rockford reads released production orders",
     "caller": "MES-RK", "target": "S4P", "function": "Z_MES_GET_ORDERS", "access": "read",
     "transport": "sRFC", "user": "TU_MES_RFC", "user_type": "technical", "s_rfc": ["*"],
     "network": "cross", "snc": False, "code_level": "C", "plan": None, "owner": "00100314"},
    {"id": "C02", "interface": "-", "name": "Augsburg posts impeller shipments to Rockford",
     "caller": "ECP", "target": "S4P", "function": "Z_IC_SHIP_STATUS", "access": "write",
     "must_once": True, "order_sensitive": True, "transport": "sRFC", "retry_on_timeout": True,
     "user": "TU_IC_RFC", "user_type": "technical", "s_rfc": ["ZIC"], "network": "cross",
     "snc": True, "code_level": "custom", "plan": None, "owner": "00100292"},
    {"id": "C03", "interface": "W06", "name": "Test certificate archive reads Augsburg's archive",
     "caller": "calder-ext-prod", "target": "ECP", "function": "Z_CERT_ARCHIVE_READ",
     "access": "read", "transport": "sRFC", "destination": "ECC_CERT_ARCHIVE",
     "user": "TU_CERT_RFC", "user_type": "technical", "s_rfc": ["ZCERT"], "network": "cloud",
     "snc": True, "code_level": "custom", "plan": None, "owner": None},
    {"id": "C04", "interface": "-", "name": "Planner's spreadsheet creates purchase orders",
     "caller": "PC-00100153", "target": "S4P", "function": "BAPI_PO_CREATE1", "access": "write",
     "must_once": True, "bapi": True, "commit_checked": False, "transport": "sRFC",
     "user": "00100153", "user_type": "personal", "s_rfc": ["*"], "network": "cross",
     "snc": False, "code_level": "B", "plan": None, "owner": "00100153"},
    {"id": "C05", "interface": "I07", "name": "Data warehouse extracts sales data by ODP over RFC",
     "caller": "DW", "target": "S4P", "function": "ODP over RFC", "access": "extract",
     "transport": "RFC", "user": "TU_DW_ODP", "user_type": "technical", "s_rfc": ["*"],
     "network": "cross", "snc": True, "code_level": "odp-rfc", "plan": None, "owner": "00100280"},
    {"id": "C06", "interface": "I02", "name": "S/4HANA pushes released orders to the MES",
     "caller": "S4P", "target": "MES-RK", "function": "MES_ORDER_IN", "access": "write",
     "transport": "sRFC", "callback": True, "callback_allowlist": [], "user": "-",
     "user_type": "technical", "s_rfc": [], "network": "cross", "snc": False,
     "code_level": "custom", "plan": None, "owner": "00100314"},
]


def reviewed_register():
    reg = copy.deepcopy(DRAFT)
    by = {c["id"]: c for c in reg}
    by["C01"].update(s_rfc=["ZMES"], snc=True,
                     plan={"action": "REPLACE", "by": "2027-06-30",
                           "with": "a released production order API from the Business Accelerator Hub"})
    by["C02"].update(transport="bgRFC-Q", queue="per delivery", retry_on_timeout=False,
                     plan={"action": "RETIRE", "by": ROLLOUT,
                           "with": "intercompany flow inside one S/4HANA system after the rollout"})
    by["C03"].update(owner="00100288",
                     plan={"action": "KEEP", "by": ROLLOUT,
                           "with": "review at the CP20 rollout"})
    by["C04"].update(status="retired", commit_checked=True,
                     plan={"action": "RETIRE", "by": "2026-12-11",
                           "with": "requisitions converted in the standard purchasing apps"})
    by["C05"].update(s_rfc=["the ODP function groups only"],
                     plan={"action": "REPLACE", "by": "2026-12-31",
                           "with": "CDS extraction to Datasphere (ADR-001)"})
    by["C06"].update(callback_allowlist=["Z_MES_READ_ROUTING"], snc=True,
                     plan={"action": "KEEP", "by": "2027-06-30",
                           "with": "review with C01"})
    systems = copy.deepcopy(SYSTEMS)
    for s in systems.values():
        s.update(ucon_rfc=True, callback_security_method=3)
    return {"company": "Calder Pumpworks (fictional)", "as_of": AS_OF,
            "systems": systems, "connections": reg}


def draft_register():
    return {"company": "Calder Pumpworks (fictional)", "as_of": AS_OF,
            "systems": copy.deepcopy(SYSTEMS), "connections": copy.deepcopy(DRAFT)}


# ---------------------------------------------------------------- review

def check(conn, systems):
    """Return a list of (status, rule, text) for one connection."""
    out = []
    t = conn["transport"]
    if conn.get("status") == "retired":
        return [("OK", "RF00", f"retired; {conn['plan']['with']}")]

    out.append(("OK", "RF01", f"owner {conn['owner']}") if conn.get("owner")
               else ("FAIL", "RF01", "no owner: nobody answers when it breaks"))

    if conn["access"] == "write" and conn.get("must_once"):
        if t in AT_MOST_ONCE:
            extra = " and the caller retries on timeout" if conn.get("retry_on_timeout") else ""
            out.append(("FAIL", "RF02", f"{t} is at most once{extra}: a lost reply can post twice or not at all"))
        else:
            out.append(("OK", "RF02", f"{t} is exactly once"))

    if conn.get("order_sensitive"):
        out.append(("OK", "RF03", f"{t} keeps the order ({conn.get('queue', 'queue')})") if t in QUEUED
                   else ("FAIL", "RF03", f"{t} doesn't keep the order of updates to one object"))

    if t in LEGACY:
        out.append(("WARN", "RF04", f"{t}: SAP recommends bgRFC for new applications"))

    if conn.get("bapi"):
        out.append(("OK", "RF05", "RETURN checked before BAPI_TRANSACTION_COMMIT") if conn.get("commit_checked")
                   else ("FAIL", "RF05", "commits without checking RETURN for E or A messages"))

    if conn["target"] in systems:  # an SAP system receives the call: check the caller's user
        if conn["user_type"] == "personal":
            out.append(("FAIL", "RF06", f"personal user {conn['user']} with a stored password"))
        elif "*" in conn["s_rfc"]:
            out.append(("FAIL", "RF06", f"S_RFC for {conn['user']} allows every function group (*)"))
        else:
            out.append(("OK", "RF06", f"{conn['user']} limited to {', '.join(conn['s_rfc'])}"))

    if conn.get("callback"):
        caller = systems.get(conn["caller"], {})
        if not conn.get("callback_allowlist"):
            out.append(("FAIL", "RF07", "callbacks allowed with no allowlist on the destination"))
        elif caller.get("callback_security_method", 0) < 3:
            out.append(("WARN", "RF07", f"allowlist set, but {conn['caller']} runs "
                                        f"rfc/callback_security_method = {caller.get('callback_security_method')}"))
        else:
            out.append(("OK", "RF07", "callback allowlist: " + ", ".join(conn["callback_allowlist"])))

    if conn["network"] in ("cross", "cloud"):
        out.append(("OK", "RF08", "SNC on") if conn["snc"]
                   else ("FAIL", "RF08", "crosses a network without SNC"))

    if conn["target"] in systems:
        out.append(("OK", "RF09", f"UCON RFC basic scenario on in {conn['target']}")
                   if systems[conn["target"]]["ucon_rfc"]
                   else ("WARN", "RF09", f"UCON not on in {conn['target']}: every remote-enabled module is reachable"))

    level, plan = conn["code_level"], conn.get("plan")
    if level in ("C", "D", "odp-rfc"):
        what = {"C": "custom module reading SAP tables (level C)", "D": "level D object",
                "odp-rfc": "ODP over RFC, unpermitted for non-SAP extraction"}[level]
        if plan and plan["action"] in ("REPLACE", "RETIRE"):
            out.append(("OK", "RF10", f"{what}: {plan['action']} by {plan['by']} with {plan['with']}"))
        else:
            out.append(("FAIL", "RF10", f"{what}, and no replacement plan"))
    elif conn["target"] == "ECP" or conn["caller"] == "ECP":
        out.append(("OK", "RF10", f"{plan['action']} by {plan['by']}: {plan['with']}") if plan
                   else ("WARN", "RF10", f"touches ECC, which CP20 leaves on {ROLLOUT}: no plan"))
    elif level == "B":
        out.append(("OK", "RF10", "classic API (level B), planned") if plan
                   else ("WARN", "RF10", "classic API (level B): upgrade-stable, not formally released; plan its successor"))
    return out


def verdict(conn, results):
    if conn.get("status") == "retired":
        return "RETIRED"
    if any(r[0] == "FAIL" for r in results):
        return "FIX"
    return conn["plan"]["action"] if conn.get("plan") else "KEEP"


def review(reg, quiet=False):
    totals = {"OK": 0, "WARN": 0, "FAIL": 0}
    verdicts = {}
    systems = reg["systems"]
    if not quiet:
        print(f"{reg['company']}: RFC register as of {reg['as_of']}")
        for name, s in systems.items():
            print(f"  system {name}: {s['kind']}, UCON RFC {'on' if s['ucon_rfc'] else 'off'}, "
                  f"rfc/callback_security_method = {s['callback_security_method']}")
    for conn in reg["connections"]:
        results = check(conn, systems)
        v = verdict(conn, results)
        verdicts[conn["id"]] = v
        for r in results:
            totals[r[0]] += 1
        if not quiet:
            print(f"\n{conn['id']} {conn['name']}")
            print(f"    {conn['caller']} -> {conn['target']}, {conn['function']}, {conn['transport']}")
            for status, rule, text in results:
                print(f"  {status:<4} {rule} {text}")
            print(f"  verdict {v}")
    if not quiet:
        print(f"\n{totals['OK']} OK, {totals['WARN']} WARN, {totals['FAIL']} FAIL "
              f"across {len(reg['connections'])} connections")
    return totals, verdicts


# ---------------------------------------------------------------- stand-in system

class StandIn:
    """A tiny stand-in for the receiving system. Not SAP software."""

    def __init__(self, name):
        self.name = name
        self.db = {"shipped": {}, "status": {}, "reason": {}, "tids": set()}
        self.pending = []       # changes waiting for COMMIT WORK in this session
        self.log = []

    # a custom module that writes its own table: saved when the call ends
    def z_ic_ship_status(self, delivery, qty=None, status=None):
        if qty is not None:
            self.db["shipped"][delivery] = self.db["shipped"].get(delivery, 0) + qty
        if status is not None:
            self.db["status"][delivery] = status

    # a BAPI-shaped stand-in: checks, registers an update, never commits itself
    def z_lab_order_reason_set(self, order, reason):
        if order not in ("1000002", "1000003", "1000006", "1000007"):
            return [{"TYPE": "E", "MESSAGE": f"Sales order {order} does not exist"}]
        if not reason:
            return [{"TYPE": "E", "MESSAGE": "Order reason is required"}]
        self.pending.append(("reason", order, reason))
        return [{"TYPE": "S", "MESSAGE": f"Sales order {order} will be changed"}]

    def bapi_transaction_commit(self):
        for _, order, reason in self.pending:
            self.db["reason"][order] = reason
        n = len(self.pending)
        self.pending = []
        return [{"TYPE": "S", "MESSAGE": f"{n} change(s) saved"}]

    def bapi_transaction_rollback(self):
        n = len(self.pending)
        self.pending = []
        return [{"TYPE": "S", "MESSAGE": f"{n} change(s) discarded"}]

    def close_session(self):
        lost = len(self.pending)
        self.pending = []   # no COMMIT WORK: the update task never runs
        return lost

    # bgRFC-like inbound unit: run once per unit ID
    def run_unit(self, unit_id, calls):
        if unit_id in self.db["tids"]:
            self.log.append(f"unit {unit_id} already done: ignored")
            return
        for fn, kwargs in calls:
            getattr(self, fn)(**kwargs)
        self.db["tids"].add(unit_id)
        self.log.append(f"unit {unit_id} done")


def sim_retry(quiet=False):
    p = (lambda *a: None) if quiet else print
    p("Augsburg (ECP) posts 2 shipments of 20 impellers for PO 4500000008 to Rockford (S4P).")
    p("The network drops the reply to the first call after S4P has saved it.\n")
    s = StandIn("S4P")
    p("sRFC with retry on timeout (draft C02):")
    for n, (delivery, qty) in enumerate([("84000047", 20), ("84000048", 20)], start=1):
        s.z_ic_ship_status(delivery="PO4500000008", qty=qty)
        if n == 1:
            p("  call 1: saved in S4P, reply lost -> caller sees a timeout and calls again")
            s.z_ic_ship_status(delivery="PO4500000008", qty=qty)
            p("  call 1 again: saved again")
        else:
            p("  call 2: saved, reply received")
    srfc = s.db["shipped"]["PO4500000008"]
    p(f"  S4P shows {srfc} impellers shipped; Augsburg shipped 40\n")

    s = StandIn("S4P")
    p("bgRFC unit with a unit ID (reviewed C02):")
    s.run_unit("UNIT-000001", [("z_ic_ship_status", {"delivery": "PO4500000008", "qty": 20})])
    p("  unit UNIT-000001: saved in S4P, confirmation lost -> the sender's scheduler sends it again")
    s.run_unit("UNIT-000001", [("z_ic_ship_status", {"delivery": "PO4500000008", "qty": 20})])
    s.run_unit("UNIT-000002", [("z_ic_ship_status", {"delivery": "PO4500000008", "qty": 20})])
    for line in s.log:
        p("  " + line)
    bg = s.db["shipped"]["PO4500000008"]
    p(f"  S4P shows {bg} impellers shipped")
    return srfc, bg


def sim_order(quiet=False):
    p = (lambda *a: None) if quiet else print
    units = [("UNIT-000011", "SHIPPED"), ("UNIT-000012", "IN_TRANSIT"), ("UNIT-000013", "ARRIVED")]
    p("Augsburg sends three status updates for delivery 84000047, in this order:")
    p("  " + ", ".join(f"{u} {st}" for u, st in units) + "\n")

    s = StandIn("S4P")
    any_order = [units[2], units[0], units[1]]   # transactional units may run in any order
    p("Transactional units (bgRFC type T or tRFC): each runs once, in no fixed order.")
    for u, st in any_order:
        s.run_unit(u, [("z_ic_ship_status", {"delivery": "84000047", "status": st})])
        p(f"  ran {u} {st}")
    t_final = s.db["status"]["84000047"]
    p(f"  final status in S4P: {t_final}\n")

    s = StandIn("S4P")
    p("Queued units (bgRFC type Q, queue IC_84000047): each runs once, in creation order.")
    for u, st in units:
        s.run_unit(u, [("z_ic_ship_status", {"delivery": "84000047", "status": st})])
        p(f"  ran {u} {st}")
    q_final = s.db["status"]["84000047"]
    p(f"  final status in S4P: {q_final}")
    return t_final, q_final


def sim_commit(quiet=False):
    p = (lambda *a: None) if quiet else print
    changes = [("1000002", "CRH"), ("1000099", "CRH"), ("1000003", "PTM")]
    p("The CRM sets order reasons on three orders in one session (one logical unit of work).")
    p("Order 1000099 doesn't exist. Z_LAB_ORDER_REASON_SET is a BAPI-shaped course stand-in.\n")

    s = StandIn("S4P")
    p("A. Call the BAPI three times, never commit:")
    for o, r in changes:
        ret = s.z_lab_order_reason_set(order=o, reason=r)
        p(f"  {o}: RETURN {ret[0]['TYPE']} {ret[0]['MESSAGE']}")
    lost = s.close_session()
    a_saved = len(s.db["reason"])
    p(f"  session closed: {lost} registered change(s) lost, {a_saved} saved\n")

    s = StandIn("S4P")
    p("B. Commit at the end without reading RETURN:")
    for o, r in changes:
        s.z_lab_order_reason_set(order=o, reason=r)
    ret = s.bapi_transaction_commit()
    b_saved = sorted(s.db["reason"])
    p(f"  BAPI_TRANSACTION_COMMIT: {ret[0]['MESSAGE']}")
    p(f"  saved: {', '.join(b_saved)}; 1000099 silently missing, the CRM reports all three done\n")

    s = StandIn("S4P")
    p("C. Read RETURN after every call; any E or A means roll back the whole unit:")
    failed = []
    for o, r in changes:
        ret = s.z_lab_order_reason_set(order=o, reason=r)
        bad = [m for m in ret if m["TYPE"] in ("E", "A")]
        p(f"  {o}: RETURN {ret[0]['TYPE']} {ret[0]['MESSAGE']}")
        if bad:
            failed.append(o)
    if failed:
        ret = s.bapi_transaction_rollback()
        p(f"  BAPI_TRANSACTION_ROLLBACK: {ret[0]['MESSAGE']}; the CRM shows {', '.join(failed)} as an error")
    else:
        ret = s.bapi_transaction_commit()
        p(f"  BAPI_TRANSACTION_COMMIT: {ret[0]['MESSAGE']}")
    c_saved = len(s.db["reason"])
    p(f"  saved: {c_saved}; fix 1000099 at the source and send the unit again")
    return a_saved, b_saved, c_saved


def sim_callback(reg_name="draft", quiet=False):
    p = (lambda *a: None) if quiet else print
    reg = draft_register() if reg_name == "draft" else reviewed_register()
    conn = next(c for c in reg["connections"] if c["id"] == "C06")
    method = reg["systems"]["S4P"]["callback_security_method"]
    allow = conn["callback_allowlist"]
    p(f"S4P calls MES_ORDER_IN on the MES (sRFC). Register: {reg_name}.")
    p(f"  rfc/callback_security_method = {method}, allowlist = {', '.join(allow) or 'none'}")
    p("  While it runs, the MES calls back into S4P with DESTINATION 'BACK':\n")
    results = {}
    for fn in ("Z_MES_READ_ROUTING", "Z_LAB_RUN_ANY_REPORT"):
        if method == 0:
            ok = True
        elif not allow:
            ok = method < 3   # no active allowlist: only method 3 rejects
        else:
            ok = fn in allow
        results[fn] = ok
        p(f"  {fn:<22} {'ALLOWED' if ok else 'REJECTED'}")
    if results["Z_LAB_RUN_ANY_REPORT"]:
        p("\n  The MES could run anything S4P's calling user may run. Set an allowlist on the destination.")
    return results


# ---------------------------------------------------------------- files and CLI

def write_samples():
    FOLDER.mkdir(parents=True, exist_ok=True)
    for name, data in (("register_draft.json", draft_register()),
                       ("register_reviewed.json", reviewed_register())):
        path = FOLDER / name
        if path.exists():
            print(f"{path} already exists; delete it first to get the sample back")
            continue
        path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
        print(f"wrote {path}")


def load(path):
    p = Path(path)
    if not p.exists():
        sys.exit(f"{p} not found: run python unit26/rfc_lab.py --init first")
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{p} is not valid JSON (line {e.lineno}): {e.msg}")


def self_test():
    checks = []
    t, v = review(draft_register(), quiet=True)
    checks.append(("draft counts", (t["OK"], t["WARN"], t["FAIL"]) == (10, 8, 14)))
    checks.append(("draft verdicts all FIX", set(v.values()) == {"FIX"}))
    t, v = review(reviewed_register(), quiet=True)
    checks.append(("reviewed counts", (t["OK"], t["WARN"], t["FAIL"]) == (26, 0, 0)))
    checks.append(("reviewed C04 retired", v["C04"] == "RETIRED"))
    checks.append(("reviewed C05 replace", v["C05"] == "REPLACE"))
    srfc, bg = sim_retry(quiet=True)
    checks.append(("retry duplicates with sRFC", srfc == 60))
    checks.append(("unit ID stops duplicate", bg == 40))
    tf, qf = sim_order(quiet=True)
    checks.append(("type T ends wrong", tf == "IN_TRANSIT"))
    checks.append(("type Q ends right", qf == "ARRIVED"))
    a, b, c = sim_commit(quiet=True)
    checks.append(("no commit saves nothing", a == 0))
    checks.append(("blind commit saves half", b == ["1000002", "1000003"]))
    checks.append(("checked unit rolls back", c == 0))
    cd = sim_callback("draft", quiet=True)
    cr = sim_callback("reviewed", quiet=True)
    checks.append(("draft callback open", cd["Z_LAB_RUN_ANY_REPORT"] is True))
    checks.append(("reviewed callback closed",
                   cr == {"Z_MES_READ_ROUTING": True, "Z_LAB_RUN_ANY_REPORT": False}))
    for name, ok in checks:
        print(f"{'OK  ' if ok else 'FAIL'} {name}")
    passed = sum(ok for _, ok in checks)
    print(f"{passed} of {len(checks)} self-test checks passed")
    return passed == len(checks)


def main():
    ap = argparse.ArgumentParser(description="RFC and BAPI course lab (Unit 26)")
    ap.add_argument("--init", action="store_true", help="write the sample registers")
    ap.add_argument("--self-test", action="store_true", help="check the built-in samples")
    ap.add_argument("command", nargs="?", choices=["review", "simulate"])
    ap.add_argument("case", nargs="?", choices=["retry", "order", "commit", "callback"])
    ap.add_argument("--file", default=str(FOLDER / "register_draft.json"))
    ap.add_argument("--register", choices=["draft", "reviewed"], default="draft",
                    help="for simulate callback")
    args = ap.parse_args()
    if args.init:
        write_samples()
        return 0
    if args.self_test:
        return 0 if self_test() else 1
    if args.command == "review":
        totals, _ = review(load(args.file))
        return 2 if totals["FAIL"] else 0
    if args.command == "simulate":
        case = args.case or "retry"
        if case == "retry":
            sim_retry()
        elif case == "order":
            sim_order()
        elif case == "commit":
            sim_commit()
        else:
            sim_callback(args.register)
        return 0
    ap.print_help()
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 3: Write the sample files and check them

1. Run:

   ```bash
   python unit26/rfc_lab.py --init
   ```

   You see:

   ```text
   wrote unit26/rfc/register_draft.json
   wrote unit26/rfc/register_reviewed.json
   ```

2. Run the self-test:

   ```bash
   python unit26/rfc_lab.py --self-test
   ```

   The last line reads `14 of 14 self-test checks passed`.

3. Open `unit26/rfc/register_draft.json`. It holds two systems (`S4P`, Calder's S/4HANA for `CP10`, and `ECP`, the ECC system of `CP20`) and six connections. Each connection says who calls whom, which function, which variant (`transport`), which user and what the user may call (`s_rfc`).

> **Note** On Windows, if `python` opens the Microsoft Store or isn't found, use `py` instead in every command.

#### Step 4: Review the partner's draft register

1. Run:

   ```bash
   python unit26/rfc_lab.py review
   ```

2. The output starts like this:

   ```text
   Calder Pumpworks (fictional): RFC register as of 2026-11-30
     system S4P: S/4HANA Cloud Private Edition (CP10), UCON RFC off, rfc/callback_security_method = 1
     system ECP: ECC 6.0 EhP 8 (CP20), UCON RFC off, rfc/callback_security_method = 1

   C01 MES Rockford reads released production orders
       MES-RK -> S4P, Z_MES_GET_ORDERS, sRFC
     OK   RF01 owner 00100314
     FAIL RF06 S_RFC for TU_MES_RFC allows every function group (*)
     FAIL RF08 crosses a network without SNC
     WARN RF09 UCON not on in S4P: every remote-enabled module is reachable
     FAIL RF10 custom module reading SAP tables (level C), and no replacement plan
     verdict FIX

   ```

3. The last line reads:

   ```text
   10 OK, 8 WARN, 14 FAIL across 6 connections
   ```

   Every connection gets the verdict `FIX`, and the exit code is `2`.

The rules:

| Rule | Checks | Source |
| --- | --- | --- |
| `RF01` | Every connection has an owner | Course rule |
| `RF02` | A write that must happen once uses an exactly-once variant | SAP's variant guarantees |
| `RF03` | Updates whose order matters use a queued variant | SAP's variant guarantees |
| `RF04` | tRFC and qRFC are flagged for a move to bgRFC | SAP's recommendation |
| `RF05` | A BAPI caller checks the return messages before committing | SAP's BAPI transaction model |
| `RF06` | A technical user, with `S_RFC` limited to named function groups | `S_RFC`; no personal users is a course rule |
| `RF07` | Callbacks have an allowlist; the caller runs `rfc/callback_security_method = 3` | SAP's callback allowlist; value 3 is a course target |
| `RF08` | SNC on connections that cross a network | Course rule |
| `RF09` | UCON's RFC basic scenario is on in the target SAP system | SAP's UCON concept |
| `RF10` | Level C code and ODP over RFC have a replacement plan; ECC connections have a plan for the July 2027 rollout | SAP's clean core levels and API policy; dates are course values |

Read the findings that matter most:

- `C02` fails `RF02` and `RF03`: Augsburg posts shipment quantities and statuses by synchronous RFC and resends on timeout.
- `C04` fails four rules: a planner's spreadsheet calls `BAPI_PO_CREATE1` under the planner's own user, with a wildcard, and commits without reading messages.
- `C06` fails `RF07`: Rockford calls the MES, and the MES may call back into Rockford with no allowlist.

#### Step 5: See why RF02 exists

1. Run:

   ```bash
   python unit26/rfc_lab.py simulate retry
   ```

2. You see:

   ```text
   Augsburg (ECP) posts 2 shipments of 20 impellers for PO 4500000008 to Rockford (S4P).
   The network drops the reply to the first call after S4P has saved it.

   sRFC with retry on timeout (draft C02):
     call 1: saved in S4P, reply lost -> caller sees a timeout and calls again
     call 1 again: saved again
     call 2: saved, reply received
     S4P shows 60 impellers shipped; Augsburg shipped 40

   bgRFC unit with a unit ID (reviewed C02):
     unit UNIT-000001: saved in S4P, confirmation lost -> the sender's scheduler sends it again
     unit UNIT-000001 done
     unit UNIT-000001 already done: ignored
     unit UNIT-000002 done
     S4P shows 40 impellers shipped
   ```

The first call was saved, but its reply was lost, so Augsburg's program called again. Synchronous RFC has no memory of the first call. The bgRFC unit carries an ID, and the receiver ignores a unit it has already run.

#### Step 6: See why RF03 exists

1. Run:

   ```bash
   python unit26/rfc_lab.py simulate order
   ```

2. You see:

   ```text
   Augsburg sends three status updates for delivery 84000047, in this order:
     UNIT-000011 SHIPPED, UNIT-000012 IN_TRANSIT, UNIT-000013 ARRIVED

   Transactional units (bgRFC type T or tRFC): each runs once, in no fixed order.
     ran UNIT-000013 ARRIVED
     ran UNIT-000011 SHIPPED
     ran UNIT-000012 IN_TRANSIT
     final status in S4P: IN_TRANSIT

   Queued units (bgRFC type Q, queue IC_84000047): each runs once, in creation order.
     ran UNIT-000011 SHIPPED
     ran UNIT-000012 IN_TRANSIT
     ran UNIT-000013 ARRIVED
     final status in S4P: ARRIVED
   ```

Each transactional unit ran exactly once, yet the delivery ends as in transit although it arrived. The stand-in runs the units in a fixed shuffled order to show what "no fixed order" allows. Queued units run in the order they were written.

#### Step 7: See why RF05 exists

1. Run:

   ```bash
   python unit26/rfc_lab.py simulate commit
   ```

2. You see:

   ```text
   The CRM sets order reasons on three orders in one session (one logical unit of work).
   Order 1000099 doesn't exist. Z_LAB_ORDER_REASON_SET is a BAPI-shaped course stand-in.

   A. Call the BAPI three times, never commit:
     1000002: RETURN S Sales order 1000002 will be changed
     1000099: RETURN E Sales order 1000099 does not exist
     1000003: RETURN S Sales order 1000003 will be changed
     session closed: 2 registered change(s) lost, 0 saved

   B. Commit at the end without reading RETURN:
     BAPI_TRANSACTION_COMMIT: 2 change(s) saved
     saved: 1000002, 1000003; 1000099 silently missing, the CRM reports all three done

   C. Read RETURN after every call; any E or A means roll back the whole unit:
     1000002: RETURN S Sales order 1000002 will be changed
     1000099: RETURN E Sales order 1000099 does not exist
     1000003: RETURN S Sales order 1000003 will be changed
     BAPI_TRANSACTION_ROLLBACK: 2 change(s) discarded; the CRM shows 1000099 as an error
     saved: 0; fix 1000099 at the source and send the unit again
   ```

Case A loses everything silently. Case B is worse: two orders change and the third doesn't, while the caller reports success. Case C treats the three changes as one unit, as SAP's transaction model intends, and reports the bad order.

#### Step 8: See why RF07 exists

1. Run the draft, then the reviewed setting:

   ```bash
   python unit26/rfc_lab.py simulate callback
   python unit26/rfc_lab.py simulate callback --register reviewed
   ```

2. The last lines of the two runs:

   ```text
   Z_MES_READ_ROUTING     ALLOWED
   Z_LAB_RUN_ANY_REPORT   ALLOWED
   ...
   Z_MES_READ_ROUTING     ALLOWED
   Z_LAB_RUN_ANY_REPORT   REJECTED
   ```

`Z_LAB_RUN_ANY_REPORT` stands for any powerful remote function the calling user is allowed to run. With an allowlist on the destination and the strictest parameter value, only the function the MES needs gets through.

#### Step 9: Review the corrected register

1. Run:

   ```bash
   python unit26/rfc_lab.py review --file unit26/rfc/register_reviewed.json
   ```

2. The verdicts and the last line:

   ```text
   C01 ... verdict REPLACE
   C02 ... verdict RETIRE
   C03 ... verdict KEEP
   C04 ... verdict RETIRED
   C05 ... verdict REPLACE
   C06 ... verdict KEEP
   26 OK, 0 WARN, 0 FAIL across 6 connections
   ```

What changed, connection by connection:

| Connection | Fix | Plan |
| --- | --- | --- |
| `C01` MES reads production orders through `Z_MES_GET_ORDERS` | `S_RFC` limited to `ZMES`, SNC on | Replace by a released API by 2027-06-30 |
| `C02` Augsburg posts shipments | bgRFC type Q, one queue per delivery | Retire at the July 2027 rollout |
| `C03` Certificate archive reads ECC | Owner `00100288` named | Keep, review at the rollout |
| `C04` Planner's spreadsheet | Retired | Requisitions converted in the standard apps |
| `C05` ODP over RFC to the warehouse | `S_RFC` narrowed | Replace by CDS extraction to Datasphere (ADR-001) |
| `C06` Push to the MES with callback | Allowlist `Z_MES_READ_ROUTING`, SNC on | Keep, review with `C01` |

Both systems also switch UCON's RFC basic scenario on and set `rfc/callback_security_method` to `3`.

> **Note** The counts, verdicts and quantities come from made-up data and course rules, not from a real SAP system. They show the method.

#### Step 10 (sketch): Read a real system's connections

> **Note** This step is a **sketch**. It needs access to an SAP system with administration rights, which learners rarely have. Units 21 and 27 cover connectivity and security.

1. In `SM59`, list the ABAP and external destinations, with their users and SNC settings, and add one register entry per destination.
2. In `UCONCOCKPIT`, check whether the RFC basic scenario is active per client.
3. In `SM58`, `SMQ1`, `SMQ2` and `SBGRFCMON`, note which interfaces leave stuck calls; those are the ones with a variant to review.
4. In the role administration, find every role with `S_RFC` and a wildcard in `RFC_NAME`.
5. Run the review on the register you built.

To call RFC from your own Python code against a real system you would need SAP's NetWeaver RFC SDK and a binding. SAP archived its Python binding PyRFC on 28 May 2026 and marks it no longer maintained ([GitHub](https://github.com/SAP-archive/PyRFC)), so don't start new work on it; prefer released OData or SOAP services, covered in [SOAP and OData services in depth](https://erpfde.com/topics/soap-and-odata-services-in-depth/).

#### Step 11: Save your work

```bash
git add unit26/rfc_lab.py unit26/rfc
git commit -m "Unit 26: RFC register review for Calder"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `DRAFT`, `reviewed_register()` | The partner's register and the corrected one, as Python data written to JSON by `--init` |
| `check()` | Applies `RF01` to `RF10` to one connection and returns OK, WARN or FAIL lines |
| `verdict()` | `FIX` if anything fails, otherwise the plan's action (`KEEP`, `REPLACE`, `RETIRE`), or `RETIRED` |
| `StandIn` | A tiny receiving system: a custom module that saves at once, a BAPI-shaped module that only registers changes, commit and rollback, and units that run once per ID |
| `sim_retry()`, `sim_order()` | Compare synchronous calls with bgRFC units, and transactional with queued units |
| `sim_commit()`, `sim_callback()` | Show the three ways to end a BAPI unit, and the callback allowlist at work |
| `self_test()` | Fourteen checks on the built-in samples, so you can tell a broken copy from an edited file |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't installed, or the terminal can't find it | Repeat the Python step of Set up your computer and open a new terminal; on macOS/Linux use `python3` until `.venv` is active |
| `No module named ...` | A different script was pasted, or an import was added | The script needs built-in modules only; paste it again from Step 2 |
| `register_draft.json not found` | Step 3 hasn't run, or you are in another folder | Run `python unit26/rfc_lab.py --init` from `orchestrate-course` |
| `already exists; delete it first` | `--init` doesn't overwrite your edits | Delete the file only if you want the sample back |
| `is not valid JSON (line N)` | A comma or bracket is missing after an edit | VS Code marks the line; fix it and run again |
| `KeyError: 'owner'` or another field | A new connection is missing a field | Copy an existing entry and change its values |
| Your counts differ from the samples | The files were edited | Run `--self-test`, then `--init` in a fresh folder |
| A company proxy blocks downloads | Not used here | The lab needs no network |

### The SAP way

What SAP provides, as of 30 November 2026:

- **bgRFC** in every ABAP system from SAP Basis 7.0 onward, with `SBGRFCMON` for monitoring and `SBGRFCCONF` for inbound destinations ([SAP Support Portal](https://support.sap.com/en/alm/sap-focused-run/expert-portal/integration-cloud-monitoring/bgrfc.html)). SAP names it the successor of tRFC and qRFC ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/99b53cee2b73e7e10000000a42189b/content.htm)).
- **The BAPI transaction model** with `BAPI_TRANSACTION_COMMIT` and `BAPI_TRANSACTION_ROLLBACK` ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/4d/5b102ba1483d8fe10000000a42189e/content.htm)). Unit 24 covers function modules, BAPIs and classes from the ABAP side.
- **UCON** for reducing what is reachable from outside ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/c0/51e93edb9344bb92c986bd9666aecd/content.htm)), and **callback allowlists** per destination ([SAP Community](https://community.sap.com/t5/additional-blog-posts-by-sap/rfc-callback-whitelist/ba-p/13227084)).
- **Cloud access to on-premise functions** from the SAP BTP ABAP environment through communication arrangements and the Cloud Connector ([SAP Developers](https://developers.sap.com/tutorials/abap-env-rfc.html)); the [BTP connectivity topic](https://erpfde.com/topics/btp-connectivity/) covers virtual hosts and location IDs.
- **SAP Integration Suite** calls RFC as a receiver through an RFC destination on BTP and the Cloud Connector, as an SAP blog shows step by step ([SAP Community](https://community.sap.com/t5/technology-blog-posts-by-sap/using-rfc-adapter-in-the-sap-integration-suite-part-ii/ba-p/13544246)). SAP's tutorial on modernizing RFC receivers replaces them with SOAP services after a migration ([SAP Developers](https://developers.sap.com/tutorials/modernize-rfc-receiver.md)).
- **Licensing note.** RFC and BAPIs are part of the ABAP platform itself. What callers may do with them is governed by your contract and SAP's API policy. Integration Suite and the ABAP environment are BTP services with their own commercial terms.

### Build vs. SAP

| Need | SAP | Your own | Use which |
| --- | --- | --- | --- |
| Exactly-once delivery between ABAP systems | bgRFC type T | A duplicate table in your function | SAP's; your own only for a non-ABAP sender that can't use bgRFC |
| Ordered delivery | bgRFC type Q (qRFC in older code) | Sequence numbers checked by the receiver | SAP's; plan queue names per business object |
| Commit and error handling for BAPIs | Transaction model and return parameter | A wrapper that commits per unit | A small wrapper per caller that follows SAP's model |
| Restricting what's callable | UCON, `S_RFC`, callback allowlists | Firewall rules only | SAP's controls; the network is a second layer |
| A register of connections | Destinations in `SM59`, UCON logs | A register with owner, variant and plan | Yours, filled from SAP's data |
| New interfaces into S/4HANA | Released APIs on the Business Accelerator Hub | Custom remote functions | Released APIs; custom functions only where no API exists, with a plan |

### Architecture view

**Where it sits.** RFC runs between ABAP systems directly, from external programs through SAP's RFC libraries, and from BTP through the Cloud Connector.

```mermaid
flowchart LR
  MES[Rockford MES] -- sRFC --> S4P[S/4HANA S4P<br/>CP10, RISE]
  S4P -- sRFC + callback --> MES
  ECP[ECC ECP<br/>CP20 Augsburg] -- bgRFC type Q --> S4P
  BTP[BTP ABAP environment<br/>calder-ext-prod] -- Cloud Connector<br/>SCC-AU-P --> ECP
  DW[Data warehouse] -. ODP over RFC,<br/>to replace .-> S4P
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Delivery guarantee | Exactly once for every posting | Duplicates or gaps in quantities and documents |
| Ordering | In order per business object where updates overwrite | Statuses or prices end on an older value |
| Latency | Synchronous reads within the caller's timeout, a few seconds | Users wait, callers retry and multiply load |
| Backlog | Stuck units visible in `SBGRFCMON` or `SMQ2` within minutes | Interfaces stop silently until someone complains |
| Least privilege | `S_RFC` per function group, UCON active | A leaked credential reaches every remote function |
| Lifetime | A plan per level C connection and per ECC target | Upgrades break custom code; ECC switch-off leaves orphans |

**Integration and identity.** Between ABAP systems, the destination names a technical user, or a trusted relationship checked with `S_RFCACL` ([SAP Help Portal](https://help.sap.com/saphelp_em92/helpdata/en/48/8d1c6eae444e6ee10000000a421937/content.htm)). From BTP, the communication arrangement and the Cloud Connector carry the call; the [BTP security model topic](https://erpfde.com/topics/btp-security-model/) covers the identity side. A technical user loses the business user's identity, so authorization checks inside the function see only the technical user; keep the user's scope as narrow as the interface.

**The decision to record** (short ADR form from the [design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context.** Augsburg's ECC posts shipment quantities and statuses to Rockford by synchronous RFC with a retry on timeout. Duplicates appeared twice in October (course story). `CP20` moves into `CP10`'s system on 5 July 2027.
- **Options.** A: keep sRFC and add a duplicate check in `Z_IC_SHIP_STATUS`. B: switch the sender to bgRFC type Q with one queue per delivery. C: move the interface to Integration Suite now.
- **Decision.** B: both sides are ABAP, bgRFC is SAP's recommended variant, and the interface retires at the rollout, so C's build and test cost buys little.
- **Consequences.** Augsburg's program changes one call statement and gets a queue name. Operations watch `SBGRFCMON` on `ECP`. A stuck queue stops all later units for that delivery, so the run book names who clears it.

**What a design review will ask.**

1. Which of these interfaces write data, and what stops a duplicate after a timeout?
2. Where does order matter, and what is the queue name per object?
3. Who owns each technical user, and what may it call?
4. What happens to each connection when ECC is switched off?
5. Which connections use code SAP rates level C, and when do they go?

### Production concerns

- **Security and authorizations.** Review every role with `S_RFC` and a wildcard first; they are the largest risk for the least effort. Switch UCON on per client after a logging period, so legitimate callers are on the list before blocking starts. Rotate passwords of technical users, or use certificates with SNC. Retire personal users in external tools.
- **Evaluation.** Test each interface for a lost reply, a resent message, an out-of-order message and a partial failure in a batch. The lab's four simulations are the test cases to write for the real system.
- **Cost.** Most fixes are small code and configuration changes. The expensive part is replacing level C functions with released APIs, which needs analysis on both sides; budget it per connection.
- **Operations.** Background variants hide failures in monitors; synchronous ones hide them in the caller's log. Name an owner and an alert for each. A stuck queue in qRFC or bgRFC type Q blocks everything behind it: the run book says when to fix and restart and who may delete a unit.
- **Clean core.** A BAPI wrapper is level B and acceptable; a function that reads SAP tables is level C. SAP's tutorial warns that RFC silently truncates values longer than the ABAP field, where SOAP and OData reject them ([SAP Developers](https://developers.sap.com/tutorials/modernize-rfc-receiver.md)); expect new errors when you move an interface.

### Where AI fits

AI changes three things for RFC and BAPIs, as of November 2026:

- **An agent is one more caller.** If an agent calls BAPIs, every rule here applies to it, plus SAP's API policy, which restricts AI systems that plan sequences of API calls to SAP-endorsed architectures ([SAP API Policy](https://help.sap.com/doc/sap-api-policy/latest/en-US/API_Policy_latest.pdf)). The [MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) and the [API policy page](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) show the endorsed routes. Don't hand an agent a technical RFC user.
- **Reading old interfaces.** A model can explain an old custom function or a caller's commit logic and draft a register entry. Treat it as a draft; the review rules and tests decide.
- **Replacing level C code.** Migration tooling that uses AI is covered in [AI in S/4HANA migration projects](https://erpfde.com/topics/ai-for-s4hana-migration-projects/); custom RFC modules are typical findings there.

### Pitfalls

- **Retrying synchronous writes.** A timeout doesn't mean the call failed. Use an exactly-once variant or make the function safe to repeat.
- **Assuming transactional means ordered.** It doesn't. Put updates to one object in one queue.
- **Committing without reading messages.** Partial saves look like success to the caller.
- **One queue for everything.** A single stuck unit stops the whole interface. Queue per business object.
- **Mixing tRFC and bgRFC on one destination.** SAP says they can't be combined there.
- **Wildcards in `S_RFC`.** They survive every audit until the day a credential leaks.
- **Callbacks left open.** The called system can run functions in yours with your user's rights.
- **Building new interfaces on custom remote functions.** Use released APIs; keep custom functions only where no API exists, with a plan.

### Exercise

Augsburg also sends Rockford the monthly transfer price of impeller `CP-IMP200`, by transactional RFC. Add it to the register and fix it.

1. Open `unit26/rfc/register_reviewed.json` and add a seventh connection at the end of the `connections` list (put a comma after the closing brace of `C06`):

   ```json
   {"id": "C07", "interface": "-", "name": "Augsburg sends the monthly impeller transfer price",
    "caller": "ECP", "target": "S4P", "function": "Z_IC_PRICE_SET", "access": "write",
    "must_once": true, "order_sensitive": true, "transport": "tRFC",
    "user": "TU_IC_RFC", "user_type": "technical", "s_rfc": ["ZIC"], "network": "cross",
    "snc": true, "code_level": "custom", "plan": null, "owner": "00100292"}
   ```

2. Run `python unit26/rfc_lab.py review --file unit26/rfc/register_reviewed.json`. `C07` shows `FAIL RF03`, `WARN RF04` and `WARN RF10`, and the last line reads `31 OK, 2 WARN, 1 FAIL across 7 connections`.
3. Change `C07`: set `"transport": "bgRFC-Q"`, add `"queue": "per material",` and replace `"plan": null` with:

   ```json
   "plan": {"action": "RETIRE", "by": "2027-07-05", "with": "the ABAP Cloud price job in CP10 after the rollout"}
   ```

4. Run the review again. `C07` reads `verdict RETIRE` and the last line reads `33 OK, 0 WARN, 0 FAIL across 7 connections`.
5. Write a short decision record in `unit26/rfc/decision_c07.md` with the four ADR headings: why queued and not transactional, and why not rebuilt before the rollout.

**Done when:** the review prints `33 OK, 0 WARN, 0 FAIL across 7 connections` and `decision_c07.md` records the decision. The register feeds the [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/).

> **Note** The counts come from made-up data and course rules, not from a real SAP system.

### Going further

For readers who want the edge cases behind delivery guarantees and SAP's own reference material.

- **Exactly once is a pair of promises.** The sender stores the unit before sending, and the receiver remembers which unit IDs it has run. Losing either side's record (a deleted unit, a cleaned-up ID table) reopens the door to duplicates or gaps. SAP's bgRFC monitor lets an administrator delete units ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/927c5caa6b17cee10000000a421937/content.htm)); a run book should say when that is allowed and who checks the business data afterwards.
- **Queues as locks.** SAP warns that a call placed in several queues creates a dependency that acts like a lock, and that misuse can stop queue processing ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/927c2caa6b17cee10000000a421937/content.htm)). Design queue names so that a unit touches the smallest set of objects it must.
- **Push and pull.** SAP's background communication overview describes push, where schedulers send, and a pull ("no-send") scenario, where the receiver collects data ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/48/96e29a0eec3987e10000000a421937/content.htm)). Pull helps when the receiver can't accept load at the sender's pace.
- **UCON with SNC.** SAP's setup guide shows how to keep a separate communication assembly for calls that must use SNC, and what happens to its functions if you delete it ([SAP Help Portal](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/10/d691aafa5e4cc0bb391ba3962280f9/content.htm)).

### Check yourself

1. Which statement matches SAP's guarantees for synchronous RFC?
   - A. Exactly once, because the caller waits for the reply
   - B. At most once, and nothing is stored before the call
   - C. Exactly once and in order when the call is repeated
   - D. At least once, because the destination retries for you

   Answer: B. SAP lists sRFC and aRFC as at most once, with the data not written to the database first. Exactly once needs a stored call with an ID, as in tRFC or bgRFC.

2. What does a receiver need in order to ignore a resent bgRFC unit?
   - A. A longer timeout on the sender's destination in SM59
   - B. A second technical user that only handles resends
   - C. The unit's ID, recorded when the unit first ran
   - D. The queue name, compared against the previous unit

   Answer: C. bgRFC stores each call under a unique ID. The lab's stand-in records the ID when the unit runs and ignores the same ID again, which is how a lost confirmation doesn't double the impellers.

3. Three BAPI calls run in one session; the second returns an E message. What should the caller do?
   - A. Commit, because the first and third calls succeeded
   - B. Close the session; the BAPI rolls back by itself
   - C. Call the second BAPI again until it returns success
   - D. Roll back the whole unit and report the failed item

   Answer: D. SAP's model treats the calls as one logical unit of work ended by the caller. Committing would save two of three changes while reporting success; rolling back keeps the unit whole.

4. Why must BAPIs change the database through the update task?
   - A. An RFC ends with an implicit database commit
   - B. The update task runs the BAPI's authorization checks
   - C. The update task keeps updates in creation order
   - D. Only the update task can write to custom tables

   Answer: A. SAP's BAPI guide says changes go through the update task because RFC performs an implicit database commit. That way nothing is saved until the caller commits the unit.

5. An interface was moved from qRFC to bgRFC on one destination. What does SAP say about going back?
   - A. It works as long as the queue names stay the same
   - B. It needs only a restart of the queue schedulers
   - C. Changing back from bgRFC to qRFC is not supported
   - D. It is possible once all open units are deleted

   Answer: C. SAP's bgRFC page says changing back to qRFC is not supported, and that bgRFC can't be combined with tRFC and qRFC on one destination. Plan the move as one way.

6. The MES calls back into S/4HANA during a synchronous call. Which setting limits what it can run?
   - A. An S_RFCACL entry for the MES's own user
   - B. A larger value for the SM59 connection timeout
   - C. The MES queue in SMQ2 with a lock on it
   - D. A callback allowlist on the SM59 destination

   Answer: D. SAP added a callback allowlist per destination, applied according to rfc/callback_security_method; value 3 is the strictest. S_RFCACL governs trusted users, not callbacks.

7. A technical user has S_RFC with a wildcard in RFC_NAME. What is the right fix?
   - A. Replace the user with the planner's personal user
   - B. Limit it to the function groups the interface needs
   - C. Keep it and turn on SNC on the destination instead
   - D. Move the interface to aRFC so it runs in parallel

   Answer: B. S_RFC is checked per function group, so a wildcard lets the user's credentials reach every remote function. SNC encrypts the line but doesn't narrow what may be called.

8. Your team wants to call an on-premise function from the SAP BTP ABAP environment. What does SAP's tutorial use?
   - A. A direct connection from BTP to the system's message server
   - B. A WebSocket RFC destination through the Cloud Connector
   - C. A communication arrangement, the Cloud Connector and cl_rfc_destination_provider
   - D. PyRFC on BTP, which SAP maintains for cloud runtimes

   Answer: C. The tutorial exposes the function in the Cloud Connector, builds a communication scenario, system and arrangement, then gets the destination with cl_rfc_destination_provider. SAP's blog says the Cloud Connector didn't support WebSocket RFC, and PyRFC is archived.

## Sources

- [RFC variants (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/saphelp_nw73/helpdata/en/48/99b53cee2b73e7e10000000a42189b/content.htm): sRFC (CALL FUNCTION ... DESTINATION) and aRFC (STARTING NEW TASK) at most once, data not stored; bgRFC (IN BACKGROUND UNIT) exactly once under a unique TID, units of type T or Q, type Q in the order written; tRFC (IN BACKGROUND TASK AS SEPARATE UNIT) the predecessor; qRFC built on tRFC with TRFC_SET_QUEUE_NAME; tRFC and bgRFC can't be used in parallel; SAP recommends bgRFC for better performance
- [bgRFC (Background Remote Function Call) (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/saphelp_nw73/helpdata/en/48/927c2caa6b17cee10000000a421937/content.htm): Transactional (once, any order) or queued (once, order of creation); units transferred whole or not at all; a call in several queues acts like a lock and misuse can stop queue processing; bgRFC can't be combined with tRFC and qRFC within one destination; changing back from bgRFC to qRFC not supported
- [Transactional RFC and queued RFC monitoring (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/8b/ceea3b31aac554e10000000a114084/content.htm): SM58 lists only tRFCs that failed or were scheduled as batch jobs; CPICERR retried depending on SM59 settings; SYSFAIL usually program errors; SYSLOAD scheduled as a job; SMQ1 outbound and SMQ2 inbound queues, SMQR and SMQS schedulers; the QOUT scheduler limits parallel connections per destination
- [Transaction Model for Developing BAPIs (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/doc/saphelp_nw73/7.3.16/en-US/4d/5b102ba1483d8fe10000000a42189e/content.htm): The caller controls the transaction; BAPIs don't COMMIT WORK themselves; several BAPIs can be combined in one LUW; a read BAPI sees changes only after COMMIT WORK; no two write accesses to the same instance in one LUW; ended with TransactionCommit/TransactionRollback or BAPI_TRANSACTION_COMMIT/BAPI_TRANSACTION_ROLLBACK; changes through the update task
- [Implementing the Function Module (SAP Help Portal, BAPI programming guide, read 2026-11-30)](https://help.sap.com/saphelp_gbt10/helpdata/en/4d/4f424ab3ee468de10000000a42189c/content.htm): BAPIs must not COMMIT WORK; updates only through the update task because RFC performs an implicit database commit; remote-enabled; no screen output; own authorization checks; no exceptions, all errors in the Return parameter; type A only returned there
- [Unified Connectivity: Concept (SAP Help Portal, SAP NetWeaver 7.4 SP16 library, read 2026-11-30)](https://help.sap.com/doc/saphelp_nw74/7.4.16/en-US/c0/51e93edb9344bb92c986bd9666aecd/content.htm): A remote-enabled function module can be called externally only if it is assigned to a communication assembly linked to a virtual host; others are blocked whatever the user's authorizations; user-context authorization checks still needed; Role Builder scenario
- [RFC callback whitelist (SAP Community, blog post by SAP, read 2026-11-30)](https://community.sap.com/t5/additional-blog-posts-by-sap/rfc-callback-whitelist/ba-p/13227084): DESTINATION 'BACK' inside a synchronous RFC; callbacks only in synchronous RFC; whitelist per destination in SM59 under Logon & Security; as of SAP Basis 7.40, downported to 7.31; rfc/callback_security_method 0 emergency, 1 compatibility (default), 2 simulation, 3 most secure
- [Call a remote function module from the SAP BTP ABAP environment (SAP Developers tutorial, read 2026-11-30)](https://developers.sap.com/tutorials/abap-env-rfc.html): Cloud Connector access control for RFC resources; outbound service of type RFC Service; customer-managed communication scenario, communication system with Cloud Connector, communication arrangement; cl_rfc_destination_provider=>create_by_comm_arrangement then CALL FUNCTION ... DESTINATION; structure rfcsi not released, own types or ACO_PROXY
- [Exploring Clean Core Extensibility Best Practices (SAP Learning, read 2026-11-30)](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-extensibility-model-best-practices_e290f382-800e-40ef-a203-85a13115f487): Levels A to D replace the three tiers; an extension is rated by its lowest-ranked technology; level B classic APIs are upgrade-safe but lack formal stability contracts, example a wrapper around BAPI_PO_CREATE1, exposed for SAP S/4HANA on-premise and SAP ERP; level A aligns with the Public Edition approach; level C internal objects; level D noAPI
- [SAP API Policy v.4.2026a (SAP Help Portal, read 2026-11-30)](https://help.sap.com/doc/sap-api-policy/latest/en-US/API_Policy_latest.pdf): Published APIs are those on the SAP Business Accelerator Hub or in product documentation; non-published APIs may not be used unless documentation or SAP permits, custom ABAP interfaces in private cloud and on-premise given as an example; ban on AI systems that plan API call sequences and on large-scale extraction except through SAP-endorsed architectures; no circumvention through proxies or gateways
