# Cloud Integration flows in depth: design, errors, parameters, versions and review

> Design Cloud Integration flows a review board can approve, covering structure, errors, retries, parameters, versions, transport and reuse, with a checklist.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/cloud-integration-flows-in-depth/
- Updated: 2026-11-29
- Reading time: Foundational 8 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

An **integration flow** is the program inside SAP Integration Suite that moves one kind of message from one system to another. It receives the message, checks and translates it, delivers it, and decides what happens when something goes wrong. SAP's name for the capability that runs these flows is **Cloud Integration**.

Building a flow that works on a good day is quick. The hard part is everything else:

- what happens when the receiving system is down for ten minutes,
- what happens when the sender's data is wrong,
- what stops a retry from creating the same order twice,
- how the flow moves from test to production without someone editing it by hand,
- and how the next developer understands it a year later.

This topic is about those decisions. It uses one interface of Calder Pumpworks, the fictional pump maker used across this course: `I10`, which turns purchase orders from distributors such as Hallam Fluid Systems into sales orders in Calder's S/4HANA system `CP10`. The decision for a leader is simple to state: **no flow goes live until it passes an agreed design review**, and the review checks the failure cases, not the happy path.

### Why it matters to the business

A flow that "works" can still cost money every day. Here is what a weak `I10` flow does to Calder:

- **Orders go to the wrong system.** If the address of the test system is typed into the flow, the flow still runs after it is moved to production. Hallam's orders land in the quality system and nobody ships them.
- **Duplicates.** If the receiving system saves an order but answers too late, a careless retry sends it again. Calder ships 20 seal kits twice and argues about the invoice for a month.
- **Retries of bad data.** A part number nobody mapped will never succeed, however often it is retried. Each retry is a wasted call, a failed message in monitoring and, in the worst case, an alert at 2 a.m. for the integration team about a master data gap that customer service owns.
- **Slow change.** A flow with copied scripts and 30 steps in one block takes days to change safely. Every change risks breaking a neighbor.

The [integration lead's toolkit](https://erpfde.com/topics/the-integration-leads-toolkit/) wrote `I10`'s spec: one hour from distributor order to sales order, six error cases, each with an owner. The flow design is where that spec becomes real. A design review costs a few hours per flow. One duplicate shipment or one day of orders in the wrong system costs more.

### How SAP does it

As of November 2026, these SAP offerings shape how flows are designed and governed. Each is described on the SAP page linked beside it.

- **Cloud Integration** is part of SAP Integration Suite. SAP's [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) lists starter, standard and enhanced editions, and a cap of 10 custom integration flows for one of them. Check which edition you hold, and its caps, before you plan many custom flows.
- **Design guidelines.** SAP publishes [integration flow design guidelines](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/integration-flow-design-guidelines-6803389.md), each with a reference flow you can copy and run. The same guidelines are now [built into the tool as rules](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/IntegrationSettings/design-guidelines-4d1c84f.md): an integration lead switches them on, developers run them against each flow, and the lead reads the report before go-live. They don't change how flows run.
- **Message queues** (the JMS adapter) hold a message so Integration Suite can retry on its own. SAP's documentation says this is [not in the basic edition](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-the-retry-pattern-with-jms-queue-da17d2d.md).
- **Versions and transport.** Flows are saved as numbered versions, and SAP recommends moving them between tenants with the [Transport Management Service or CTS+](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/decision-help-for-choosing-the-right-content-transport-option-19e0e73.md), not by hand.

### What a flow review checks

A review board doesn't need to read the flow's diagram. It needs answers to eight questions. Calder uses this table for every flow.

| Question | A good answer for `I10` | What goes wrong without it |
| --- | --- | --- |
| How does a message get in, and who retries? | The sender hands the order to a queue and gets "accepted"; Integration Suite retries delivery | The distributor's system must resend, and many don't |
| Which errors are business errors, and who owns each? | Unknown sender to the integration team, unknown part and duplicate PO to customer service | Bad data is retried until it gives up, and the wrong team is woken |
| What stops a second order? | A message key and a business key (distributor plus PO number) checked at the receiver | Duplicate shipments and disputed invoices |
| What changes between test and production? | Addresses, credentials and timeouts are parameters set once per tenant | Test addresses in production, or a developer editing production |
| Where are the credentials? | Stored once in Integration Suite and referred to by name | Passwords visible in monitoring or in a copied file |
| How big is each piece? | Small processes, shared logic in shared artifacts | Changes take days and break neighbors |
| How is it released? | A saved version with a change note, moved by the transport service | Nobody can say what runs in production |
| How much does monitoring record? | Basic information in production, detail only in test | Slow tenants, and customer data kept in logs |

> **Note** **For functional consultants.** A reviewed flow changes your work in three places. Error routes create worklists in your area: for `I10`, customer service receives unknown parts and duplicate POs. Test cases must include bad data and repeats, not just a clean order. And cross-references (Hallam's part `HFS-SK-200` is Calder's `CP-SK200`) are master data you maintain, with an owner and a change process.

### Questions to ask

1. Which of our flows have no error route, and who finds out when they fail?
2. For each flow that creates documents, what stops a duplicate if the receiver answers late?
3. Are any addresses or credentials typed into our flows instead of set as parameters?
4. Are design guidelines switched on in our tenants, the same set in each, and who reads the reports?
5. Who may skip a guideline, and where is the reason recorded?
6. How do flows reach production: the transport service, or downloads and uploads by hand?
7. Which edition do we hold, and does it include message queues and enough custom flows for our plan?
8. When SAP's prepackaged flows are copied and changed, who owns the copy?

### Common misconceptions

- **"If it passed the test, it's ready."** Tests usually cover the good day. The review checks the bad days: down systems, wrong data, repeats.
- **"Retry everything, it's safer."** Retrying a message with an unknown part number never helps. Business errors need an owner, not a retry.
- **"The retry setting prevents duplicates."** Retries cause duplicates. Something must recognize a message it has already processed.
- **"We'll fix the addresses after transport."** Editing a flow in production breaks the link between what was tested and what runs. Parameters set per tenant avoid it.
- **"Design guidelines will slow our flows."** SAP states that the guidelines don't affect how flows run; they check the design.

### Key terms

- **Integration flow (iFlow):** a program in Cloud Integration that receives, processes and delivers one kind of message.
- **Adapter:** the part of a flow that speaks one protocol to one system, such as a queue, SOAP or OData.
- **Exception subprocess:** the part of a flow that runs when an unexpected error happens, and decides how the flow ends.
- **Externalized parameter:** a value in a flow, such as an address, that is set per tenant instead of typed into the design.
- **Idempotent receiver:** a receiver that recognizes a message it has already processed and doesn't process it again.
- **Design guidelines:** SAP's rules for robust flows, which the tool can check and report on.
- **Transport:** moving a tested flow version from one tenant to the next, ideally through a transport service.

### Check yourself

1. What should decide whether a new integration flow goes live?
   - A. A successful test with one clean message from the partner
   - B. An agreed review of how the flow behaves on bad days
   - C. The number of steps the developer used to build the flow
   - D. Whether the flow was copied from SAP's prepackaged content

   Answer: B. A flow that works on a good day can still create duplicates or send orders to the wrong system. The review checks the failure cases: down systems, bad data, repeats, and how the flow moves between tenants.

2. Hallam sends an order with a part number Calder has never mapped. What should the flow do?
   - A. Retry it every few minutes until the mapping appears on its own
   - B. Stop and wake the integration team on call at night
   - C. Route it once to the team that owns part cross-references
   - D. Create the order without the line so the rest can ship

   Answer: C. An unknown part is a business error: retrying never fixes it. The spec gives it an owner, customer service, who adds the cross-reference so the message can be processed again.

3. Why do retries make duplicate orders possible?
   - A. Because the queue copies every message twice to be safe
   - B. Because a receiver may save an order but answer too late
   - C. Because SAP charges each retry as a separate message
   - D. Because retries skip the mapping and reach a different client

   Answer: B. If the receiver saves the order and the answer arrives after the flow's timeout, the flow can't tell, and a retry sends it again. Only a key the receiver checks stops the second order.

4. The partner proposes typing the production address into the flow after it is transported. What is the better answer?
   - A. Accept it, as long as the change is written in the release notes
   - B. Keep one tenant for both test and production to avoid the step
   - C. Copy the flow in production and keep the original for testing
   - D. Make the address a parameter and set its value once per tenant

   Answer: D. SAP's guidance is to externalize such values and configure them on each tenant after transport, without editing the model. Later transports don't overwrite configured values, so it is a one-time step.

5. What do SAP's built-in design guidelines do?
   - A. They rewrite flows automatically to follow SAP's rules
   - B. They check flows against rules and give the lead a report
   - C. They block every flow that has a step SAP doesn't recommend
   - D. They slow flows down in production to record compliance

   Answer: B. An integration lead switches guidelines on, developers run them on each flow and the lead reads the report before go-live. SAP states they don't affect how flows run.

6. Calder plans a dozen custom flows on an edition it hasn't checked. What should a leader look at first?
   - A. Whether the partner has built flows in another country before
   - B. Whether SAP will waive the cap for the first year of use
   - C. Whether that edition's custom flow cap and features fit
   - D. Whether the flows can share one queue to stay below the limit

   Answer: C. SAP's pricing page lists a cap of 10 custom integration flows for one edition, and SAP's documentation says message queues aren't in the basic edition. Both decide whether the plan fits the edition you hold.

## Deep layer

### Mental model

A flow makes four promises: **what it accepts**, **what it delivers**, **what happens when it fails**, and **how it changes**. Every design element serves one of them.

- A queue at the start, input checks and a duplicate key keep the first two promises honest.
- Error routes, an exception subprocess, retry limits and alerts keep the third.
- Parameters, versions, transports, naming and reuse keep the fourth.

A reviewer reads a flow by asking which element keeps which promise. If no element does, the promise is broken, however clean the diagram looks. The rest of this topic goes through the elements one promise at a time, then builds a checker and a replay for Calder's `I10` flow.

### How it works

This section explains the parts of a flow as SAP's documentation describes them in November 2026. The [integration styles topic](https://erpfde.com/topics/how-sap-systems-talk/) covers when to choose each style. This topic assumes you have chosen an asynchronous flow through Integration Suite.

#### The parts of a flow

A flow has a **sender** (who starts it) and **receivers** (who it calls), each connected through an **adapter**. Inside, an **integration process** holds the steps: content modifiers that set headers and properties, mappings, routers, splitters, scripts, calls to receivers. Steps can be grouped into **local integration processes**, called with a *Process Call* step. Each process can have one **exception subprocess** for unexpected errors.

Here is the reviewed design for `I10` that you will check later in this topic:

```mermaid
flowchart LR
  B2B[B2B intake flow<br/>EDI from Hallam] -->|JMS queue I10_IN| M
  subgraph M[CPUS_I10_DistributorOrder_Inbound]
    K[Set keys] --> V[Validate<br/>local process]
    V -->|E01 E02 E04| X[Escalation end<br/>owner route]
    V -->|valid| MAP[Map order]
    MAP --> D[Deliver<br/>local process]
    D -->|409| E3[E03 to<br/>customer service]
  end
  D -->|SOAP via Cloud Connector| S4[CP10 S/4HANA]
  M -.->|ProcessDirect| AL[Global_Alert_Notify]
  M -.->|after 5 retries| ERR[Queue I10_ERR]
```

#### Decoupling and retry

SAP's guideline [Relax Dependencies to External Components](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/relax-dependencies-to-external-components-3ea1e33.md) starts from one assumption: the receiver will sometimes be unavailable. Without a plan, the error goes back to the sender, and the sender must resend.

The better pattern, in SAP's [retry guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-the-retry-pattern-with-jms-queue-da17d2d.md), is to store the message in a **JMS queue** at the start. The sender gets HTTP 202 (*Accepted*) at once. A second flow reads the queue and delivers. If delivery fails, the message stays in the queue and the JMS sender adapter retries it. Its settings, with SAP's defaults:

| Setting | Default | What it does |
| --- | --- | --- |
| *Retry Interval* | 1 minute | Wait before the first retry |
| *Exponential Backoff* | On | Doubles the wait after each failed retry |
| *Maximum Retry Interval* | 60 minutes | Caps the doubling |

The adapter has no setting for "stop after N retries". An SAP blog on [retry with JMS](https://community.sap.com/t5/integration-blog-posts/cloud-integration-configure-asynchronous-messaging-with-retry-using-jms/ba-p/13315669) shows the usual design: a router reads the `SAPJMSRetries` header, and above a limit the flow moves the message aside and sends an alert. The author warns the header may overcount when several worker nodes retry at once. Treat the limit as approximate.

Two more choices matter. The [JMS sender adapter](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/configure-the-jms-sender-adapter-161791b.md) offers *Non-Exclusive* access (parallel, no order guaranteed) and *Exclusive* access (strict order, but one failed message blocks the rest). `I10` orders are independent, so Calder uses non-exclusive. And queues are a limited resource: SAP's [resource limits page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/jms-resource-limits-and-optimizing-their-usage-4857054.md) lists 30 queues by default and up to 100 by self-service. A design with two queues per interface uses them up quickly.

#### Expected and unexpected errors

SAP Learning [separates two kinds of error](https://learning.sap.com/learning-journeys/developing-with-sap-integration-suite/performing-exception-handling_c545ebe7-bcf0-4865-8750-df2c51775a4d). **Expected** errors, such as a field value you can check, are handled in the flow's design. **Unexpected** errors, such as a connection failure or a script error, go to the exception subprocess.

For `I10`, the spec's error list splits cleanly:

| Code | Error | Kind | Handled by |
| --- | --- | --- | --- |
| E01 | Unknown sender | Expected | Router in the flow, owner integration team |
| E02 | Unknown part number | Expected | Router after the value mapping, owner customer service |
| E03 | Duplicate customer PO | Expected (found by the receiver) | Router on the receiver's answer, owner customer service |
| E04 | Unknown unit | Expected | Router in the flow, owner integration team |
| E05 | S/4HANA not reachable | Unexpected | Exception subprocess and queue retry |
| E06 | Order blocked for credit | Not an interface error | Order-to-cash worklist |

The [exception subprocess](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/define-exception-subprocess-690e078.md) has rules worth knowing before you design:

- It always starts with an *Error Start* event and ends with *End Message*, *Error End* or an *Escalation* end.
- A router, splitter or aggregator can't be used inside it. Business routing belongs in the main or local process, which is another reason to handle expected errors there.
- **Exceptions of a local integration process can't be caught in the main process.** Each local process needs its own exception subprocess.
- `${exception.message}` and `${exception.stacktrace}` give the error's details inside the subprocess. SAP's page also notes that the message processing log is in an error state even when the subprocess catches the exception, while the error guideline below lists a status per end event. Test which status your tenant shows before you build alerts on it.

The end event decides what monitoring shows. SAP's [error handling guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/handle-errors-gracefully-42c95f7.md) lists *Completed* for a message end, *Failed* for an error end, and *Escalated* for an escalation end. For a queue-fed flow, an error end matters: the failure leaves the message in the queue, so the retry happens. A message end would tell the queue all is well, and the order would be lost. Calder ends business errors with an escalation end: visible, not retried.

#### Exactly once

SAP's page on [quality of service exactly once](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/quality-of-service-exactly-once-f96cf27.md) defines it as two patterns together: **guaranteed delivery** (the queue retries, so a message can arrive more than once) and an **idempotent receiver** (which processes it only once).

Integration Suite offers an [Idempotent Process Call](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/define-idempotent-process-call-84c85d7.md). It records a message ID once a local process has succeeded and skips the process for a repeat. SAP's own note calls it second-best: if the receiver times out, Integration Suite can't know whether the order was saved. IDs are kept for 90 days by default, and each instance of the step keeps its own history, so deleting and remodeling the step forgets everything.

So `I10` sends two keys to the receiver. The **message key** lets the receiver say "I have this message already" and return the same order. The **business key**, distributor plus customer PO, lets it refuse a genuinely new message for an order that exists (E03). The [Unit 4 setup topic](https://erpfde.com/topics/set-up-for-unit-04/) taught the same pair with its local order inbox.

#### Mapping and lookups

SAP Learning [lists the mapping options](https://learning.sap.com/learning-journeys/developing-with-sap-integration-suite/using-mappings_aaf2c8b4-f0ba-4e1f-bdbb-a8445dd0f3a3): message mapping (graphical, from XSD, WSDL, OData metadata or OpenAPI definitions), XSLT mapping, scripts in Groovy or JavaScript, and operation mappings imported from an on-premise Enterprise Services Repository. A message mapping can be tested by simulation; XSLT and scripts need a deployment or outside tools.

For code translations, a [value mapping](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/creating-value-mapping-25eff9b.md) is its own artifact in the package: it says how the same object is identified in two systems. Hallam's `HFS-SK-200` is Calder's `CP-SK200`.

Two cost rules come from SAP's page on [boundary conditions](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/run-an-integration-flow-under-well-defined-boundary-conditions-f8cf974.md). Every step uses CPU and memory, and mappings are among the heaviest. And a call to another system inside a splitter runs once per line: a 40-line order means 40 calls. Look values up from a value mapping, or read them once before the split.

#### Parameters per tenant

A value that differs by landscape (an address, a credential name, a timeout) should be an **externalized parameter**, written `{{S4_ORDER_URL}}` in the field. SAP's guideline [Externalize Volatile Configurations](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/externalize-volatile-configurations-300277d.md) gives the reason: these values change with every landscape, and the person changing them shouldn't need to understand the whole flow.

A parameter has a default value from the design and a configured value set per tenant with *Configure*. An SAP blog on [externalization](https://community.sap.com/t5/technology-blog-posts-by-sap/enrichments-of-externalization-feature-in-sap-cloud-integration/ba-p/13430329) explains that the configured value wins when both exist. SAP's [transport guidance](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/decoupling-development-from-transport-using-externalized-parameters-9064b09.md) adds the part that matters for operations: configured values are set once on the target tenant and are not overwritten by later transports.

Calder's three Integration Suite tenants live in the subaccounts `calder-int-dev`, `calder-int-test` and `calder-int-prod` of the [account model](https://erpfde.com/topics/btp-account-model/), and each stage reaches only its own S/4HANA system. Through the [Cloud Connector](https://erpfde.com/topics/btp-connectivity/), test calls `s4q-api:443` and production calls `s4p-api:443`. A flow whose production address names `s4q-api` breaks that rule, and the checker below fails it without a possible skip.

#### Credentials and logs

Credentials live once in Integration Suite's security material and the flow refers to them by name. SAP's security guideline [Remove Sensitive or Secret Content](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/remove-sensitive-or-secret-content-before-logging-or-forwarding-4686862.md) warns that anything written to the message log is visible in monitoring, and that a list of all headers can include the authorization header. A content modifier that sets `Authorization: Basic ...` puts a password into the design itself.

The [log level](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/setting-log-levels-4e6d3fc.md) sets what monitoring records:

| Level | What it records | Use |
| --- | --- | --- |
| `None` | Nothing | Rarely; no monitoring data |
| `Info` | Basic information; detail on the last 50 steps of failed messages | Production |
| `Error` | Failed messages only | Volume flows; a successful final retry isn't recorded |
| `Debug` | Every step | Development and test only; expires after 24 hours |
| `Trace` | Every step plus message content | Short investigations; expires after 10 minutes by default, content kept 1 hour by default |

#### Versions, transport and naming

*Save* stores a **Draft**. *Save as Version* creates a numbered version with a comment. SAP's [versioning page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/versioning-of-artifacts-cb536a3.md) recommends `major.minor.micro`: a new step raises the micro version, a new process or exception subprocess raises the minor version. Version history belongs to one tenant, so the version number, not the tenant's history, is what links test to production.

For moving versions, SAP's [decision help](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/decision-help-for-choosing-the-right-content-transport-option-19e0e73.md) recommends the cloud **Transport Management Service** (TMS) or **CTS+**, with roles, routes, approvals and logs. Manual export and import, and MTAR download, are for exceptions such as an urgent fix while the transport system is down. The [CI/CD and transport topic](https://erpfde.com/topics/btp-cicd-and-transport/) set up Calder's Cloud Transport Management service; integration content travels on the same service. An [SAP blog on artifact-level transport](https://community.sap.com/t5/technology-blog-posts-by-sap/sap-cloud-integration-transport-at-artifact-level/ba-p/13506764) notes that artifacts in draft state can't be transported.

SAP's [naming conventions](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/naming-conventions-7c00e9b.md) are recommendations: a business unit or the constant `Global`, a scenario, optional systems, CamelCase, and a marker such as `COMMON` for packages of reusable objects. Calder's course rule follows them: `CPUS_I10_DistributorOrder_Inbound`, `Global_Alert_Notify` in package `CAL_Global_ErrorHandling_COMMON`.

#### Reuse

SAP's guideline [Apply a Balanced Encapsulation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-a-balanced-encapsulation-of-the-integration-logics-e010db3.md) offers two tools. **Local integration processes** split one flow into smaller units. Separate flows called through the **ProcessDirect adapter** share logic between flows on the same tenant, with one message processing log per flow, related by a correlation ID. The same page warns that more than 8 nested routes in one process can delay or break deployment.

Scripts used by several flows go into a **script collection**. SAP's page on [consuming a script collection](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/consuming-a-script-collection-1b801fa.md) shows a flow adding a reference under *Resources > References*, including collections from other packages in the tenant. One fix then reaches every flow.

#### Design guidelines in the tool

The built-in [design guidelines](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/IntegrationSettings/design-guidelines-4d1c84f.md) work like this, as of November 2026:

1. An integration lead opens *Settings > Integrations > Design Guidelines*, chooses *Edit* and activates guidelines, weighing each one's severity. A tenant administrator can delegate this with the role `WorkspaceDesignGuidelinesConfigure`.
2. *Export* and *Import* copy the same set to every tenant.
3. Developers run the guidelines in the flow editor. SAP Learning's [lesson on design guidelines](https://learning.sap.com/courses/sap-integration-suite-overview/defining-design-guidelines_f31e433f-0a68-4c30-901b-571d5aa89a0d) adds that a developer may skip a rule with a justification, and that the operations are available through public APIs for CI/CD.
4. The lead reads the report per artifact and decides on go-live.

The checker you build next works the same way, on rules Calder adds for its own landscape.

### Build it yourself: review and replay Calder's I10 flow

You will describe two designs for the `I10` flow as JSON files: the partner's first draft and the reviewed version. A Python script checks each against twelve rules, writes a compliance report like the one SAP's design guidelines produce, and replays seven test messages through each design to show what the rules prevent.

```mermaid
flowchart LR
  I[--init] --> D[i10_draft.json]
  I --> R[i10_reviewed.json]
  I --> M[i10_messages.json]
  D --> C[review<br/>rules F01-F12]
  R --> C
  C --> P[compliance report .md]
  D --> X[run --tenant prod<br/>replay]
  R --> X
  M --> X
  X --> L[run log .jsonl]
```

**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 doesn't repeat their steps, and it needs none of the setup's optional trials.

> **Note** New words. **JSON** is a text format for structured data. A **design file** here is a JSON description of a flow: its adapters, processes, steps, parameters and keys. It is a course format, not SAP's `.iflw` file, so the checker can run on your computer. A **replay** feeds test messages through a model of the design and prints what would happen. It models the design's behavior; it is not SAP's runtime. **Exit code** is the number a program returns when it ends; `2` here means "at least one rule failed", which a pipeline can use to stop a release.

#### 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 Python's built-in modules only and has no randomness, so your output matches the samples below 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/iflow_review.py`.
2. Paste the code below and save.

```python
"""Review and replay a Cloud Integration flow design for Calder's I10 interface.

Course lab for Unit 26 (built-in modules only, no randomness). The flow designs
are JSON descriptions of integration flows, not SAP's own .iflw files. The
replay is a model of how the design behaves, not SAP's runtime.

  python unit26/iflow_review.py --init                       write the draft, the reviewed design and test messages
  python unit26/iflow_review.py review unit26/flows/i10_draft.json      check against rules F01-F12
  python unit26/iflow_review.py run unit26/flows/i10_draft.json --tenant prod   replay the test messages
  python unit26/iflow_review.py --self-test                  check the lab itself
"""
import argparse
import copy
import json
import re
import sys
from pathlib import Path

FOLDER = Path("unit26/flows")
RUN_DATE = "2026-11-29"
STEP_LIMIT = 12          # course rule: steps per process
RETRY_LIMIT_MAX = 5      # course rule: retries before the error queue
MAX_INTERVAL_MIN = 60    # SAP's recommendation for Maximum Retry Interval
TENANT_SYSTEM = {"dev": "S4D", "test": "S4Q", "prod": "S4P"}
HOST_SYSTEM = {"s4d-api": "S4D", "s4q-api": "S4Q", "s4p-api": "S4P"}
PARTNERS = {"HALLAM": "10000002"}            # trading partner profile (course values)
UNITS = {"EA": "PC", "PCE": "PC", "PC": "PC"}  # course code list
CHECK_KINDS = {"sender_known", "part_mapped", "unit_mapped", "date_not_past"}

RULES = {
    "F01": "Every integration process and local process has an exception subprocess",
    "F02": "Expected business errors are routed in the flow to an owner, not retried",
    "F03": "Asynchronous inbound is decoupled by a JMS queue with bounded retry",
    "F04": "A flow that creates documents sends an idempotency key and a business key",
    "F05": "Volatile receiver properties are externalized parameters",
    "F06": "Every parameter is configured per tenant; production names only production",
    "F07": "No credentials in headers, properties, parameters or scripts",
    "F08": "No external call inside a split or loop; use a lookup",
    "F09": f"At most {STEP_LIMIT} steps per process",
    "F10": "No unused steps",
    "F11": "Shared scripts live in a script collection; shared logic is called over ProcessDirect",
    "F12": "Released as a saved version with a change note; production log level Info",
}
NO_SKIP = {"F06", "F07"}   # course rule: security and stage rules can't be skipped

DRAFT = {
    "package": "CAL_CPUS_DistributorOrders",
    "flows": [{
        "id": "I10 orders final v2",
        "status": "draft", "version": None, "change_note": "",
        "log_level": {"test": "Debug", "prod": "Debug"},
        "sender": {"adapter": "HTTPS", "path": "/i10/orders", "resend_after_min": 5, "resends": 3},
        "receiver": {"adapter": "SOAP", "address": "http://s4q-api:443/sap/course/i10/orders",
                     "credential": "TU_I10_ORDERS", "timeout_ms": "30000",
                     "proxy": "OnPremise", "location_id": "RK"},
        "keys": [],
        "checks": [],
        "processes": [{
            "name": "Integration Process", "type": "integration", "exception_subprocess": False,
            "steps": ["Start", "Content Modifier: set headers", "Groovy: normalizeUnit",
                      "Groovy: log payload", "General Splitter: lines",
                      "Request Reply: partner part lookup", "Content Modifier: part",
                      "Gather", "Message Mapping: order", "Groovy: normalizeDates",
                      "Content Modifier: auth header", "Request Reply: S/4HANA",
                      "Content Modifier: response", "Groovy: log response",
                      "Router: status", "Content Modifier: old_header_test", "End"],
            "unused_steps": ["Content Modifier: old_header_test"],
            "calls_in_loop": ["Request Reply: partner part lookup"],
            "headers": {"Authorization": "Basic dHVfaTEwOkNhbGRlcjIwMjY="}}],
        "scripts": [{"name": "normalizeUnit.groovy", "source": "inline"},
                    {"name": "normalizeDates.groovy", "source": "inline"}],
        "processdirect_calls": [],
    }, {
        "id": "I11 ic orders",
        "status": "version", "version": "1.0.0", "change_note": "first release",
        "log_level": {"test": "Info", "prod": "Info"},
        "sender": {"adapter": "JMS", "queue": "I11_IN", "retry_interval_min": 1,
                   "exponential_backoff": True, "max_retry_interval_min": 60,
                   "retry_limit": 5, "on_limit": "I11_ERR"},
        "receiver": None, "keys": ["idempotency", "business"],
        "checks": [{"code": "E01", "check": "sender_known", "action": "escalate", "owner": "Intercompany team"}],
        "processes": [{"name": "Integration Process", "type": "integration", "exception_subprocess": True,
                       "steps": ["Start", "Groovy: normalizeUnit", "Message Mapping", "End"],
                       "unused_steps": [], "calls_in_loop": [], "headers": {}}],
        "scripts": [{"name": "normalizeUnit.groovy", "source": "inline"}],
        "processdirect_calls": [],
    }],
    "script_collections": [],
    "value_mappings": [],
    "parameters": {},
    "skips": {},
}


def reviewed_design():
    d = copy.deepcopy(DRAFT)
    i10 = {
        "id": "CPUS_I10_DistributorOrder_Inbound",
        "status": "version", "version": "1.0.0",
        "change_note": "1.0.0: JMS decoupling, business routes E01-E04, keys, parameters, script collection",
        "log_level": {"test": "Info", "prod": "Info"},
        "sender": {"adapter": "JMS", "queue": "I10_IN", "retry_interval_min": 1,
                   "exponential_backoff": True, "max_retry_interval_min": 60,
                   "retry_limit": 5, "on_limit": "I10_ERR"},
        "receiver": {"adapter": "SOAP", "address": "{{S4_ORDER_URL}}",
                     "credential": "{{S4_CREDENTIAL}}", "timeout_ms": "{{S4_TIMEOUT_MS}}",
                     "proxy": "OnPremise", "location_id": "{{SCC_LOCATION_ID}}"},
        "keys": ["idempotency", "business"],
        "checks": [
            {"code": "E01", "check": "sender_known", "action": "escalate", "owner": "Integration team"},
            {"code": "E02", "check": "part_mapped", "action": "escalate", "owner": "Customer service"},
            {"code": "E04", "check": "unit_mapped", "action": "escalate", "owner": "Integration team"}],
        "processes": [
            {"name": "Integration Process", "type": "integration", "exception_subprocess": True,
             "steps": ["Start", "Content Modifier: keys", "Process Call: Validate",
                       "Router: valid?", "Message Mapping: order", "Process Call: Deliver",
                       "End", "Escalation End: business error"],
             "unused_steps": [], "calls_in_loop": [], "headers": {}},
            {"name": "Validate", "type": "local", "exception_subprocess": True,
             "steps": ["Start", "Groovy: normalizeUnit", "Value Mapping: partner part",
                       "Router: E01/E02/E04", "End"],
             "unused_steps": [], "calls_in_loop": [], "headers": {}},
            {"name": "Deliver", "type": "local", "exception_subprocess": True,
             "steps": ["Start", "Request Reply: S/4HANA", "Router: 2xx/409/other",
                       "Escalation End: E03 duplicate", "End"],
             "unused_steps": [], "calls_in_loop": [], "headers": {}}],
        "scripts": [{"name": "normalizeUnit.groovy", "source": "SC_Calder_Common"}],
        "processdirect_calls": ["/calder/common/alert"],
    }
    d["flows"][0] = i10
    d["flows"][1]["id"] = "CPUS_I11_IntercompanyOrder_Inbound"
    d["flows"][1]["scripts"] = [{"name": "normalizeUnit.groovy", "source": "SC_Calder_Common"}]
    d["flows"].append({
        "id": "Global_Alert_Notify", "package": "CAL_Global_ErrorHandling_COMMON", "status": "version", "version": "1.0.0",
        "change_note": "1.0.0: one alert flow for every interface",
        "log_level": {"test": "Info", "prod": "Info"},
        "sender": {"adapter": "ProcessDirect", "path": "/calder/common/alert"},
        "receiver": {"adapter": "Mail", "address": "{{ALERT_MAILBOX}}", "credential": "{{MAIL_CREDENTIAL}}",
                     "timeout_ms": "{{MAIL_TIMEOUT_MS}}", "proxy": "Internet", "location_id": ""},
        "keys": [], "checks": [],
        "processes": [{"name": "Integration Process", "type": "integration", "exception_subprocess": True,
                       "steps": ["Start", "Content Modifier: alert text", "Send: mail", "End"],
                       "unused_steps": [], "calls_in_loop": [], "headers": {}}],
        "scripts": [], "processdirect_calls": []})
    d["script_collections"] = [{"id": "SC_Calder_Common", "scripts": ["normalizeUnit.groovy"]}]
    d["value_mappings"] = [{"id": "VM_Calder_PartnerParts",
                            "entries": {"HALLAM|HFS-SK-200": "CP-SK200", "HALLAM|HFS-P200": "CP-ES200"}}]
    d["parameters"] = {
        "S4_ORDER_URL": {"configured": {"test": "http://s4q-api:443/sap/course/i10/orders",
                                        "prod": "http://s4p-api:443/sap/course/i10/orders"}},
        "S4_CREDENTIAL": {"configured": {"test": "I10_S4Q_OAUTH", "prod": "I10_S4P_OAUTH"}},
        "S4_TIMEOUT_MS": {"configured": {"test": "30000", "prod": "30000"}},
        "SCC_LOCATION_ID": {"configured": {"test": "RK", "prod": "RK"}},
        "ALERT_MAILBOX": {"configured": {"test": "int-test-alerts@calder-pumpworks.example",
                                         "prod": "int-oncall@calder-pumpworks.example"}},
        "MAIL_CREDENTIAL": {"configured": {"test": "MAIL_ALERTS", "prod": "MAIL_ALERTS"}},
        "MAIL_TIMEOUT_MS": {"configured": {"test": "10000", "prod": "10000"}},
    }
    d["skips"] = {"F03": {"flow": "Global_Alert_Notify",
                          "reason": "Called over ProcessDirect inside the caller's processing; the caller's queue retries",
                          "by": "00100292"}}
    return d


MESSAGES = [
    {"id": "HFS-PO-7781", "sender": "HALLAM", "customer_po": "HFS-PO-7781", "requested": "2026-12-14",
     "lines": [{"part": "HFS-SK-200", "qty": 60, "unit": "EA"}]},
    {"id": "HFS-PO-7790", "sender": "HALLAM", "customer_po": "HFS-PO-7790", "requested": "2026-12-18",
     "lines": [{"part": "HFS-P200", "qty": 4, "unit": "EA"}], "fault": {"unavailable": 2}},
    {"id": "HFS-PO-7816", "sender": "HALLAM", "customer_po": "HFS-PO-7816", "requested": "2026-12-21",
     "lines": [{"part": "HFS-SK-200", "qty": 20, "unit": "PCE"}], "fault": {"late_answer": True}},
    {"id": "XYZ-PO-0001", "sender": "XYZ", "customer_po": "XYZ-PO-0001", "requested": "2026-12-15",
     "lines": [{"part": "XYZ-1", "qty": 1, "unit": "EA"}]},
    {"id": "HFS-PO-8102", "sender": "HALLAM", "customer_po": "HFS-PO-8102", "requested": "2026-12-16",
     "lines": [{"part": "HFS-SK-210", "qty": 30, "unit": "EA"}]},
    {"id": "HFS-PO-8109", "sender": "HALLAM", "customer_po": "HFS-PO-8109", "requested": "2026-12-16",
     "lines": [{"part": "HFS-SK-200", "qty": 2, "unit": "BX"}]},
    {"id": "HFS-PO-7781-R", "sender": "HALLAM", "customer_po": "HFS-PO-7781", "requested": "2026-12-14",
     "lines": [{"part": "HFS-SK-200", "qty": 60, "unit": "EA"}], "note": "distributor sent the same PO again"},
]


def load(path):
    p = Path(path)
    if not p.exists():
        sys.exit(f"{p} not found. Run: python unit26/iflow_review.py --init")
    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 init():
    FOLDER.mkdir(parents=True, exist_ok=True)
    for name, data in [("i10_draft.json", DRAFT), ("i10_reviewed.json", reviewed_design()),
                       ("i10_messages.json", MESSAGES)]:
        p = FOLDER / name
        if p.exists():
            print(f"{p} already exists; delete it first to get the sample back")
            continue
        p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {p}")


def params_in(value):
    return re.findall(r"\{\{(\w+)\}\}", value or "")


def resolve(value, design, tenant):
    for name in params_in(value):
        conf = design["parameters"].get(name, {}).get("configured", {})
        value = value.replace("{{%s}}" % name, conf.get(tenant, conf.get("default", "")))
    return value


def system_of(address):
    host = re.sub(r"^\w+://", "", address or "").split(":")[0].split("/")[0]
    return HOST_SYSTEM.get(host, "?")


def check_flow(f, design):
    """Yield (rule, verdict, reason) for one flow."""
    procs = f["processes"]
    creates = f["receiver"] is not None and f["receiver"]["adapter"] != "Mail"
    missing = [p["name"] for p in procs if not p["exception_subprocess"]]
    yield "F01", "FAIL" if missing else "OK", f"no exception subprocess in {', '.join(missing)}" if missing else "all processes"

    if creates:
        codes = {c["code"] for c in f["checks"] if c.get("owner")}
        need = {"E01", "E02", "E04"} - codes
        bad = [c["check"] for c in f["checks"] if c["check"] not in CHECK_KINDS]
        if bad:
            yield "F02", "FAIL", f"unknown check kind {', '.join(bad)}"
        elif need:
            yield "F02", "FAIL", f"no route with an owner for {', '.join(sorted(need))}; they fail and get retried"
        else:
            yield "F02", "OK", f"routes {', '.join(sorted(codes))}"
    s = f["sender"]
    if s["adapter"] == "ProcessDirect":
        yield "F03", "FAIL", "no queue of its own (needs a justified skip)"
    elif s["adapter"] != "JMS":
        yield "F03", "FAIL", f"{s['adapter']} sender: the caller resends, nothing bounds or records retries"
    else:
        probs = []
        if not s.get("exponential_backoff"):
            probs.append("no exponential backoff")
        if s.get("max_retry_interval_min", 0) > MAX_INTERVAL_MIN:
            probs.append("maximum interval above 60 min")
        if not s.get("retry_limit") or s["retry_limit"] > RETRY_LIMIT_MAX or not s.get("on_limit"):
            probs.append(f"no retry limit of {RETRY_LIMIT_MAX} or fewer with an error queue")
        yield "F03", "WARN" if probs else "OK", "; ".join(probs) or f"queue {s['queue']}, limit {s['retry_limit']}, then {s['on_limit']}"
    if creates:
        miss = {"idempotency", "business"} - set(f["keys"])
        yield "F04", "FAIL" if miss else "OK", f"no {' or '.join(sorted(miss))} key: a retry can create a second order" if miss else "both keys"

    r = f["receiver"]
    if r:
        literal = [k for k in ("address", "credential", "timeout_ms") if not params_in(r.get(k))]
        yield "F05", "FAIL" if literal else "OK", f"typed in: {', '.join(literal)}" if literal else "address, credential and timeout"
        names = [n for k in ("address", "credential", "timeout_ms", "location_id") for n in params_in(r.get(k))]
        probs = []
        for n in names:
            conf = design["parameters"].get(n, {}).get("configured", {})
            for t in ("test", "prod"):
                if t not in conf:
                    probs.append(f"{n} not configured in {t}")
        for t in ("test", "prod"):
            sysid = system_of(resolve(r["address"], design, t))
            if r["adapter"] != "Mail" and sysid != TENANT_SYSTEM[t]:
                probs.append(f"{t} tenant reaches {sysid}")
        good = "configured in test and prod" if r["adapter"] == "Mail" else "test reaches S4Q, prod reaches S4P"
        yield "F06", "FAIL" if probs else "OK", "; ".join(probs) or good

    leaks = []
    for p in procs:
        for k, v in p.get("headers", {}).items():
            if re.match(r"(Basic|Bearer) ", str(v)) or re.search(r"pass|secret", k, re.I):
                leaks.append(f"{k} header in {p['name']}")
    for n, par in design["parameters"].items():
        if re.search(r"pass|secret", n, re.I):
            leaks.append(f"parameter {n}")
    yield "F07", "FAIL" if leaks else "OK", "; ".join(leaks) or "credentials by name only"

    loops = [c for p in procs for c in p["calls_in_loop"]]
    yield "F08", "FAIL" if loops else "OK", f"{', '.join(loops)} runs once per line" if loops else "no calls in loops"
    big = [f"{p['name']} {len(p['steps'])}" for p in procs if len(p["steps"]) > STEP_LIMIT]
    yield "F09", "WARN" if big else "OK", f"steps: {', '.join(big)}" if big else f"largest {max(len(p['steps']) for p in procs)}"
    unused = [u for p in procs for u in p["unused_steps"]]
    yield "F10", "WARN" if unused else "OK", ", ".join(unused) or "none"

    probs = []
    for sc in f["scripts"]:
        if sc["source"] == "inline":
            others = [g["id"] for g in design["flows"] if g is not f and
                      any(x["name"] == sc["name"] for x in g["scripts"])]
            if others:
                probs.append(f"{sc['name']} copied in {', '.join(others)}")
        elif sc["source"] not in {c["id"] for c in design["script_collections"]}:
            probs.append(f"{sc['name']} points at missing {sc['source']}")
    for path in f["processdirect_calls"]:
        if not any(g["sender"].get("path") == path and g["sender"]["adapter"] == "ProcessDirect" for g in design["flows"]):
            probs.append(f"no flow listens on ProcessDirect {path}")
    yield "F11", "WARN" if probs else "OK", "; ".join(probs) or "no copies"

    probs = []
    if f["status"] != "version" or not re.fullmatch(r"\d+\.\d+\.\d+", f.get("version") or ""):
        probs.append("draft, no version: can't be transported")
    elif not f.get("change_note"):
        probs.append("no change note")
    if f["log_level"].get("prod") != "Info":
        probs.append(f"production log level {f['log_level'].get('prod')}")
    if not re.fullmatch(r"(CPUS|CPDE|Global)_[A-Za-z0-9]+(_[A-Za-z0-9]+)*", f["id"]):
        probs.append("name doesn't follow <unit or Global>_<interface>_<object>_<direction>")
    yield "F12", "FAIL" if probs else "OK", "; ".join(probs) or f"{f['version']}, Info"


def review(path, quiet=False):
    design = load(path)
    rows = []
    for f in design["flows"]:
        for rule, verdict, reason in check_flow(f, design):
            skip = design.get("skips", {}).get(rule)
            if verdict != "OK" and skip and skip.get("flow") == f["id"]:
                if rule in NO_SKIP:
                    reason += " (skip refused: rule can't be skipped)"
                else:
                    verdict, reason = "SKIPPED", f"{reason}; skipped by {skip['by']}: {skip['reason']}"
            rows.append((f["id"], rule, verdict, reason))
    counts = {v: sum(1 for r in rows if r[2] == v) for v in ("OK", "WARN", "FAIL", "SKIPPED")}
    summary = f"{len(rows)} checks: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL, {counts['SKIPPED']} SKIPPED"
    if not quiet:
        last = None
        for flow, rule, verdict, reason in rows:
            if flow != last:
                print(f"\n{flow}")
                last = flow
            print(f"  {rule} {verdict:<7} {reason}")
        print("\n" + summary)
        out = Path(path).with_name("compliance_" + Path(path).stem + ".md")
        lines = [f"# Compliance report: {design['package']}", "", f"Design file `{path}`, checked {RUN_DATE}.", "",
                 "| Flow | Rule | Result | Reason |", "| --- | --- | --- | --- |"]
        lines += [f"| {a} | {b} {RULES[b]} | {c} | {d} |" for a, b, c, d in rows]
        lines += ["", summary, "", "Decision: go live / fix first (circle one). Signed: ________"]
        out.write_text("\n".join(lines) + "\n", encoding="utf-8")
        print(f"Wrote {out}")
    return rows, counts


class StandIn:
    """A stand-in for S/4HANA's order inbound: idempotency key and business key checks."""
    def __init__(self):
        self.next_no, self.by_key, self.by_po, self.orders = 1000601, {}, {}, []

    def post(self, system, msg, keys, attempt):
        fault = msg.get("fault", {})
        if attempt < fault.get("unavailable", 0):
            return 503, None
        if "idempotency" in keys and msg["id"] in self.by_key:
            return 200, self.by_key[msg["id"]]
        po = (system, msg["sender"], msg["customer_po"])
        if "business" in keys and po in self.by_po:
            return 409, self.by_po[po]
        if msg["sender"] not in PARTNERS or any(l["unit"] not in UNITS for l in msg["lines"]) or \
                any(f"{msg['sender']}|{l['part']}" not in KNOWN_PARTS for l in msg["lines"]):
            return 400, None
        no = self.next_no
        self.next_no += 1
        self.orders.append((system, no, msg["customer_po"]))
        self.by_key[msg["id"]] = no
        self.by_po[po] = no
        if fault.get("late_answer") and attempt == 0:
            return 504, None   # saved, but the answer came after the flow's timeout
        return 201, no


KNOWN_PARTS = {"HALLAM|HFS-SK-200", "HALLAM|HFS-P200"}


def business_error(f, design, msg):
    vm, flags = {}, []
    for v in design["value_mappings"]:
        vm.update(v["entries"])
    for c in f["checks"]:
        ok = True
        if c["check"] == "sender_known":
            ok = msg["sender"] in PARTNERS
        elif c["check"] == "part_mapped":
            ok = all(f"{msg['sender']}|{l['part']}" in vm for l in msg["lines"])
        elif c["check"] == "unit_mapped":
            ok = all(l["unit"] in UNITS for l in msg["lines"])
        elif c["check"] == "date_not_past":
            ok = msg["requested"] >= RUN_DATE
        if not ok and c["action"] == "escalate":
            return c, []
        if not ok:
            flags.append(c)
    return None, flags


def run(path, tenant, quiet=False):
    design = load(path)
    msgs = load(FOLDER / "i10_messages.json")
    f = design["flows"][0]
    s4 = StandIn()
    system = system_of(resolve(f["receiver"]["address"], design, tenant))
    jms = f["sender"]["adapter"] == "JMS"
    results = []
    for m in msgs:
        calls = wasted = minutes = 0
        err, soft = business_error(f, design, m)
        if err:
            results.append((m["id"], f"ESCALATED {err['code']} to {err['owner']}", 0, 0, 0))
            continue
        flags = [f"flagged {c['code']} for {c['owner']}" for c in soft]
        tries = 1 + (f["sender"]["retry_limit"] if jms else f["sender"]["resends"])
        interval = f["sender"].get("retry_interval_min", f["sender"].get("resend_after_min", 5))
        outcome = None
        for attempt in range(tries):
            calls += 1
            status, no = s4.post(system, m, f["keys"], attempt)
            if status in (200, 201):
                outcome = f"ORDER {no} in {system}" + (" (already saved, same message)" if status == 200 else "")
                break
            if status == 409:
                outcome = f"ESCALATED E03 to Customer service (order {no} exists)"
                break
            if status == 400:
                wasted += 1
            if attempt < tries - 1:
                minutes += interval
                if jms and f["sender"].get("exponential_backoff"):
                    interval = min(interval * 2, f["sender"].get("max_retry_interval_min", 60))
        if outcome is None:
            outcome = f"FAILED, in {f['sender']['on_limit']} with an alert" if jms else "FAILED, partner resent and gave up"
        results.append((m["id"], "; ".join([outcome] + flags), calls, wasted, minutes))
    orders = {}
    for sysid, no, po in s4.orders:
        orders.setdefault(sysid, []).append(po)
    dupes = sum(len(v) - len(set(v)) for v in orders.values())
    if not quiet:
        print(f"Replay of {len(msgs)} messages through {f['id']} in the {tenant} tenant (expected system {TENANT_SYSTEM[tenant]})\n")
        print(f"  {'message':<15} {'calls':>5} {'wasted':>6} {'waited':>6}  outcome")
        for mid, out, c, w, mins in results:
            print(f"  {mid:<15} {c:>5} {w:>6} {mins:>4} m  {out}")
        made = ", ".join(f"{k}: {len(v)}" for k, v in sorted(orders.items())) or "none"
        print(f"\nOrders created: {made}; duplicates: {dupes}; calls: {sum(r[2] for r in results)}, "
              f"wasted on business errors: {sum(r[3] for r in results)}")
        log = Path(path).with_name(f"run_{Path(path).stem}_{tenant}.jsonl")
        log.write_text("".join(json.dumps({"message": r[0], "outcome": r[1], "calls": r[2], "wasted": r[3],
                                           "waited_min": r[4], "tenant": tenant}) + "\n" for r in results), encoding="utf-8")
        print(f"Wrote {log}")
    return results, orders, dupes


def self_test():
    import tempfile, os
    here = Path.cwd()
    with tempfile.TemporaryDirectory() as tmp:
        os.chdir(tmp)
        try:
            init_quiet = sys.stdout
            sys.stdout = open(os.devnull, "w")
            init()
            sys.stdout = init_quiet
            _, c = review(FOLDER / "i10_draft.json", quiet=True)
            assert c["FAIL"] > 0, "draft should fail"
            _, c = review(FOLDER / "i10_reviewed.json", quiet=True)
            assert c["FAIL"] == 0 and c["WARN"] == 0, c
            _, orders, dupes = run(FOLDER / "i10_draft.json", "prod", quiet=True)
            assert "S4P" not in orders and dupes > 0
            res, orders, dupes = run(FOLDER / "i10_reviewed.json", "prod", quiet=True)
            assert len(orders["S4P"]) == 3 and dupes == 0 and sum(r[3] for r in res) == 0
        finally:
            os.chdir(here)
    print("Self-test OK: draft fails, reviewed passes, replay matches")


def main():
    ap = argparse.ArgumentParser(description="Review and replay Calder's I10 integration flow design")
    ap.add_argument("command", nargs="?", choices=["review", "run"])
    ap.add_argument("file", nargs="?")
    ap.add_argument("--tenant", choices=["test", "prod"], default="prod")
    ap.add_argument("--init", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.init:
        init()
    elif a.self_test:
        self_test()
    elif a.command == "review" and a.file:
        _, c = review(a.file)
        sys.exit(2 if c["FAIL"] else 0)
    elif a.command == "run" and a.file:
        run(a.file, a.tenant)
    else:
        ap.print_help()


if __name__ == "__main__":
    main()
```

#### Step 3: Write the two designs and the test messages

1. Run:

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

2. You see:

   ```text
   Wrote unit26/flows/i10_draft.json
   Wrote unit26/flows/i10_reviewed.json
   Wrote unit26/flows/i10_messages.json
   ```

3. Open `unit26/flows/i10_draft.json`. This is the partner's first `I10` flow, plus an intercompany flow (`I11`) that shares one script with it. Look for the receiver `address`: the test system's host `s4q-api` is typed in. Look for `headers`: a content modifier sets a password in an `Authorization` header.
4. Open `unit26/flows/i10_messages.json`. The seven test messages come from the `I10` spec: a clean order (`HFS-PO-7781`), an order while S/4HANA is down twice (`HFS-PO-7790`), an order the receiver saves but answers too late (`HFS-PO-7816`), an unknown sender (`XYZ-PO-0001`), an unknown part (`HFS-PO-8102`), an unknown unit (`HFS-PO-8109`) and Hallam sending `HFS-PO-7781` again.

#### Step 4: Review the draft

1. Run:

   ```bash
   python unit26/iflow_review.py review unit26/flows/i10_draft.json
   ```

2. You see:

   ```text
   I10 orders final v2
     F01 FAIL    no exception subprocess in Integration Process
     F02 FAIL    no route with an owner for E01, E02, E04; they fail and get retried
     F03 FAIL    HTTPS sender: the caller resends, nothing bounds or records retries
     F04 FAIL    no business or idempotency key: a retry can create a second order
     F05 FAIL    typed in: address, credential, timeout_ms
     F06 FAIL    prod tenant reaches S4Q
     F07 FAIL    Authorization header in Integration Process
     F08 FAIL    Request Reply: partner part lookup runs once per line
     F09 WARN    steps: Integration Process 17
     F10 WARN    Content Modifier: old_header_test
     F11 WARN    normalizeUnit.groovy copied in I11 ic orders
     F12 FAIL    draft, no version: can't be transported; production log level Debug; name doesn't follow <unit or Global>_<interface>_<object>_<direction>

   I11 ic orders
     F01 OK      all processes
     F03 OK      queue I11_IN, limit 5, then I11_ERR
     F07 OK      credentials by name only
     F08 OK      no calls in loops
     F09 OK      largest 4
     F10 OK      none
     F11 WARN    normalizeUnit.groovy copied in I10 orders final v2
     F12 FAIL    name doesn't follow <unit or Global>_<interface>_<object>_<direction>

   20 checks: 6 OK, 4 WARN, 10 FAIL, 0 SKIPPED
   Wrote unit26/flows/compliance_i10_draft.md
   ```

3. Read the failures in the order a board would: F06 and F07 first (production orders reach the quality system, a password sits in the design), then F02 to F04 (errors, retries, duplicates), then the rest.
4. The script ends with exit code 2. In a pipeline, that stops the release.

#### Step 5: Replay the draft in production

1. Run:

   ```bash
   python unit26/iflow_review.py run unit26/flows/i10_draft.json --tenant prod
   ```

2. You see:

   ```text
   Replay of 7 messages through I10 orders final v2 in the prod tenant (expected system S4P)

     message         calls wasted waited  outcome
     HFS-PO-7781         1      0    0 m  ORDER 1000601 in S4Q
     HFS-PO-7790         3      0   10 m  ORDER 1000602 in S4Q
     HFS-PO-7816         2      0    5 m  ORDER 1000604 in S4Q
     XYZ-PO-0001         4      4   15 m  FAILED, partner resent and gave up
     HFS-PO-8102         4      4   15 m  FAILED, partner resent and gave up
     HFS-PO-8109         4      4   15 m  FAILED, partner resent and gave up
     HFS-PO-7781-R       1      0    0 m  ORDER 1000605 in S4Q

   Orders created: S4Q: 5; duplicates: 2; calls: 19, wasted on business errors: 12
   Wrote unit26/flows/run_i10_draft_prod.jsonl
   ```

3. Read it against the review. Every order went to `S4Q`, the quality system, although the flow ran in production (F05, F06). `HFS-PO-7816` made two orders, `1000603` (saved, but answered late) and `1000604` (the resend), because nothing told the receiver it was the same message (F04). Hallam's repeat of `HFS-PO-7781` became a second order too. The three bad messages were sent four times each, and the distributor's system did the retrying (F02, F03).

> **Note** These counts come from made-up test messages and a model of the design. They show the method, not results from a real SAP system.

#### Step 6: Review the reviewed design

1. Run:

   ```bash
   python unit26/iflow_review.py review unit26/flows/i10_reviewed.json
   ```

2. You see:

   ```text
   CPUS_I10_DistributorOrder_Inbound
     F01 OK      all processes
     F02 OK      routes E01, E02, E04
     F03 OK      queue I10_IN, limit 5, then I10_ERR
     F04 OK      both keys
     F05 OK      address, credential and timeout
     F06 OK      test reaches S4Q, prod reaches S4P
     F07 OK      credentials by name only
     F08 OK      no calls in loops
     F09 OK      largest 8
     F10 OK      none
     F11 OK      no copies
     F12 OK      1.0.0, Info

   CPUS_I11_IntercompanyOrder_Inbound
     F01 OK      all processes
     F03 OK      queue I11_IN, limit 5, then I11_ERR
     F07 OK      credentials by name only
     F08 OK      no calls in loops
     F09 OK      largest 4
     F10 OK      none
     F11 OK      no copies
     F12 OK      1.0.0, Info

   Global_Alert_Notify
     F01 OK      all processes
     F03 SKIPPED no queue of its own (needs a justified skip); skipped by 00100292: Called over ProcessDirect inside the caller's processing; the caller's queue retries
     F05 OK      address, credential and timeout
     F06 OK      configured in test and prod
     F07 OK      credentials by name only
     F08 OK      no calls in loops
     F09 OK      largest 4
     F10 OK      none
     F11 OK      no copies
     F12 OK      1.0.0, Info

   30 checks: 29 OK, 0 WARN, 0 FAIL, 1 SKIPPED
   Wrote unit26/flows/compliance_i10_reviewed.md
   ```

3. One rule is skipped, not passed. The shared alert flow has no queue of its own, and the integration lead `00100292` recorded why: it runs inside the calling flow, whose queue retries. That is how SAP's tool handles a justified exception too. F06 and F07 can't be skipped: the script refuses a skip on them, because a stage rule or a credential rule with an exception is no rule.

#### Step 7: Replay the reviewed design

1. Run it in production, then in test:

   ```bash
   python unit26/iflow_review.py run unit26/flows/i10_reviewed.json --tenant prod
   python unit26/iflow_review.py run unit26/flows/i10_reviewed.json --tenant test
   ```

2. The production run prints:

   ```text
   Replay of 7 messages through CPUS_I10_DistributorOrder_Inbound in the prod tenant (expected system S4P)

     message         calls wasted waited  outcome
     HFS-PO-7781         1      0    0 m  ORDER 1000601 in S4P
     HFS-PO-7790         3      0    3 m  ORDER 1000602 in S4P
     HFS-PO-7816         2      0    1 m  ORDER 1000603 in S4P (already saved, same message)
     XYZ-PO-0001         0      0    0 m  ESCALATED E01 to Integration team
     HFS-PO-8102         0      0    0 m  ESCALATED E02 to Customer service
     HFS-PO-8109         0      0    0 m  ESCALATED E04 to Integration team
     HFS-PO-7781-R       1      0    0 m  ESCALATED E03 to Customer service (order 1000601 exists)

   Orders created: S4P: 3; duplicates: 0; calls: 7, wasted on business errors: 0
   Wrote unit26/flows/run_i10_reviewed_prod.jsonl
   ```

3. The test run shows the same outcomes with `S4Q` in place of `S4P`: one design, two tenants, two configured values.
4. Compare with Step 5. Three orders, all in `S4P`, no duplicates. `HFS-PO-7790` waited 3 minutes (1 then 2, the exponential backoff) instead of the draft's 10. `HFS-PO-7816`'s retry found the order already saved and returned it. The three bad messages never reached S/4HANA and went once to their owners. Hallam's repeat was refused as E03 and sent to customer service.

> **Note** These results come from synthetic test messages and a model of the design, not from SAP's runtime or a real S/4HANA system. The order numbers from `1000601` are course values.

#### Step 8: Sign the compliance report

1. Open `unit26/flows/compliance_i10_reviewed.md` and choose **Open Preview** (`Ctrl+Shift+V` on Windows, `Cmd+Shift+V` on macOS).
2. You see one table row per flow and rule, the summary line and an empty decision line.
3. Write the go-live decision and your name, as the integration lead would. Keep the draft's report too: it shows what the review caught.

#### Step 9 (optional): Run SAP's reference flows in a trial

If you have an Integration Suite trial from [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/), you can open SAP's own reference flows. SAP's [tutorial](https://developers.sap.com/tutorials/btp-integration-suite-design-guidelines.html), read on 29 November 2026, describes the path:

1. In Integration Suite, choose **Discover > Integrations** and search for *integration flow design guidelines*.
2. Open the package **Learn the Basics** and choose **Copy**.
3. Choose **Design > Integrations and APIs**, open the copied package and its **Artifacts** tab.
4. Open a flow, choose **Deploy**, and confirm the transaction handling prompt.
5. Under **Monitor > Integrations and APIs**, check that it shows *Started*.

The packages for the other guidelines, such as *Integration Flow Design Guidelines - Handle Errors Gracefully*, are found the same way. Compare their exception subprocesses with Calder's reviewed design.

#### Step 10: Save your work

```bash
git add unit26/iflow_review.py unit26/flows/
git commit -m "Unit 26: I10 flow review and replay"
```

#### How the code works

| Part | What it does |
| --- | --- |
| Constants and `RULES` | The twelve rules, Calder's tenants and hosts, the course code list and the trading partner table |
| `DRAFT`, `reviewed_design()` | The partner's draft and the reviewed design; the second starts from the first and applies the fixes |
| `MESSAGES` | Seven test messages from the `I10` spec, with faults for an outage and a late answer |
| `check_flow()` | One block per rule; each yields OK, WARN or FAIL with a reason, for one flow |
| `review()` | Runs every flow, applies justified skips (never for F06 and F07), prints, writes the compliance report |
| `StandIn` | A stand-in for S/4HANA's order inbound: outages, late answers, the message key and the business key |
| `business_error()`, `run()` | The flow's input checks, then delivery with the design's retry behavior; counts calls, waste and duplicates |
| `self_test()` | Builds everything in a temporary folder and checks that the draft fails and the reviewed design passes |

#### 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, 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 |
| `i10_draft.json not found` | Step 3 hasn't run, or you are in another folder | Run `python unit26/iflow_review.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 quote is missing after an edit | VS Code marks the line; fix it and run again |
| `KeyError` after editing a design | A field the checker expects is missing, such as `steps` or `keys` | Compare your flow with one in `i10_reviewed.json` |
| Your counts differ from the samples | The design or message files were edited | Run `python unit26/iflow_review.py --self-test`, then `--init` in a fresh folder |
| A company proxy blocks downloads | Not used here | The lab needs no network; only Step 9's trial does |

### The SAP way

What SAP provides for designing and governing flows, as of 29 November 2026:

- **Cloud Integration** in SAP Integration Suite: the flow editor, adapters, mappings, value mappings, script collections, local processes, ProcessDirect and JMS queues, described in SAP's [Integration Suite documentation](https://github.com/SAP-docs/btp-integration-suite). Editions and caps are on the [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html); the JMS adapter isn't in the basic edition, per [SAP's retry guideline](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-the-retry-pattern-with-jms-queue-da17d2d.md).
- **Integration flow design guidelines**: documentation plus reference packages on the SAP Business Accelerator Hub, and the same rules [built into the tenant](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/IntegrationSettings/design-guidelines-4d1c84f.md) with reports per artifact.
- **Idempotent Process Call** for duplicate detection inside a flow, with its [stated limits](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/define-idempotent-process-call-84c85d7.md).
- **Versioning** with *Save as Version* and **transport** through the Transport Management Service or CTS+; SAP's [Cloud Transport Management page](https://www.sap.com/uk/products/technology-platform/cloud-transport-management.html) lists Integration Suite iFlows among the content it moves.
- **Licensing note.** SAP's pricing page counts a message above 250 KB as one more message for each further 250 KB. A flow that splits or multicasts multiplies messages; size it before go-live.

### Build vs. SAP

| Need | SAP feature | Calder's lab or custom rule | Use which |
| --- | --- | --- | --- |
| Check flows against rules | Built-in design guidelines and reports | `iflow_review.py` with landscape rules (stage addresses, keys, owners) | SAP's for its guidelines; a pipeline check for rules SAP doesn't know, such as "production names only production" |
| Retry delivery | JMS queue with backoff | Retry loop in a script | The queue: it survives restarts and shows *Retry* in monitoring |
| Stop duplicates | Idempotent Process Call | Keys checked by the receiver | Both where the receiver allows; the receiver's check is the stronger one, as SAP notes |
| Per-tenant values | Externalized parameters | Edit after transport | Parameters, always |
| Move versions | TMS or CTS+ | Download and upload | The transport service; downloads only for emergencies |
| Shared logic | Script collections, ProcessDirect, value mappings | Copy and paste | The shared artifacts |

### Architecture view

**Where it sits.** The `I10` flow runs in the Integration Suite tenant of `calder-int-prod`. It reads a queue filled by the B2B intake flow ([B2B and EDI with Trading Partner Management](https://erpfde.com/topics/b2b-and-edi-integration/) covers EDI and trading partners) and calls `CP10`'s S/4HANA through the Cloud Connector pair `SCC-RK-P`. Alerts go through the shared `Global_Alert_Notify` flow over ProcessDirect. The diagram under *How it works* shows the pieces.

**Non-functional requirements.**

| Requirement | Target for `I10` | What breaks if missed |
| --- | --- | --- |
| Delay | Sales order within 1 hour of receipt (spec) | Orders miss the day's picking at `RKDC` |
| Retry window | 5 retries with backoff, about 31 minutes, inside the hour | Long outages end in `I10_ERR` with an alert, not silent loss |
| Duplicates | None, including after a late answer | Double shipments, disputed invoices |
| Volume | 60 messages an hour in the volume test (twice the peak) | Queue backlog; the 30-queue default caps the design |
| Security | Credentials by name; technical user limited to creating orders in `CPUS` | A password in monitoring; a user that can do more than its job |
| Logging | `Info` in production, payload not logged | Slow tenant; customer data kept longer than the retention rule |

**Integration and identity.** The distributor is identified by its trading partner profile, never by a value in the message. The flow posts to `CP10` with a technical user whose role only creates sales orders in sales org `CPUS`, as the spec requires; the [BTP security topic](https://erpfde.com/topics/btp-security-model/) covers how such users are governed. The order request carries the message key and the business key. Errors and alerts carry the order reference, not the payload.

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

- **Context.** `I10` creates sales orders from distributor EDI. The receiver can be briefly down and can answer late. Distributors' systems retry differently or not at all.
- **Options.** A: synchronous flow, sender retries. B: JMS queue with retry and an Idempotent Process Call only. C: JMS queue with retry, business errors routed in the flow, message key and business key checked by the receiver.
- **Decision.** C, with an Idempotent Process Call added only if the receiver can't check the message key.
- **Consequences.** One queue per interface plus a shared error queue count against the queue limit. Customer service gets a worklist for E02 and E03. The receiver's inbound must support both keys, which the spec now says.

**What a design review will ask.**

1. What happens to an order that arrives while S/4HANA is down for two hours?
2. Show me the second order that a late answer would create, and what stops it.
3. Which values change between test and production, and where are they set?
4. Who receives each error, and how do they reprocess a message after fixing the data?
5. Which design guidelines are active in every tenant, and who approved each skip?

### Production concerns

- **Security and authorizations.** Store credentials as security material and refer to them by name. Remove sensitive headers before logging or forwarding, as SAP's security guideline says. Limit who may *Configure* parameters in production: changing an address there is a production change. Give the role `WorkspaceDesignGuidelinesConfigure` to the integration lead, not to every developer.
- **Evaluation.** Keep the seven test messages, and add one for every production incident. Run the review and the replay in the pipeline before each transport; a FAIL stops the import.
- **Resources and cost.** Queues, worker memory and database space are shared by every flow on the tenant. SAP's boundary page lists 30 queues by default, and mappings and splitters are the heavy steps. Messages above 250 KB count as more than one message on SAP's pricing page.
- **Operations.** Watch the *Retry* and *Escalated* statuses, the error queue and alerts. Set `Debug` only in test, and note that a successful final retry isn't recorded at log level `Error`. Remember that the Idempotent Process Call forgets IDs after 90 days by default. The [observability topic](https://erpfde.com/topics/btp-observability/) covers alert routing.
- **Clean core.** Call S/4HANA only through released interfaces, as the [clean core topic](https://erpfde.com/topics/integration-platform-and-clean-core/) explains. A flow is upgrade-safe only if what it calls is.

### Where AI fits

AI touches flows in three ways, as of November 2026.

- **A flow calls a model.** SAP's AI adapter lets a flow call the generative AI hub or another provider as a receiver. [Calling AI from SAP Integration Suite](https://erpfde.com/topics/ai-in-sap-integration-suite/) builds one. Treat the model like any receiver: timeout, retry, error route, and no secrets in the prompt.
- **An agent calls a flow.** SAP's pricing page lists an MCP gateway that exposes APIs and integrations as tools for AI agents. The [MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) shows the policies. An agent is one more sender: it needs the same keys against duplicates and the same owner routes.
- **AI helps design.** The pricing page describes Integration Advisor as AI-assisted for B2B and EDI mappings. Anything AI drafts, a mapping, a script or a whole flow, goes through the same design guidelines and review as human work. The rules don't care who wrote the flow.

### Pitfalls

- **A message end in the exception subprocess of a queue-fed flow.** The queue sees success and deletes the message. Use an error end where the queue must retry.
- **Exception handling only in the main process.** SAP's documentation says exceptions of a local process can't be caught there. Give each local process its own subprocess.
- **Business errors in the retry path.** Unknown parts and units are retried for an hour and then land with the wrong team.
- **Trusting the retry count exactly.** `SAPJMSRetries` can overcount on several worker nodes; treat the limit as approximate.
- **Exclusive queues by habit.** Strict order means one bad message blocks every message behind it. Use them only when order matters.
- **A test address in a production flow.** The flow runs, so nobody notices until orders are missing. Parameters, set per tenant, checked in the pipeline.
- **Remodeling the Idempotent Process Call step.** A new step instance has an empty history and processes earlier messages again.
- **Copies instead of references.** Three copies of one script means three fixes, and one gets forgotten.
- **Manual downloads becoming the routine.** SAP recommends them only for emergencies; they leave no record of who moved what.

### Exercise

The `I10` spec says a requested date in the past is kept and flagged for customer service, not rejected. Add that rule as error code `E07` and release the flow as version 1.1.0.

1. Open `unit26/flows/i10_reviewed.json`.
2. In the first flow's `checks` list, after the `E04` entry, add (with a comma after the previous entry):

   ```json
   {"code": "E07", "check": "date_not_past", "action": "flag", "owner": "Customer service"}
   ```

3. In the same flow, change `"version": "1.0.0"` to `"version": "1.1.0"` and set `"change_note"` to `"1.1.0: E07 flags a requested date in the past"`. SAP's convention raises the minor version for a new process path.
4. Open `unit26/flows/i10_messages.json` and add an eighth message at the end of the list:

   ```json
   {"id": "HFS-PO-7822", "sender": "HALLAM", "customer_po": "HFS-PO-7822", "requested": "2026-11-20",
    "lines": [{"part": "HFS-SK-200", "qty": 10, "unit": "EA"}]}
   ```

5. Run `python unit26/iflow_review.py review unit26/flows/i10_reviewed.json`. The last line still reads `30 checks: 29 OK, 0 WARN, 0 FAIL, 1 SKIPPED`.
6. Run `python unit26/iflow_review.py run unit26/flows/i10_reviewed.json --tenant prod`. The new line reads `ORDER 1000604 in S4P; flagged E07 for Customer service`.
7. Break a rule on purpose. Set the test value of `S4_ORDER_URL` to the production host `s4p-api`, and add a skip for it under `skips`: `"F06": {"flow": "CPUS_I10_DistributorOrder_Inbound", "reason": "test with production data this week", "by": "00100288"}`. Run the review: F06 fails with *skip refused*. Put both back.
8. Add one row to your compliance report for the change: version 1.1.0, what it adds, and who approved it.

**Done when:** the review prints `30 checks: 29 OK, 0 WARN, 0 FAIL, 1 SKIPPED`, the replay shows four orders in `S4P` with `HFS-PO-7822` flagged for customer service, and your report records version 1.1.0. The reviewed flow and its test messages feed the [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/).

> **Note** The flagged order comes from a made-up message and a model of the design, not from a real SAP system.

### Check yourself

1. The I10 flow reads from a JMS queue. In its exception subprocess for an S/4HANA outage, which end event keeps the retry working?
   - A. A message end, so monitoring shows the message as completed
   - B. An error end, so the failure leaves the message in the queue
   - C. An escalation end, so the outage is shown as a business error
   - D. No end event, so the subprocess hands control back to the router

   Answer: B. A failed message stays in the queue and the JMS sender adapter retries it. A message end tells the queue all is well, so the order would be lost; an escalation end is what Calder uses for business errors that must not be retried.

2. Why does the reviewed design give the Validate and Deliver local processes their own exception subprocesses?
   - A. Because SAP charges each local process as a separate flow
   - B. Because a router in the main exception subprocess would catch them all
   - C. Because the main process can't catch a local process's exceptions
   - D. Because local processes can only end with an escalation event

   Answer: C. SAP's documentation states that exceptions of a local integration process can't be caught in the main process. Each local process needs its own exception subprocess, which is what rule F01 checks.

3. Why does the reviewed I10 design send both a message key and a business key to the receiver?
   - A. The message key picks the sales area and the business key picks the plant
   - B. One spots a retried message, the other refuses a repeat order
   - C. One is required by the JMS adapter and the other by the Cloud Connector
   - D. Both are needed because SAP's Idempotent Process Call keeps IDs for 90 days

   Answer: B. The message key lets the receiver return the order it already saved, as with HFS-PO-7816's late answer. The business key, distributor plus customer PO, refuses Hallam's genuinely new message for an order that exists and routes it as E03.

4. In the draft's replay, every order landed in S4Q although the flow ran in production. Which two rules caught the cause?
   - A. F09 and F10, because the process was too long and had an unused step
   - B. F03 and F04, because there was no queue and no duplicate key
   - C. F11 and F12, because scripts were copied and the flow was a draft
   - D. F05 and F06, as the address was typed in, not set per tenant

   Answer: D. F05 fails a receiver address typed into the design, and F06 checks that each tenant's configured address names its own stage's system. With a parameter set once per tenant, test reaches S4Q and production reaches S4P from the same design.

5. The partner asks to add a splitter and call Hallam's part catalog once per order line. What do you answer?
   - A. Accept it, since the JMS queue retries any calls that fail
   - B. Accept it, if the call is moved into the exception subprocess
   - C. Use a value mapping, since a call in a loop runs per line
   - D. Use Trace log level in production to watch the calls per line

   Answer: C. A call inside a splitter runs once per line, so a 40-line order means 40 calls, and SAP's boundary page lists mappings and splitters among the heavy steps. A value mapping holds the cross-reference in the package; rule F08 checks for calls in loops.

6. A developer wants to switch the production I10 flow to Debug for a week to investigate slow orders. What is the right response?
   - A. Fine, Debug is the recommended level for productive flows
   - B. Debug is for test only, and it expires after 24 hours
   - C. Use log level None instead, since it records the most detail
   - D. Use Error instead, since it records every step of every message

   Answer: B. SAP recommends Debug only in a development or test environment, and fixes its expiry at 24 hours. Info is the production level; Trace exists for short investigations and expires after 10 minutes by default.

7. The integration lead approves a skip for rule F06 because "we test with production data this week". What does the checker do, and why?
   - A. It accepts the skip, since every rule can be skipped with a reason
   - B. It accepts the skip but changes the rule's result to WARN
   - C. It deletes the test tenant's parameter so the default is used
   - D. It refuses: stage and credential rules have no exceptions

   Answer: D. The course checker never skips F06 or F07. A test tenant reaching production, or a password in a design, is exactly the kind of exception a review exists to stop.

8. After transport to production, someone sets the S/4HANA address with Configure. What happens at the next transport of version 1.1.0?
   - A. The configured value stays; transports don't overwrite it
   - B. The configured value is reset to the design's default value
   - C. The transport fails until the configured value is removed
   - D. The configured value moves back to the test tenant

   Answer: A. SAP's transport guidance says configuring externalized parameters on the target is usually one-time, because initially configured values aren't overwritten by later transports. The configured value also takes precedence over the default.

## Sources

- [Integration Flow Design Guidelines (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-29)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/integration-flow-design-guidelines-6803389.md): three groups (Learn the Basics, enterprise-grade guidelines, integration patterns); reference integration flows per guideline on the SAP Business Accelerator Hub; sub-pages Handle Errors Gracefully, Relax Dependencies to External Components, Keep Readability in Mind, Apply the Highest Security Standards, Run an Integration Flow Under Well-Defined Boundary Conditions
- [Design Guidelines (SAP Integration Suite documentation, Integration Settings)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/IntegrationSettings/design-guidelines-4d1c84f.md): guidelines embedded as rules; Settings > Integrations > Design Guidelines; severity; role WorkspaceDesignGuidelinesConfigure; export and import to harmonize tenants; report per artifact before go-live; no effect on execution; applies to SAP's prepackaged content too
- [Define Exception Subprocess (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/define-exception-subprocess-690e078.md): Error Start event; End Message, Error End or Escalation end; Router, Splitter, Aggregator and others not supported inside; exceptions of a local integration process can't be caught in the main process; ${exception.message}; a duplicate-key Data Store Write can't be handled
- [Handle Errors Gracefully (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/handle-errors-gracefully-42c95f7.md): end event variants and monitoring status (Message End Completed, Error End Failed, Escalation End Escalated); errors in successful responses; outsourcing exception handling into a separate flow
- [Apply the Retry Pattern with JMS Queue (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/apply-the-retry-pattern-with-jms-queue-da17d2d.md): persist at the start, sender gets HTTP 202; not in the basic edition (SAP Note 2903776); Retry Interval default 1, Exponential Backoff on by default, Maximum Retry Interval default 60; status Retry in monitoring
- [Define Idempotent Process Call (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/define-idempotent-process-call-84c85d7.md): skips or marks duplicates by message ID; exactly once needs an idempotent receiver, the process call is second-best; IDs deleted after 90 days by default; each step instance has its own history
- [Decoupling Development from Transport Using Externalized Parameters (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/decoupling-development-from-transport-using-externalized-parameters-9064b09.md): configure externalized parameters on the target tenant after transport, without editing the model; usually one-time, as configured values aren't overwritten by later transports
- [Versioning of Artifacts (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/versioning-of-artifacts-cb536a3.md): Save makes a Draft, Save as Version with a comment; default 1.0.0 and micro increments; recommended conventions for step, process and package changes; version history is tenant-specific
- [Decision Help for Choosing the Right Content Transport Option (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/decision-help-for-choosing-the-right-content-transport-option-19e0e73.md): manual export and import and MTAR download only for exceptions; CTS+ and the Transport Management Service recommended; TMS for cloud, CTS+ on premise
- [Setting Log Levels (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/setting-log-levels-4e6d3fc.md): None, Info, Error, Debug (development or test only, expires after 24 hours), Trace (expires after 10 minutes by default, content kept 1 hour by default); log level kept when a flow is updated
