# CI/CD and transport management on BTP: one release flow for a hybrid landscape

> Design how BTP changes are built, promoted from dev to test to production and released with S/4HANA transports, using pipelines and the transport service.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-cicd-and-transport/
- Updated: 2026-11-27
- 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

Every change to a BTP app has to travel. It is written in development, checked in test, and only then reaches production. Three things carry it:

1. **A pipeline** builds the change from the code in Git, runs the tests and produces one package. On BTP that package is usually an **MTA** (multitarget application): one archive that holds the app's parts and says which services they need.
2. **A transport service** moves that same package from development to test to production. SAP's is **SAP Cloud Transport Management**. It keeps a queue for each stage and a record of who imported what, and when.
3. **A coordinator** keeps BTP changes in step with S/4HANA changes. A new field in S/4HANA and the app that shows it are one feature. **SAP Cloud ALM** can track both kinds of transport for that feature.

The rule underneath is simple: **build once, then promote the same package**. Production should run exactly what passed test, not a rebuild of it.

### Why it matters to the business

- **Fewer surprises in production.** If a pipeline deploys straight to production, nothing stops a version that failed in test. A staged route with a gate does.
- **A record for audit.** SAP describes the transport service as adding an audit trail of who changed production, and when ([SAP Cloud Transport Management](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/what-is-sap-cloud-transport-management-5fef9d6.md)). That is the question a SOX or ISO auditor asks.
- **Separation of duties.** Developers start the transport; an operations team imports into production. The roles make that split enforceable.
- **Hybrid releases that don't break.** Most SAP changes touch both sides. Calder's distributor order-status app will show the test certificate number, and the field lives in S/4HANA. If the app reaches production before the field, distributors see an error.
- **Cost is small and visible.** As of November 2026, SAP bills the transport service's standard plan per started gigabyte uploaded, counted once; imports cost nothing ([service plans](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/service-plans-and-metering-17c102d.md)).

> **Example:** Calder Pumpworks, the course's fictional pump maker, had a bad Monday on 23 November 2026. Version 1.3.1 of its distributor portal failed to install in test at 10:00, yet it was in production at 22:00. The transport setup forwarded it before the test result was known, and production imported on a timer. The deep layer replays that week and the fix.

### How SAP does it

As of 27 November 2026, SAP's documentation describes these pieces:

- **SAP Continuous Integration and Delivery** runs predefined pipelines for SAP project types. Its job types are Cloud Foundry Environment, SAP Fiori for the ABAP Platform, SAP Integration Suite Artifacts, Kyma Runtime and, since May 2026, gCTS for ABAP Development ([SAP documentation](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/what-is-sap-continuous-integration-and-delivery-618ca03.md)). The service itself runs in the Cloud Foundry environment.
- **SAP Cloud Transport Management** moves four kinds of content: MTA archives, references to ABAP code in Git for the ABAP environment, application-specific content archives, and SAP HANA XS classic delivery units ([content types](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/supported-content-types-8961dcb.md)). It can transport across global accounts in Cloud Foundry.
- **MTAs** are SAP's packaging format for Cloud Foundry apps. An **extension descriptor** adds the values that differ by stage, such as memory or instance counts, so one archive deploys everywhere ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/defining-mta-extension-descriptors-50df803.md)).
- **SAP Cloud ALM** can connect to the transport service and to the ABAP transport system of S/4HANA Cloud Private Edition and on-premise systems, and orchestrate both from its Features app ([Cloud ALM setup](https://github.com/SAP-docs/cloud-alm-setup-admin-guide/blob/main/docs/02_integration_and_config_options/sap-cloud-transport-management-service-8b4af2f.md)).
- **CTS+**, the older route through an ABAP system's transport system, is still supported for BTP. SAP recommends the cloud transport service as the way forward ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/integration-with-transport-management-tools-c8bee32.md)).

### Who does what in a release

| Step | Who | Tool | What a leader should see |
| --- | --- | --- | --- |
| Change the code | Developer | Git, an IDE | A reviewed pull request |
| Build and test | Pipeline, no person | SAP Continuous Integration and Delivery or Jenkins | Green build, test results, one versioned package |
| Promote to test | Pipeline hands over; schedule imports | SAP Cloud Transport Management | The package in the test queue, then "Succeeded" |
| Accept | Key users and testers | Test system | Sign-off on the feature |
| Release to production | Operations, in a release window | Transport service, coordinated in SAP Cloud ALM | The same package, imported after its S/4HANA part |
| Roll back | Operations | Blue-green deployment, or the previous version | A rehearsed procedure, not improvisation |

> **Note** **For functional consultants.** Your test cases now follow a feature, not a system. For each feature, ask which S/4HANA transports and which BTP packages belong to it, test them together in the quality system and the BTP test subaccount, and sign off once. Key-user configuration that travels in an S/4HANA transport belongs to the same feature as the app that uses it.

### Questions to ask

- Does anything deploy straight to production from a pipeline or a laptop?
- Is the package in production the same one that passed test, or a rebuild?
- What stops a version that failed in test from reaching production?
- Who can import into production, and who checks that list?
- How do we keep S/4HANA transports and BTP packages for one feature in step?
- How long does a rollback take, and when did we last try one?
- Where do the stage-specific values live: in the package, or beside it?

### Common misconceptions

- **"CI/CD means every change goes straight to production."** Continuous delivery means every change *could* go; a release window and a gate decide when it does.
- **"The transport service replaces the pipeline."** It moves packages. Building and testing them is the pipeline's job.
- **"A test failure stops the transport."** Only if the setup says so. SAP's default forwarding mode moves a request on before its import in the current stage ([SAP documentation](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/20-configure-landscape/create-transport-nodes-f71a4d5.md)).
- **"BTP and S/4HANA releases are separate projects."** For the user they are one feature. Releasing them apart is how the app arrives before its field.
- **"Rollback is a button."** For MTAs, SAP marks rollback as experimental and limits it to apps, not managed services such as databases.

### Key terms

- **CI/CD:** continuous integration (build and test every change) and continuous delivery (keep every change ready to release).
- **Pipeline:** the automated sequence of build, test and hand-over steps for one project.
- **MTA (multitarget application):** SAP's package format for Cloud Foundry apps: one archive with all parts and the services they need.
- **Extension descriptor:** a small file with the values that differ by stage, applied when the MTA is deployed.
- **Transport node:** one stop in the transport service, usually one subaccount or system, with its own import queue.
- **Transport route:** the link from one node to the next.
- **Forwarding mode:** when a node passes a request on to the next node: before its own import, after it, only after success, or by hand.
- **Release window:** an agreed time when production imports happen.
- **Feature:** in SAP Cloud ALM, one business change with all the transports that implement it.

### Check yourself

1. What does "build once, promote the same package" protect against?
   - A. Pipelines that take too long to run for every stage
   - B. Production running something different from what passed test
   - C. Developers who forget to write unit tests for each change
   - D. Extra charges for each import into the production subaccount

   Answer: B. If each stage rebuilds the code, production may get a package nobody tested. Promoting the one tested archive means production runs exactly what test approved.

2. Calder's portal 1.3.1 failed in test at 10:00 and was in production at 22:00. Which setting allowed that?
   - A. The pipeline used the npm build tool instead of the mta build tool
   - B. The test subaccount had too little memory quota for the app
   - C. Forwarding before the test import, plus timed production imports
   - D. The transport service charged for the upload of the package

   Answer: C. SAP's default forwarding mode passes a request to the next node before importing it in the current one. With a timer on the production queue, nothing waited for the test result.

3. A partner proposes a pipeline that deploys straight to production after the tests pass. What is the main concern?
   - A. Pipelines on BTP can't deploy to more than one subaccount
   - B. The transport service would then charge twice for the same package
   - C. Production would lose its extension descriptors after the deployment
   - D. Nothing separates who builds from who decides to release to production

   Answer: D. The transport service adds a gate and a record: developers start the transport, operations import into production. A direct deployment skips both.

4. Calder's app shows a new S/4HANA field. In what order should production receive the two parts?
   - A. Both at once, since one feature should always go in one import
   - B. The app first, so users can see the change as early as possible
   - C. The S/4HANA transport first, then the BTP app that reads the field
   - D. Whichever transport happens to be ready first in that release window

   Answer: C. The app depends on the field. If the app arrives first, its calls fail until the field exists. Backend first, then the consumer, at every stage.

5. Which SAP tool can track the S/4HANA transports and the BTP transports of one feature together?
   - A. SAP Cloud ALM, connected to both transport systems
   - B. SAP Continuous Integration and Delivery, through its gCTS job
   - C. The MTA extension descriptor of the BTP app
   - D. SAP Cloud Transport Management on its own, without Cloud ALM

   Answer: A. SAP Cloud ALM connects to the ABAP transport system and to the cloud transport service and orchestrates deployments in its Features app. The transport service alone doesn't see S/4HANA transports.

6. What should a leader ask about rollback before go-live?
   - A. Which button in the cockpit undoes a production release
   - B. How it works, what it can't undo, and when it was last rehearsed
   - C. Whether SAP rolls back production automatically after errors
   - D. How many days the transport service keeps the old version's data

   Answer: B. For MTAs, SAP marks rollback as experimental and limits it to apps, not managed service instances. A rehearsed procedure is the only rollback you can count on.

## Deep layer

### Mental model

Think of a release as **one parcel on a route with gates**. The pipeline packs the parcel once and seals it. The transport service carries it from stop to stop. At each stop, someone or something decides whether it goes further. Labels that differ by stop, such as the delivery address, are not written on the parcel; they wait at each stop.

That maps to BTP like this:

- **The parcel** is an MTA archive (`.mtar`) with a version number, built by the pipeline. It never changes after the build.
- **The labels** are MTA extension descriptors (`.mtaext`), one per stage, held at each transport node.
- **The route** is a chain of transport nodes in SAP Cloud Transport Management: development, test, production.
- **The gates** are the nodes' forwarding modes and import settings, and the roles that say who may import where.
- **A second route** runs beside it: S/4HANA's own transport system, from `S4D` to `S4Q` to `S4P`. Hybrid features need both routes in step, and SAP Cloud ALM is where they meet.

[Deploying AI apps on BTP](https://erpfde.com/topics/deploying-ai-apps-on-btp/) built and pushed one app by hand. This topic is about the flow that replaces "by hand" for a whole landscape. The ABAP transport system itself, with requests, tasks and import order, is covered in Unit 29; Git-based ABAP transport (gCTS) in Unit 24; DevOps across both worlds in Unit 28.

### How it works

```mermaid
flowchart LR
  G[Git main branch] --> P[Pipeline<br/>build, test, scan]
  P -->|acceptance deploy| DEV[Dev subaccount]
  P -->|export .mtar| N1[Node EXT_DEV]
  N1 --> N2[Node EXT_TEST<br/>queue + test .mtaext]
  N2 -->|On Success| N3[Node EXT_PROD<br/>queue + prod .mtaext]
  N2 --> T[Test subaccount]
  N3 -->|import in window| PR[Prod subaccount]
  S4D[S4D] --> S4Q[S4Q] --> S4P[S4P]
  ALM[SAP Cloud ALM<br/>Features app] -.orchestrates.-> N2
  ALM -.orchestrates.-> N3
  ALM -.orchestrates.-> S4Q
  ALM -.orchestrates.-> S4P
```

#### The pipeline

SAP Continuous Integration and Delivery runs predefined pipelines. Your configuration of one is called a **job**, and its stages run in order. For a Cloud Foundry Environment job configured in the repository, the stages live in `.sap_cid/config.yaml` ([SAP documentation](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/configure-a-cloud-foundry-environment-job-in-your-repository-bfe48a4.md)):

| Stage | What it does | Notes from SAP's page |
| --- | --- | --- |
| `build` | Builds with `mta`, `npm` or `maven` | Mandatory; `buildDescriptor` defaults to `mta.yaml` for the `mta` tool |
| `additionalTests` | Runs an npm test script | `mta` or `npm` build tool only |
| `malwareScan` | Scans the project files | `mta` build tool only |
| `acceptance` | Deploys to a test space (`cfDeploy`), runs WebdriverIO tests | Takes `mtaExtensionDescriptors` |
| `compliance` | SonarCloud or SonarQube scan | Token kept as a credential |
| `release` | Deploys (`cfDeploy`) and/or hands over to the transport service (`cloudTransportManagement`) | `nodeOperation` is `export` or `upload` |

Two details matter for design. The deploy `strategy` can be `blue-green` only with the `mta` build tool, and blue-green needs extra Cloud Foundry memory quota because old and new versions run side by side. And the job's credentials should belong to technical users, not people; SAP's page says so for the test credential, and the same reasoning applies to the deploy user.

As of March 2026 every Cloud Foundry Environment job runs on pipeline version 3.0; version 2.0 was removed ([what's new](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/what-s-new-for-sap-continuous-integration-and-delivery-8d3bf2e.md)). Jobs on the free plan or in a trial are switched off after a week without changes.

If you run Jenkins instead, SAP's open-source project "Piper" has steps for the same hand-over: `tmsUpload` and `tmsExport` upload an MTA and its extension descriptors into the transport service ([Piper step metadata](https://github.com/SAP/jenkins-library/blob/master/resources/metadata/tmsUpload.yaml)).

#### Export or upload

The `release` stage can hand the archive over in two ways ([SAP documentation](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/integrate-cloud-transport-management-into-your-job-a0f029b.md)):

- **Export from** a node: the transport request goes to the queues of the nodes **after** the named node. Use it when the pipeline has already deployed to development itself (its acceptance stage), so the development node is only a starting point. SAP says to choose this option for lifecycles driven by SAP Cloud ALM.
- **Upload to** a node: the request lands in the named node's **own** queue. Use it when the first real target is test.

Either way the transport request can't be changed afterwards. That is "build once" enforced by the tool.

#### Nodes, routes and forwarding

A **transport node** stands for a source or target, typically a subaccount. A target node names a content type, a destination that says where to deploy, and for MTAs a deployment strategy. A **route** connects exactly one source node to one target node ([SAP documentation](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/20-configure-landscape/transport-routes-39b082d.md)).

The **forwarding mode** decides when a request moves on ([Create Transport Nodes](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/20-configure-landscape/create-transport-nodes-f71a4d5.md)):

| Mode | When the request goes to the next node | What it means for a failed import |
| --- | --- | --- |
| Pre-Import (default) | As the import starts, before the import | Already forwarded |
| Post-Import | After the import, whatever the result | Forwarded anyway |
| On Success | Only after Succeeded, Warning or Skipped | Stays behind |
| Manual | When someone chooses *Forward* | Stays behind |

The default is the trap. On a test node in front of production, only **On Success** or **Manual** gates production on the test result.

Other node settings worth knowing:

- **Allow Upload to Node** must be on for any node that pipelines or people upload into. Leave it off where only the route should fill the queue.
- **Virtual nodes** have no target. Imports there get the status *Skipped*, which counts as success. They help with uneven landscapes, such as a BTP route with fewer stages than the ABAP one.
- **Import settings** (grouped under one *Import Settings* menu since the November 2026 release) can schedule imports or switch them off for a node.
- **Statuses** tell you what an *Import All* will do. A request in *Error* is left out until someone resets it; one in *Fatal* (nothing imported, for example a wrong destination) is retried ([statuses](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/40-using-request-overview/statuses-of-transport-requests-3a8259e.md)).

#### Destinations and deployment

For MTAs on Cloud Foundry, a target node's destination points to the **SAP Cloud Deployment service** of the target space. SAP recommends addressing the space by its GUID, because the GUID survives a rename of the org or space and needs no URL encoding ([SAP documentation](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/20-configure-landscape/creating-destinations-using-sap-cloud-deployment-service-with-basic-authentication-6b7c9d8.md)). The URL has the form `https://deploy-service.cf.<domain>/slprot/<space-guid>/slp`. Content from SAP API Management and SAP Cloud Integration can instead go through SAP Content Agent service.

The deploy service has limits worth putting in a design. An MTA archive can be up to 4 GB. When one import of several transport requests becomes one deployment, SAP allows at most 100 archives and 20 GB in total through the transport service ([MTA documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/multitarget-applications-in-the-cloud-foundry-environment-d04fc0e.md)).

#### Stage values: extension descriptors

An extension descriptor names the MTA it `extends` and adds or overwrites parameters. With `cf deploy app.mtar -e prod.mtaext` the deploy service merges them; several descriptors chain in order ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/defining-mta-extension-descriptors-50df803.md)).

In the transport service, you upload a descriptor to each node on its *MTA Extension Descriptors* tab. Three rules from SAP's page ([Upload MTA Extension Descriptors](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/30-using-import-queue/upload-mta-extension-descriptors-0c7a672.md)) shape the operating model:

- Descriptors **aren't forwarded**. Every node that imports the MTA needs its own.
- A descriptor binds to all versions (`*`, the recommended default) or to one exact version. A specific one wins where both exist.
- Uploading one needs the *TransportOperator* authorization, so production values are under operations' control, not the developer's.

#### Blue-green, backup and rollback

On a node with content type MTA you choose **default** (the old version stops, the new one starts: downtime) or **blue-green**. With blue-green, the deploy service starts the new version beside the old one, then switches the routes. SAP's restrictions are architectural facts ([blue-green strategy](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/blue-green-deployment-strategy-7c83810.md)):

- It covers Cloud Foundry applications only, not service instances, workflow content or HTML5 repository content. Old and new versions share the same service instances, so database changes must work for both.
- During the switch the app needs double its instances, unless you use the slower **incremental** blue-green strategy.
- The transport service skips blue-green's manual testing phase.

**Rollback** is marked experimental. It needs a blue-green deployment with `--backup-previous-version`, keeps the backup for 3 days, and backs up only when the MTA version changed ([rollback](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/experimental-rollback-of-multitarget-applications-d612be9.md)). So reusing a version number quietly removes your rollback.

#### Who may do what

The transport service's role templates ([Security](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/60-security/security-51939a4.md)):

| Template | Can do |
| --- | --- |
| Administrator | Everything |
| LandscapeOperator | Create and change nodes and routes |
| TransportOperator | Forward, reset, remove, schedule, upload extension descriptors, **and import** |
| ImportSelectedOperator | Import selected requests |
| ImportOperator | Import all requests in a queue |
| ExportOperator | Add files to queues |
| Viewer | Display only |

Attributes such as `TmsNodesImport` restrict a role to named nodes. One sentence on SAP's page deserves a design review of its own: the `TmsNodesTransportOperator` attribute restricts the TransportOperator tasks but **not the import tasks that the same role includes**. A developer given TransportOperator "only for test nodes" can still import into production. Give developers ImportSelectedOperator restricted with `TmsNodesImportSelected` instead.

For API access, the service offers instance plans: `standard`, `export` (upload and export only, which SAP suggests for CI/CD pipelines) and `transport_operator` (import, reset, forward, delete) ([service plans](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/service-plans-and-metering-17c102d.md)). The pipeline's service key should come from an `export` instance.

#### The ABAP side: two different things

"ABAP transports" means two things in a hybrid landscape, and they travel differently:

- **The SAP BTP ABAP environment** (SAP's documentation now calls it SAP Business AI Platform, ABAP environment) records changes in ABAP transport requests that, on release, become commits in a Git repository per software component. You export a commit from the *Manage Software Components* app to a transport node (communication scenario `SAP_COM_0599`), and the node imports it into the target system through `SAP_COM_0948`. SAP recommends exporting by commit ID, because a branch's latest commit can move ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/export-commits-using-sap-cloud-transport-management-b837a3b.md)). That is the *BTP ABAP* content type.
- **S/4HANA Cloud Private Edition or on-premise** keeps its classic transport system (CTS). The cloud transport service doesn't import into it. SAP Cloud ALM connects to CTS for systems on ABAP 7.40 or higher, ECC included, and requires `CTC=1` in TMS ([Cloud ALM setup](https://github.com/SAP-docs/cloud-alm-setup-admin-guide/blob/main/docs/02_integration_and_config_options/sap-s-4hana-cloud-private-edition-and-on-premise-systems-5aa24f0.md)). The same page says CTS+ isn't supported there, identical system IDs aren't supported, and the Features app treats the last system in the landscape as production.

So the alignment between S/4HANA and BTP happens one level up: in SAP Cloud ALM's Features app, or in your own release plan if you don't use it. Cloud ALM's setup guide recommends running the transport service in a central administrative subaccount, not in Cloud ALM's own accounts ([Cloud ALM setup](https://github.com/SAP-docs/cloud-alm-setup-admin-guide/blob/main/docs/02_integration_and_config_options/sap-cloud-transport-management-service-8b4af2f.md)). For *BTP ABAP* content, Cloud ALM can't use *Import Selected*; it imports up to a request, so all earlier requests in the queue go too.

The alternative is **CTS+**: the ABAP system's transport system carries MTAs as attachments to its requests. SAP lists it for customers who already use CTS+ or want the ABAP system to lead, and recommends the cloud transport service as the future-proof way ([SAP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/integration-with-transport-management-tools-c8bee32.md)).

#### What doesn't fit the transport service

Kyma workloads aren't among the four content types. A Kyma app is promoted by its pipeline, for example the CI/CD service's Kyma Runtime job, which deploys a CAP project with a Helm chart ([SAP documentation](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/configure-a-kyma-runtime-job-in-your-repository-9f1c1e2.md)), or by a GitOps tool. Calder's MES listener (W04 from [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/)) needs its own gate in that pipeline: a manual approval before the production stage.

### Build it yourself: Calder's release flow

You will write Calder's transport landscape, pipelines, roles and four release features as data, check them against twelve rules, replay last week's release through the import queues, and print a release plan for one hybrid feature. Everything runs on your computer with no account. An optional step builds a real MTA and deploys it to your trial with an extension descriptor.

```mermaid
flowchart LR
  I[--init] --> J[calder_release.json<br/>partner's draft]
  I2[--init --reviewed] --> J2[calder_release_reviewed.json]
  J --> C[release_flow.py<br/>rules D01-D12]
  J2 --> C
  C --> R[OK / WARN / FAIL]
  C --> S[--simulate<br/>release week]
  C --> P[--plan F-101]
  C --> W[--write]
  W --> M[calder_release_flow.md]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). This walkthrough doesn't repeat their steps.

> **Note** New words. A **pipeline** is a script a server runs on every change: build, test, hand over. A **transport request** is the transport service's envelope around one package on its way through the landscape. An **import queue** is the list of requests waiting at one node. **JSON** is a text format for structured data. A **release window** is an agreed time for production imports. All Calder values here are course values for a fictional company.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account for Steps 1 to 7 and 9. Step 8 optionally uses your trial, the cf CLI and Node.js from earlier setup topics.
- About 45 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. The `unit21` folder exists from the setup topic. If it doesn't, create it with `mkdir unit21`.

#### Step 2: Create the script

1. In VS Code, create a new file `unit21/release_flow.py`.
2. Paste the whole script below and save. It uses built-in Python modules only, so there is nothing to install.

```python
"""Calder's release flow on BTP: transport landscape, pipelines and hybrid releases, checked.

Unit 21, CI/CD and transport management on BTP. Built-in modules only, no randomness.

  python unit21/release_flow.py --init                 write unit21/calder_release.json (the partner's draft)
  python unit21/release_flow.py --init --reviewed      write unit21/calder_release_reviewed.json (after review)
  python unit21/release_flow.py                        check the draft against rules D01-D12
  python unit21/release_flow.py --simulate             replay the release week through the import queues
  python unit21/release_flow.py --plan F-101           print the release plan for one feature
  python unit21/release_flow.py --write                write unit21/calder_release_flow.md
  add --file unit21/calder_release_reviewed.json to any command to use the reviewed design

All names, numbers, dates and rules are course values for the fictional Calder Pumpworks.
"""
import argparse
import copy
import json
import os
import sys
from datetime import datetime, timedelta

HERE = os.path.dirname(os.path.abspath(__file__))
DRAFT = os.path.join(HERE, "calder_release.json")
REVIEWED = os.path.join(HERE, "calder_release_reviewed.json")
REPORT = os.path.join(HERE, "calder_release_flow.md")
STAGES = ["dev", "test", "prod"]
S4 = {"S4D": "dev", "S4Q": "test", "S4P": "prod"}
SAFE_FORWARDING = {"On Success", "Manual"}
GOOD_STATUSES = {"Succeeded", "Warning", "Skipped"}   # SAP: an import counts as successful with these

RULES = {
    "D01": "Routes follow the stages one step at a time: dev to test to prod, never dev to prod",
    "D02": "A target node's destination deploys to a subaccount of the node's own stage",
    "D03": "Production nodes don't allow uploads: only the route fills their queue",
    "D04": "Nodes that forward to production forward On Success or Manual",
    "D05": "Production imports are started by a person in a release window, not on a schedule",
    "D06": "Customer-facing apps deploy blue-green in production",
    "D07": "Every MTA node has its own extension descriptor where the MTA needs stage values",
    "D08": "Pipelines hand over to the transport service and never deploy to production",
    "D09": "Every release carries a new MTA version",
    "D10": "Developers hold no TransportOperator role and import only into test nodes",
    "D11": "In a hybrid feature the S/4HANA transport reaches each stage first",
    "D12": "Destinations to the deploy service use the space GUID",
}

DRAFT_DATA = {
    "as_of": "2026-11-27",
    "transport_service": {"subaccount": "calder-admin", "plan": "standard (Application)",
                          "connected_to_cloud_alm": True},
    "people": {"00100288": "integration developer", "00100292": "integration lead (release manager)",
               "00100316": "BTP platform administrator", "00100317": "BTP platform administrator"},
    "developers": ["00100288"],
    "subaccounts": {"calder-ext-dev": "dev", "calder-ext-test": "test", "calder-ext-prod": "prod",
                    "calder-ai-dev": "dev", "calder-ai-test": "test", "calder-ai-prod": "prod"},
    "destinations": {
        "CTMS_EXT_TEST": {"subaccount": "calder-ext-test", "addressing": "space-guid"},
        "CTMS_EXT_PROD": {"subaccount": "calder-ext-prod", "addressing": "org-and-space-names"},
        "CTMS_AI_TEST": {"subaccount": "calder-ai-prod", "addressing": "space-guid"},
        "CTMS_AI_PROD": {"subaccount": "calder-ai-prod", "addressing": "space-guid"},
        "CTMS_CERT_PROD": {"subaccount": "calder-ext-prod", "addressing": "communication-arrangement"},
    },
    "mtas_with_stage_values": {"calder.orderstatus": ["EXT_TEST", "EXT_PROD"],
                               "calder.orderexc": ["AI_TEST", "AI_PROD"]},
    "nodes": [
        dict(name="EXT_DEV", stage="dev", allow_upload=True, forwarding="Pre-Import"),
        dict(name="EXT_TEST", stage="test", content_type="MTA", destination="CTMS_EXT_TEST",
             forwarding="Pre-Import", auto_import="hourly", strategy="default",
             extension_descriptors=["calder.orderstatus"]),
        dict(name="EXT_PROD", stage="prod", content_type="MTA", destination="CTMS_EXT_PROD",
             forwarding="Manual", auto_import="daily 22:00", strategy="default", allow_upload=True,
             customer_facing=["calder.orderstatus"], extension_descriptors=[]),
        dict(name="AI_DEV", stage="dev", allow_upload=True, forwarding="Pre-Import"),
        dict(name="AI_TEST", stage="test", content_type="MTA", destination="CTMS_AI_TEST",
             forwarding="On Success", auto_import="hourly", strategy="default",
             extension_descriptors=["calder.orderexc"]),
        dict(name="AI_PROD", stage="prod", content_type="MTA", destination="CTMS_AI_PROD",
             forwarding="Manual", auto_import="none", strategy="blue-green",
             extension_descriptors=["calder.orderexc"]),
        dict(name="CERT_DEV", stage="dev", allow_upload=True, forwarding="Pre-Import"),
        dict(name="CERT_PROD", stage="prod", content_type="BTP ABAP", destination="CTMS_CERT_PROD",
             forwarding="Manual", auto_import="none", two_system=True),
    ],
    "routes": [["EXT_DEV", "EXT_TEST"], ["EXT_TEST", "EXT_PROD"], ["AI_DEV", "AI_TEST"],
               ["AI_DEV", "AI_PROD"], ["AI_TEST", "AI_PROD"], ["CERT_DEV", "CERT_PROD"]],
    "role_assignments": [
        {"user": "00100288", "template": "TransportOperator", "nodes": ["EXT_TEST", "AI_TEST"]},
        {"user": "00100292", "template": "ImportSelectedOperator", "nodes": ["EXT_TEST", "AI_TEST"]},
        {"user": "00100316", "template": "ImportOperator", "nodes": ["EXT_PROD", "AI_PROD", "CERT_PROD"]},
    ],
    "pipelines": [
        {"job": "orderstatus-main", "mta": "calder.orderstatus", "build_tool": "mta",
         "acceptance_subaccount": "calder-ext-dev", "release_deploy_subaccount": None,
         "transport": {"nodeOperation": "export", "nodeName": "EXT_DEV", "instance_plan": "standard"},
         "last_released": "1.3.2", "next_version": "1.4.0"},
        {"job": "orderexc-main", "mta": "calder.orderexc", "build_tool": "mta",
         "acceptance_subaccount": "calder-ai-dev", "release_deploy_subaccount": "calder-ai-prod",
         "transport": None, "last_released": "2.2.0", "next_version": "2.2.0"},
    ],
    "features": [
        {"id": "F-101", "title": "Order status shows the test certificate number",
         "parts": [{"kind": "abap", "item": "S4DK900431", "reached": "S4D"},
                   {"kind": "mta", "item": "calder.orderstatus 1.4.0", "path": ["EXT_DEV", "EXT_TEST", "EXT_PROD"],
                    "reached": "EXT_TEST"}]},
        {"id": "F-102", "title": "Order-exceptions agent drafts in the clerk's language",
         "parts": [{"kind": "mta", "item": "calder.orderexc 2.2.0", "path": ["AI_DEV", "AI_TEST", "AI_PROD"],
                    "reached": "AI_DEV"}]},
        {"id": "F-103", "title": "Intercompany price job for CP-IMP200 (R08)",
         "parts": [{"kind": "abap", "item": "S4DK900433", "reached": "S4Q"}]},
        {"id": "F-104", "title": "Test certificate archive keeps 10 years of PDFs",
         "parts": [{"kind": "btp-abap", "item": "ZCALDER_CERT commit 4f2a9c1", "path": ["CERT_DEV", "CERT_PROD"],
                    "reached": "CERT_DEV"}]},
    ],
    "simulation": {
        "start": "2026-11-23 00:00", "end": "2026-11-26 23:00",
        "release_windows": ["2026-11-24 18:00", "2026-11-26 18:00", "2026-12-01 18:00", "2026-12-03 18:00"],
        "exports": [{"at": "2026-11-23 09:20", "node": "EXT_DEV", "mta": "calder.orderstatus", "version": "1.3.1"},
                    {"at": "2026-11-24 09:20", "node": "EXT_DEV", "mta": "calder.orderstatus", "version": "1.3.2"}],
        "outcomes": {"EXT_TEST|calder.orderstatus|1.3.1": "Error"},
    },
}


def reviewed_data():
    d = copy.deepcopy(DRAFT_DATA)
    d["destinations"]["CTMS_EXT_PROD"]["addressing"] = "space-guid"
    d["destinations"]["CTMS_AI_TEST"]["subaccount"] = "calder-ai-test"
    nodes = {n["name"]: n for n in d["nodes"]}
    nodes["EXT_TEST"]["forwarding"] = "On Success"
    nodes["EXT_PROD"].update(allow_upload=False, auto_import="none", strategy="blue-green",
                             extension_descriptors=["calder.orderstatus"])
    d["routes"].remove(["AI_DEV", "AI_PROD"])
    d["role_assignments"][0] = {"user": "00100288", "template": "ImportSelectedOperator",
                                "nodes": ["EXT_TEST", "AI_TEST"]}
    d["role_assignments"].append({"user": "00100317", "template": "ImportOperator",
                                  "nodes": ["EXT_PROD", "AI_PROD", "CERT_PROD"]})
    p = d["pipelines"]
    p[0]["transport"]["instance_plan"] = "export"
    p[1].update(release_deploy_subaccount=None, next_version="2.3.0",
                transport={"nodeOperation": "export", "nodeName": "AI_DEV", "instance_plan": "export"})
    d["features"][0]["parts"][0]["reached"] = "S4Q"
    d["features"][1]["parts"][0]["item"] = "calder.orderexc 2.3.0"
    return d


# ---------------------------------------------------------------- checks
def stage_of_node(d, name):
    for n in d["nodes"]:
        if n["name"] == name:
            return n["stage"]
    return None


def check(d):
    """Return a list of (section, object, [(rule, verdict, reason)])."""
    out = []
    nodes = {n["name"]: n for n in d["nodes"]}
    feeds_prod = {src for src, dst in d["routes"] if nodes.get(dst, {}).get("stage") == "prod"}
    for n in d["nodes"]:
        f = []
        if n.get("destination"):
            dest = d["destinations"].get(n["destination"], {})
            target_stage = d["subaccounts"].get(dest.get("subaccount"))
            if target_stage != n["stage"]:
                f.append(("D02", "FAIL", f"destination {n['destination']} deploys to {dest.get('subaccount')} ({target_stage})"))
            if dest.get("addressing") == "org-and-space-names":
                f.append(("D12", "WARN", f"{n['destination']} uses org and space names; a rename breaks it"))
        if n["stage"] == "prod" and n.get("allow_upload"):
            f.append(("D03", "FAIL", "uploads allowed into a production node"))
        if n["stage"] == "test" and n["name"] in feeds_prod and n.get("forwarding") not in SAFE_FORWARDING:
            f.append(("D04", "FAIL", f"forwards to production '{n['forwarding']}': a failed import still moves on"))
        if n["stage"] == "prod" and n.get("auto_import", "none") != "none":
            f.append(("D05", "FAIL", f"production imports run on a schedule ({n['auto_import']})"))
        for mta in n.get("customer_facing", []):
            if n.get("strategy") != "blue-green":
                f.append(("D06", "FAIL", f"{mta} is customer-facing and deploys '{n.get('strategy')}' (downtime)"))
        for mta, where in d.get("mtas_with_stage_values", {}).items():
            if n["name"] in where and mta not in n.get("extension_descriptors", []):
                f.append(("D07", "FAIL", f"no extension descriptor for {mta}: it would deploy with the archive's values"))
        out.append(("Nodes", n["name"], sorted(f)))
    for src, dst in d["routes"]:
        f = []
        a, b = STAGES.index(nodes[src]["stage"]), STAGES.index(nodes[dst]["stage"])
        if b - a != 1 and nodes[dst].get("two_system"):
            f.append(("D01", "WARN", "two-system landscape: tests run in the development system"))
        elif b - a != 1:
            f.append(("D01", "FAIL", f"{nodes[src]['stage']} to {nodes[dst]['stage']} skips a stage"))
        out.append(("Routes", f"{src} -> {dst}", f))
    for p in d["pipelines"]:
        f = []
        target = p.get("release_deploy_subaccount")
        if target and d["subaccounts"].get(target) == "prod":
            f.append(("D08", "FAIL", f"Release stage deploys straight to {target}"))
        if not p.get("transport"):
            f.append(("D08", "FAIL", "no hand-over to the transport service"))
        elif p["transport"].get("instance_plan") != "export":
            f.append(("D08", "WARN", f"credential from a '{p['transport']['instance_plan']}' instance; the export plan is enough"))
        if version_key(p["next_version"]) <= version_key(p["last_released"]):
            f.append(("D09", "FAIL", f"next version {p['next_version']} isn't above {p['last_released']}"))
        out.append(("Pipelines", p["job"], f))
    for r in d["role_assignments"]:
        f = []
        if r["user"] in d["developers"]:
            if r["template"] in ("TransportOperator", "Administrator"):
                f.append(("D10", "FAIL", f"{r['template']} includes imports that its node attribute doesn't restrict"))
            prod = [x for x in r["nodes"] if stage_of_node(d, x) == "prod"] if r["nodes"] else ["all nodes"]
            if prod and r["template"] in ("ImportOperator", "ImportSelectedOperator", "TransportOperator", "Administrator"):
                f.append(("D10", "FAIL", f"developer can import into {', '.join(prod)}"))
        out.append(("Roles", f"{r['user']} {r['template']}", f))
    for feat in d["features"]:
        f = []
        abap = [x for x in feat["parts"] if x["kind"] == "abap"]
        btp = [x for x in feat["parts"] if x["kind"] != "abap"]
        if abap and btp:
            s4_stage = STAGES.index(S4[abap[0]["reached"]])
            for part in btp:
                bstage = STAGES.index(stage_of_node(d, part["reached"]))
                if bstage > s4_stage:
                    f.append(("D11", "FAIL", f"{part['item']} is in {part['reached']} while "
                                             f"{abap[0]['item']} is still in {abap[0]['reached']}"))
        out.append(("Features", feat["id"], f))
    return out


def version_key(v):
    return tuple(int(x) for x in v.split("."))


def verdict(findings):
    if any(v == "FAIL" for _, v, _ in findings):
        return "FAIL"
    return "WARN" if findings else "OK"


def print_check(d, path):
    results = check(d)
    print(f"Calder release flow, as of {d['as_of']} ({os.path.relpath(path)})")
    section = None
    for sec, obj, f in results:
        if sec != section:
            print(f"\n{sec}")
            section = sec
        print(f"  {obj:<36} {verdict(f)}")
        for rule, v, reason in f:
            print(f"      {rule} {v}: {reason}")
    counts = {k: sum(1 for _, _, f in results if verdict(f) == k) for k in ("OK", "WARN", "FAIL")}
    print(f"\n{len(results)} objects: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return results


# ---------------------------------------------------------------- simulation
def simulate(d):
    """Replay exports and imports hour by hour, using the nodes' forwarding modes and schedules."""
    sim = d["simulation"]
    nodes = {n["name"]: n for n in d["nodes"]}
    targets = {}
    for src, dst in d["routes"]:
        targets.setdefault(src, []).append(dst)
    queues = {n: [] for n in nodes}
    live = {}
    counter = [1000]
    log = []
    t = datetime.strptime(sim["start"], "%Y-%m-%d %H:%M")
    end = datetime.strptime(sim["end"], "%Y-%m-%d %H:%M")
    windows = set(sim.get("release_windows", []))

    def add(node, req):
        queues[node].append(dict(req, status="Initial"))

    def forward(node, req, when, why):
        for dst in targets.get(node, []):
            add(dst, req)
            log.append((when, node, f"forward {req['id']} to {dst} ({why})"))

    while t <= end:
        stamp = t.strftime("%Y-%m-%d %H:%M")
        for name, n in nodes.items():
            sched = n.get("auto_import", "none")
            due = (sched == "hourly") or (sched.startswith("daily") and t.strftime("%H:%M") == sched.split()[1])
            by_hand = sched == "none" and n["stage"] == "prod" and stamp in windows
            if not (due or by_hand):
                continue
            for req in queues[name]:
                if req["status"] not in ("Initial", "Repeatable", "Fatal"):
                    continue          # Import All leaves Error requests alone until someone resets them
                mode = n.get("forwarding", "Manual")
                if mode == "Pre-Import":
                    forward(name, req, stamp, "Pre-Import")
                status = sim["outcomes"].get(f"{name}|{req['mta']}|{req['version']}", "Succeeded")
                req["status"] = status
                who = "release window, by hand" if by_hand else f"schedule {sched}"
                note = ""
                if n["stage"] == "prod":
                    tested = [q for x in nodes.values() if x["stage"] == "test"
                              for q in queues[x["name"]] if q["id"] == req["id"]]
                    if tested and tested[0]["status"] not in GOOD_STATUSES:
                        note = "   <- failed in test"
                log.append((stamp, name, f"import {req['id']} {req['mta']} {req['version']}: {status} ({who}){note}"))
                if n["stage"] == "prod" and status in GOOD_STATUSES:
                    live[(name, req["mta"])] = (req["version"], stamp, note != "")
                if mode == "Post-Import" or (mode == "On Success" and status in GOOD_STATUSES):
                    forward(name, req, stamp, mode)
        for e in sim["exports"]:
            if t <= datetime.strptime(e["at"], "%Y-%m-%d %H:%M") < t + timedelta(hours=1):
                counter[0] += 1
                req = {"id": counter[0], "mta": e["mta"], "version": e["version"]}
                for dst in targets.get(e["node"], []):
                    add(dst, req)
                log.append((e["at"], e["node"], f"export {e['mta']} {e['version']} -> request {req['id']} "
                                                f"in {', '.join(targets.get(e['node'], []))} queue"))
        t += timedelta(hours=1)
    return log, live


def print_simulation(d, path):
    log, live = simulate(d)
    sim = d["simulation"]
    print(f"Release week, {sim['start'][:10]} to {sim['end'][:10]} ({os.path.relpath(path)})\n")
    for when, node, text in log:
        print(f"{when}  {node:<9} {text}")
    print("\nIn production at the end:")
    if not live:
        print("  nothing new")
    for (node, mta), (version, stamp, bad) in sorted(live.items()):
        print(f"  {node}: {mta} {version}, imported {stamp}")
    for node, text in failed_in_prod(log):
        print(f"  Warning: {text} reached {node} although its import into test failed")


def failed_in_prod(log):
    for when, node, text in log:
        if text.endswith("<- failed in test"):
            parts = text.split()
            yield node, f"{parts[2]} {parts[3].rstrip(':')}"


# ---------------------------------------------------------------- plan
def plan(d, feature_id):
    feat = next((f for f in d["features"] if f["id"] == feature_id), None)
    if not feat:
        sys.exit(f"No feature {feature_id}. Features: {', '.join(f['id'] for f in d['features'])}")
    nodes = {n["name"]: n for n in d["nodes"]}
    steps = []
    for part in feat["parts"]:
        if part["kind"] == "abap":
            for i, system in enumerate(["S4D", "S4Q", "S4P"]):
                action = "release in" if i == 0 else "import into"
                steps.append((i, 0, system, f"{part['item']}: {action} {system}", part, system))
        else:
            for i, node in enumerate(part["path"]):
                if i == 0:
                    tool = "Manage Software Components" if part["kind"] == "btp-abap" else "pipeline"
                    action = f"{tool} exports {part['item']}"
                else:
                    n = nodes[node]
                    how = "in a release window" if n.get("auto_import", "none") == "none" else n["auto_import"]
                    strat = f", {n['strategy']}" if n.get("strategy") else ""
                    action = f"import {part['item']} ({how}{strat})"
                steps.append((STAGES.index(nodes[node]["stage"]), 1, node, action, part, node))
    steps.sort(key=lambda s: (s[0], s[1]))
    window = next((w for w in d["simulation"]["release_windows"] if w[:10] >= d["as_of"]), "the next window")
    print(f"Release plan for {feat['id']}: {feat['title']}")
    if any(p["kind"] == "abap" for p in feat["parts"]) and any(p["kind"] != "abap" for p in feat["parts"]):
        print("Rule D11: at every stage the S/4HANA transport goes first, then the BTP part\n")
    else:
        print()
    print(f"  #  Stage  Where      Step{'':<58} State")
    blocked = False
    for k, (stage, _, where, action, part, here) in enumerate(steps, 1):
        order = (["S4D", "S4Q", "S4P"] if part["kind"] == "abap" else part["path"])
        done = order.index(here) <= order.index(part["reached"])
        if done:
            state = "done, too early" if blocked else "done"
        elif not blocked:
            state = "next" + (f" ({window})" if STAGES[stage] == "prod" else "")
            blocked = True
        else:
            state = "waits"
        print(f"  {k:<2} {STAGES[stage]:<6} {where:<10} {action:<62} {state}")
    issues = [x for sec, obj, f in check(d) if sec == "Features" and obj == feature_id for x in f]
    for rule, v, reason in issues:
        print(f"\n  {rule} {v}: {reason}")


# ---------------------------------------------------------------- report
def write_report(d, path):
    results = check(d)
    lines = [f"# Calder release flow: design check, {d['as_of']}", "",
             f"Source: `{os.path.relpath(path)}`. Course values for the fictional Calder Pumpworks.", "",
             "## Rules", "", "| Rule | Check |", "| --- | --- |"]
    lines += [f"| {k} | {v} |" for k, v in RULES.items()]
    lines += ["", "## Results", "", "| Section | Object | Verdict | Findings |", "| --- | --- | --- | --- |"]
    for sec, obj, f in results:
        found = "; ".join(f"{r} {v}: {why}" for r, v, why in f) or "none"
        lines.append(f"| {sec} | {obj} | {verdict(f)} | {found} |")
    log, live = simulate(d)
    lines += ["", "## Release week replay", "", "```text"]
    lines += [f"{w}  {n:<9} {t}" for w, n, t in log]
    lines += ["```", "", "## Decision record", "", "- **Context:**", "- **Options:**", "- **Decision:**",
              "- **Consequences:**", ""]
    with open(REPORT, "w", encoding="utf-8") as fh:
        fh.write("\n".join(lines))
    print(f"Wrote {os.path.relpath(REPORT)}")


# ---------------------------------------------------------------- main
def load(path):
    if not os.path.exists(path):
        sys.exit(f"{os.path.relpath(path)} not found. Run: python unit21/release_flow.py --init"
                 + (" --reviewed" if path == REVIEWED else ""))
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except json.JSONDecodeError as e:
        sys.exit(f"{os.path.relpath(path)} is not valid JSON: {e}")


def main():
    ap = argparse.ArgumentParser(description="Check Calder's BTP release flow (course lab).")
    ap.add_argument("--init", action="store_true", help="write the sample design file")
    ap.add_argument("--reviewed", action="store_true", help="with --init: write the reviewed design")
    ap.add_argument("--file", help="design file to read (default unit21/calder_release.json)")
    ap.add_argument("--simulate", action="store_true", help="replay the release week")
    ap.add_argument("--plan", metavar="FEATURE", help="print the release plan for one feature")
    ap.add_argument("--write", action="store_true", help="write unit21/calder_release_flow.md")
    a = ap.parse_args()
    if a.init:
        path = REVIEWED if a.reviewed else DRAFT
        if os.path.exists(path):
            sys.exit(f"{os.path.relpath(path)} already exists; delete it first if you want the sample back")
        data = reviewed_data() if a.reviewed else DRAFT_DATA
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
        print(f"Wrote {os.path.relpath(path)}: {len(data['nodes'])} nodes, {len(data['routes'])} routes, "
              f"{len(data['pipelines'])} pipelines, {len(data['features'])} features")
        return
    path = a.file or DRAFT
    d = load(path)
    if a.simulate:
        print_simulation(d, path)
    elif a.plan:
        plan(d, a.plan)
    elif a.write:
        write_report(d, path)
    else:
        print_check(d, path)


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

#### Step 3: Write Calder's draft and the reviewed design

1. Run both commands:

   ```bash
   python unit21/release_flow.py --init
   python unit21/release_flow.py --init --reviewed
   ```

2. Expected:

   ```text
   Wrote unit21/calder_release.json: 8 nodes, 6 routes, 2 pipelines, 4 features
   Wrote unit21/calder_release_reviewed.json: 8 nodes, 5 routes, 2 pipelines, 4 features
   ```

3. Open `unit21/calder_release.json`. It is the design an implementation partner handed Calder. The transport service runs in a new subaccount `calder-admin` (*Transport admin*, in the *Platform* directory of [the BTP account model](https://erpfde.com/topics/btp-account-model/)), connected to SAP Cloud ALM. Its parts:

| Part | What it holds |
| --- | --- |
| `subaccounts`, `destinations` | Each subaccount's stage, and where each node's destination deploys |
| `nodes`, `routes` | Three routes: the distributor order-status app (W02, `EXT_*`), the order-exceptions agent API (W01, `AI_*`), the test certificate archive in the ABAP environment (W06, `CERT_*`) |
| `pipelines` | Two CI/CD jobs, with their hand-over and version numbers |
| `role_assignments` | Who holds which transport role, on which nodes |
| `features` | Four changes for the next release, each with its S/4HANA transport and BTP parts, and how far each has got |
| `simulation` | Last week's exports, the release windows (Tuesdays and Thursdays 18:00 Rockford time, a course value) and one failed import |

The four features:

| ID | Change | Parts |
| --- | --- | --- |
| F-101 | Order status shows the test certificate number | S/4HANA transport `S4DK900431` (the field) + `calder.orderstatus` 1.4.0 |
| F-102 | Order-exceptions agent drafts in the clerk's language | `calder.orderexc` only |
| F-103 | Intercompany price job for `CP-IMP200` (R08 from the fit-to-standard topic) | S/4HANA transport `S4DK900433` only |
| F-104 | Test certificate archive keeps 10 years of PDFs | ABAP environment commit `4f2a9c1` of software component `ZCALDER_CERT` |

#### Step 4: Check the draft

1. Run:

   ```bash
   python unit21/release_flow.py
   ```

2. Expected (the data is fixed, so your output matches exactly):

```text
Calder release flow, as of 2026-11-27 (unit21/calder_release.json)

Nodes
  EXT_DEV                              OK
  EXT_TEST                             FAIL
      D04 FAIL: forwards to production 'Pre-Import': a failed import still moves on
  EXT_PROD                             FAIL
      D03 FAIL: uploads allowed into a production node
      D05 FAIL: production imports run on a schedule (daily 22:00)
      D06 FAIL: calder.orderstatus is customer-facing and deploys 'default' (downtime)
      D07 FAIL: no extension descriptor for calder.orderstatus: it would deploy with the archive's values
      D12 WARN: CTMS_EXT_PROD uses org and space names; a rename breaks it
  AI_DEV                               OK
  AI_TEST                              FAIL
      D02 FAIL: destination CTMS_AI_TEST deploys to calder-ai-prod (prod)
  AI_PROD                              OK
  CERT_DEV                             OK
  CERT_PROD                            OK

Routes
  EXT_DEV -> EXT_TEST                  OK
  EXT_TEST -> EXT_PROD                 OK
  AI_DEV -> AI_TEST                    OK
  AI_DEV -> AI_PROD                    FAIL
      D01 FAIL: dev to prod skips a stage
  AI_TEST -> AI_PROD                   OK
  CERT_DEV -> CERT_PROD                WARN
      D01 WARN: two-system landscape: tests run in the development system

Pipelines
  orderstatus-main                     WARN
      D08 WARN: credential from a 'standard' instance; the export plan is enough
  orderexc-main                        FAIL
      D08 FAIL: Release stage deploys straight to calder-ai-prod
      D08 FAIL: no hand-over to the transport service
      D09 FAIL: next version 2.2.0 isn't above 2.2.0

Roles
  00100288 TransportOperator           FAIL
      D10 FAIL: TransportOperator includes imports that its node attribute doesn't restrict
  00100292 ImportSelectedOperator      OK
  00100316 ImportOperator              OK

Features
  F-101                                FAIL
      D11 FAIL: calder.orderstatus 1.4.0 is in EXT_TEST while S4DK900431 is still in S4D
  F-102                                OK
  F-103                                OK
  F-104                                OK

23 objects: 14 OK, 2 WARN, 7 FAIL
```

3. Read it against the rules:

| Rule | Where it comes from |
| --- | --- |
| D01 Routes go one stage at a time | Course rule; a two-system ABAP landscape gets a warning, not a failure |
| D02 A node deploys to its own stage | Course rule; the AI test node's destination was copied from production |
| D03 No uploads into production nodes | SAP: *Allow Upload to Node* is needed only where files are uploaded; course rule to keep it off in production |
| D04 Test nodes forward On Success or Manual | SAP's forwarding modes: Pre-Import and Post-Import forward failed imports too |
| D05 Production imports by a person in a window | Course rule; SAP lets you schedule imports, which suits test |
| D06 Customer-facing apps deploy blue-green | SAP: default strategy stops the old version first; course rule for the distributor portal |
| D07 Each node has its own extension descriptor | SAP: descriptors aren't forwarded |
| D08 Pipelines hand over and never deploy to production; key from an export instance | SAP suggests the `export` plan for CI/CD; course rule against direct deployment |
| D09 New MTA version per release | SAP: rollback backups happen only when the version changes |
| D10 Developers hold no TransportOperator | SAP: its node attribute doesn't restrict its import tasks |
| D11 S/4HANA transport first at every stage | Course rule: backend before consumer |
| D12 Destinations by space GUID | SAP's recommendation |

> **Note** These verdicts come from made-up Calder data. They show the method, not findings from a real BTP account.

#### Step 5: Replay last week

1. Run the release week against the draft:

   ```bash
   python unit21/release_flow.py --simulate
   ```

2. Expected:

```text
Release week, 2026-11-23 to 2026-11-26 (unit21/calder_release.json)

2026-11-23 09:20  EXT_DEV   export calder.orderstatus 1.3.1 -> request 1001 in EXT_TEST queue
2026-11-23 10:00  EXT_TEST  forward 1001 to EXT_PROD (Pre-Import)
2026-11-23 10:00  EXT_TEST  import 1001 calder.orderstatus 1.3.1: Error (schedule hourly)
2026-11-23 22:00  EXT_PROD  import 1001 calder.orderstatus 1.3.1: Succeeded (schedule daily 22:00)   <- failed in test
2026-11-24 09:20  EXT_DEV   export calder.orderstatus 1.3.2 -> request 1002 in EXT_TEST queue
2026-11-24 10:00  EXT_TEST  forward 1002 to EXT_PROD (Pre-Import)
2026-11-24 10:00  EXT_TEST  import 1002 calder.orderstatus 1.3.2: Succeeded (schedule hourly)
2026-11-24 22:00  EXT_PROD  import 1002 calder.orderstatus 1.3.2: Succeeded (schedule daily 22:00)

In production at the end:
  EXT_PROD: calder.orderstatus 1.3.2, imported 2026-11-24 22:00
  Warning: calder.orderstatus 1.3.1 reached EXT_PROD although its import into test failed
```

3. Read the third and fourth lines. `EXT_TEST` forwarded request 1001 *before* importing it (Pre-Import), the import failed, and `EXT_PROD` imported it at 22:00 on its timer. This is Monday's incident from the foundational layer.

4. Run the same week against the reviewed design:

   ```bash
   python unit21/release_flow.py --simulate --file unit21/calder_release_reviewed.json
   ```

5. Expected:

```text
Release week, 2026-11-23 to 2026-11-26 (unit21/calder_release_reviewed.json)

2026-11-23 09:20  EXT_DEV   export calder.orderstatus 1.3.1 -> request 1001 in EXT_TEST queue
2026-11-23 10:00  EXT_TEST  import 1001 calder.orderstatus 1.3.1: Error (schedule hourly)
2026-11-24 09:20  EXT_DEV   export calder.orderstatus 1.3.2 -> request 1002 in EXT_TEST queue
2026-11-24 10:00  EXT_TEST  import 1002 calder.orderstatus 1.3.2: Succeeded (schedule hourly)
2026-11-24 10:00  EXT_TEST  forward 1002 to EXT_PROD (On Success)
2026-11-24 18:00  EXT_PROD  import 1002 calder.orderstatus 1.3.2: Succeeded (release window, by hand)

In production at the end:
  EXT_PROD: calder.orderstatus 1.3.2, imported 2026-11-24 18:00
```

Version 1.3.1 stays in the test queue with status *Error*, and only 1.3.2 moves on. Production imports it by hand in Tuesday's 18:00 window.

> **Note** The simulation follows SAP's documented forwarding modes and the rule that *Import All* skips requests in *Error*. It is a model of the transport service, not the service itself, and the failed import is a course outcome.

#### Step 6: Plan a hybrid feature

1. Print the plan for F-101 in the draft:

   ```bash
   python unit21/release_flow.py --plan F-101
   ```

2. Expected:

```text
Release plan for F-101: Order status shows the test certificate number
Rule D11: at every stage the S/4HANA transport goes first, then the BTP part

  #  Stage  Where      Step                                                           State
  1  dev    S4D        S4DK900431: release in S4D                                     done
  2  dev    EXT_DEV    pipeline exports calder.orderstatus 1.4.0                      done
  3  test   S4Q        S4DK900431: import into S4Q                                    next
  4  test   EXT_TEST   import calder.orderstatus 1.4.0 (hourly, default)              done, too early
  5  prod   S4P        S4DK900431: import into S4P                                    waits
  6  prod   EXT_PROD   import calder.orderstatus 1.4.0 (daily 22:00, default)         waits

  D11 FAIL: calder.orderstatus 1.4.0 is in EXT_TEST while S4DK900431 is still in S4D
```

   Step 4 says *done, too early*: the app is in test while the field is still only in development. Testers would see errors that have nothing to do with the app.

3. Print it for the reviewed design, where `S4DK900431` has reached `S4Q`:

   ```bash
   python unit21/release_flow.py --plan F-101 --file unit21/calder_release_reviewed.json
   ```

4. Expected:

```text
Release plan for F-101: Order status shows the test certificate number
Rule D11: at every stage the S/4HANA transport goes first, then the BTP part

  #  Stage  Where      Step                                                           State
  1  dev    S4D        S4DK900431: release in S4D                                     done
  2  dev    EXT_DEV    pipeline exports calder.orderstatus 1.4.0                      done
  3  test   S4Q        S4DK900431: import into S4Q                                    done
  4  test   EXT_TEST   import calder.orderstatus 1.4.0 (hourly, default)              done
  5  prod   S4P        S4DK900431: import into S4P                                    next (2026-12-01 18:00)
  6  prod   EXT_PROD   import calder.orderstatus 1.4.0 (in a release window, blue-green) waits
```

The next step is the S/4HANA import in the next release window, and the app waits for it. In SAP Cloud ALM the same plan would be one feature holding both transports.

#### Step 7: Check the reviewed design

1. Run:

   ```bash
   python unit21/release_flow.py --file unit21/calder_release_reviewed.json
   ```

2. From the routes on:

```text
Routes
  EXT_DEV -> EXT_TEST                  OK
  EXT_TEST -> EXT_PROD                 OK
  AI_DEV -> AI_TEST                    OK
  AI_TEST -> AI_PROD                   OK
  CERT_DEV -> CERT_PROD                WARN
      D01 WARN: two-system landscape: tests run in the development system

Pipelines
  orderstatus-main                     OK
  orderexc-main                        OK

Roles
  00100288 ImportSelectedOperator      OK
  00100292 ImportSelectedOperator      OK
  00100316 ImportOperator              OK
  00100317 ImportOperator              OK

Features
  F-101                                OK
  F-102                                OK
  F-103                                OK
  F-104                                OK

23 objects: 22 OK, 1 WARN, 0 FAIL
```

The one warning stays on purpose. W06's ABAP environment has a development and a production system only (sized in [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/)), so its tests run in development. That is a cost decision to record, not an error to hide.

#### Step 8 (optional): Build an MTA and deploy it with an extension descriptor

This step needs your trial, the cf CLI logged in as in the Unit 21 setup, and Node.js (installed for [CAP for architects](https://erpfde.com/topics/cap-for-architects/)). It packs the `hello-btp` app from the setup topic as an MTA and deploys it with test values. Skip it if anything is missing.

1. Create the folder `unit21/release` and in it the file `unit21/release/mta.yaml`:

   ```yaml
   _schema-version: "3.1"
   ID: calder.hello
   version: 1.0.0
   modules:
     - name: hello-mta
       type: python
       path: ../hello-btp
       parameters:
         memory: 128M
         command: python app.py
   ```

2. Create `unit21/release/test.mtaext`, the values for the test stage:

   ```yaml
   _schema-version: "3.1"
   ID: calder.hello.test
   extends: calder.hello
   modules:
     - name: hello-mta
       parameters:
         memory: 256M
   ```

3. Build the archive with the Cloud MTA Build Tool, pinned to a version:

   ```bash
   cd unit21/release
   npx --yes mbt@1.2.50 build
   ```

   Expected last line (your path differs):

   ```text
   INFO the MTA archive generated at: .../unit21/release/mta_archives/calder.hello_1.0.0.mtar
   ```

4. Install the MultiApps plugin for the cf CLI once, as SAP's documentation describes:

   ```bash
   cf add-plugin-repo CF-Community https://plugins.cloudfoundry.org
   cf install-plugin multiapps -f
   ```

5. Deploy the archive with the test descriptor:

   ```bash
   cf deploy mta_archives/calder.hello_1.0.0.mtar -e test.mtaext
   ```

6. Run `cf app hello-mta` and open the route it shows (add `https://` in front). The page reports `"memory_limit_mb": 256`: the descriptor changed the deployment, not the archive.
7. Remove it again, so the trial's memory is free:

   ```bash
   cf undeploy calder.hello -f
   cd ../..
   ```

> **Note** We built the archive with mbt 1.2.50 and checked its `META-INF/mtad.yaml`. We could not reach SAP's Cloud Foundry endpoints from our test environment, so `cf deploy` and `cf undeploy` are untested here; the commands follow SAP's MultiApps plugin documentation.

#### Step 9: Write the release flow document

1. Run against the reviewed design:

   ```bash
   python unit21/release_flow.py --write --file unit21/calder_release_reviewed.json
   ```

2. The last line:

   ```text
   Wrote unit21/calder_release_flow.md
   ```

3. Open `unit21/calder_release_flow.md`. It holds the rules, every object's verdict, the release week replay and an empty decision record. Fill in the decision (the Architecture view below shows one way).

4. Save your work in Git:

   ```bash
   git add unit21/release_flow.py unit21/calder_release.json unit21/calder_release_reviewed.json unit21/calder_release_flow.md
   git commit -m "Unit 21: Calder release flow"
   ```

   If you did Step 8, add `unit21/release/mta.yaml` and `unit21/release/test.mtaext` too, and put `unit21/release/mta_archives/` in your `.gitignore`: archives are build outputs, not source.

#### How the code works

| Part | What it does |
| --- | --- |
| `RULES` and constants | The twelve rules, the three stages, the S/4HANA systems and SAP's success statuses |
| `DRAFT_DATA`, `reviewed_data()` | The partner's draft and the reviewed design: the second is the first with the fixes applied |
| `check()` | One block per section (nodes, routes, pipelines, roles, features), each rule an `if` returning OK, WARN or FAIL with a reason |
| `simulate()` | Walks the week hour by hour: imports per node schedule or release window, forwarding by mode, exports into the next nodes' queues |
| `plan()` | Puts a feature's S/4HANA and BTP steps in stage order, S/4HANA first, and marks each done, next, waits or done too early |
| `write_report()` | The markdown deliverable with an empty decision record |
| `load()`, `main()` | Reads the JSON with clear errors and dispatches the command-line options |

#### 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, then open a new terminal; on macOS/Linux use `python3` until `.venv` is active |
| `No module named ...` | You added an import, or pasted a different script | The script needs built-in modules only; paste it again from Step 2 |
| `calder_release.json not found` | Step 3 hasn't run | Run `python unit21/release_flow.py --init` (add `--reviewed` for the second file) |
| `already exists; delete it first` | `--init` won't overwrite your edits | Delete the file only if you want the sample back |
| `is not valid JSON` | A comma or quote is missing after an edit | VS Code marks the line in red; fix it and run again |
| `KeyError` with a node or system name | A route, feature or role names a node that isn't in `nodes`, or a `reached` value other than `S4D`, `S4Q`, `S4P` or a node name | Fix the spelling; names are case-sensitive, as in the transport service |
| `npx` or `mbt` fails to download (Step 8) | No Node.js, or a proxy blocks npm or GitHub | Install Node.js as in the CAP topic; ask IT for the proxy setting (`HTTPS_PROXY`) |
| `'deploy' is not a registered command` | The MultiApps plugin isn't installed | Step 8.4 |
| cf says `Not logged in` | The cf session ended | `cf login --sso` with the API endpoint from the setup topic |
| Deploy fails with a memory quota error | The trial's memory is used by other apps | `cf stop hello-btp`, or lower the memory in `test.mtaext` |

### The SAP way

What SAP provides for build and promotion, as of 27 November 2026:

- **SAP Continuous Integration and Delivery.** Predefined pipelines, configured in the job editor or in `.sap_cid/config.yaml`; plans `default`, `free`, `trial` and `build-runtime` (for SAP Build customers) ([service plans](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/service-plans-and-metering-9bd6321.md)). It added the gCTS for ABAP Development pipeline on 28 May 2026 and a post-execution step for Cloud Foundry jobs in April 2026.
- **SAP Cloud Transport Management.** Application plans `standard` (50 GB storage, 1 GB per file, 30 days retention, configurable to 90 since November 2026), `free` (500 MB, 7 days, community support only) and `build-runtime`; instance plans `standard`, `export` and `transport_operator` for API access. The standard plan is billed per started GB uploaded per month, aggregated at global account level; imports are free. It is included in the Enhanced and Premium editions of SAP Integration Suite for Integration Suite artifacts, up to a cap ([service plans](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/service-plans-and-metering-17c102d.md)).
- **Design-time integrations.** Several SAP tools start a transport from their own UI. SAP's content table lists, among others, SAP API Management, SAP Analytics Cloud and **Joule Studio projects** (including Joule skills, as MTAs) ([content types](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/supported-content-types-8961dcb.md)).
- **SAP Content Agent service** assembles and exports SAP Cloud Integration and API Management content to the transport service.
- **MTA tooling.** The Cloud MTA Build Tool (`mbt`), the MultiApps cf CLI plugin (`cf deploy`, `cf mtas`, `cf undeploy`), blue-green and incremental blue-green strategies, and the experimental rollback.
- **Project "Piper"** for Jenkins, with `mtaBuild`, `tmsUpload` and `tmsExport` steps.
- **SAP Cloud ALM** for orchestrating transports of the cloud transport service and of CTS in its Features app; also **SAP Solution Manager** Change Request Management for customers still on it, where a node can be marked *Controlled By SAP Solution Manager*.
- **SAP Automation Pilot** has a command catalog for the transport service's nodes, routes and requests ([extended integrations](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/70-integrations/extended-integration-scenarios-7e966f7.md)).
- **SAP Alert Notification service** can send notifications for transport actions and for CI/CD builds.

### Build vs. SAP

| Need | SAP's services | Your own tooling (GitHub Actions, GitLab, Jenkins with Piper) |
| --- | --- | --- |
| Build and test a CAP or Fiori MTA | CI/CD service, predefined stages, little to maintain | Full control of steps and runners; you maintain them |
| Promote one archive dev, test, prod | Transport service with queues, audit trail, roles | Possible with `cf deploy` per stage, but you build the gate and the log |
| Integration Suite or API Management content | Transport service with Content Agent, design-time export | Hard: the content isn't plain code |
| ABAP environment code | *BTP ABAP* content type, or the CI/CD gCTS pipeline for gCTS systems | abapGit and custom scripts (Unit 24) |
| Coordinate with S/4HANA transports | SAP Cloud ALM Features app | A release plan you keep by hand |
| Kyma workloads | CI/CD Kyma Runtime job (CAP with Helm) | GitOps tools such as Argo CD |
| Cost | CI/CD per plan; transport service per GB uploaded | Runner minutes and people's time |

A common combination: your company's Git platform runs the build and tests, and hands the archive to the transport service with the `export` plan. You keep your engineering tools and still get SAP's gate and audit trail.

### Architecture view

**Where it sits.** The release flow touches every BTP stage subaccount and both S/4HANA routes; the transport service and its connection to Cloud ALM sit in a central subaccount.

```mermaid
flowchart TB
  subgraph Git[Git platform]
    R1[order-status repo]
    R2[order-exc repo]
  end
  subgraph ADM[calder-admin]
    TMS[SAP Cloud Transport Management]
  end
  CI[SAP Continuous Integration and Delivery] --> TMS
  R1 --> CI
  R2 --> CI
  TMS --> ET[calder-ext-test] --> EP[calder-ext-prod]
  TMS --> AT[calder-ai-test] --> AP[calder-ai-prod]
  ALM[SAP Cloud ALM] --> TMS
  ALM --> CTS[CTS: S4D to S4Q to S4P]
```

**Non-functional requirements that decide the design:**

| Requirement | Typical target | What breaks if it's missed |
| --- | --- | --- |
| Lead time, merge to test | Under 1 hour | Testers wait, and batch many changes into one risky import |
| Production change window | Twice a week, 18:00 (course value) | Imports during business hours hit users |
| Downtime per release | None for the distributor portal | Distributors see errors during each import |
| Rollback time | Under 30 minutes, rehearsed | A bad release stays live while people improvise |
| Audit trail | Every production import with who and when | An auditor's sample can't be answered |
| Artifact retention | Long enough to re-import the last release | SAP's default 30 days can drop the archive you need |

**Integration and identity.** Three identities need design. The pipeline reaches the transport service with a service key from an `export` instance, stored as a CI credential. Each target node reaches its space through a destination to the deploy service, with a technical platform user; with a custom identity provider SAP offers OAuth2Password authentication for it. People act through role collections built on the transport service's role templates. SAP Cloud ALM uses its own service key for the transport service and its own connection to each managed system's CTS. Keep all of these in the credential register from [services, instances and bindings](https://erpfde.com/topics/btp-services-and-bindings/).

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

- **Context:** BTP apps on Cloud Foundry (W01, W02), one ABAP environment app (W06), one Kyma workload (W04), S/4HANA `CP10` on Private Edition with CTS; last week a version that failed in test reached production.
- **Options:** (1) pipelines deploy to every stage directly, (2) pipelines build and deploy to development, then hand over to SAP Cloud Transport Management, coordinated with CTS in SAP Cloud ALM, (3) CTS+ carries BTP archives inside S/4HANA's transport system.
- **Decision:** option 2. The transport service runs in `calder-admin`; test nodes forward On Success; production imports by operations in the Tuesday and Thursday windows, blue-green for customer-facing apps; every feature with S/4HANA parts is planned backend first.
- **Consequences:** developers lose direct production access; operations need the ImportOperator role restricted to production nodes; every release bumps the MTA version; Kyma (W04) keeps its own pipeline with a manual approval; Cloud ALM must hold both transports of a hybrid feature, and if it can't in Calder's tenant, the release manager keeps the plan from Step 6.

**What a design review will ask:**

1. What stops a package that failed in test from reaching production, in configuration and in roles?
2. Is production running the exact archive that passed test, and how do you prove it?
3. Which features have S/4HANA parts, and who checks the order at each stage?
4. How long does a rollback take, what can't it undo (services, database), and when was it rehearsed?
5. Who can import into production, and how is that list reviewed?

### Production concerns

- **Pipeline credentials are shared.** SAP's [credential handling](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/credential-handling-e26a096.md) page says credentials in a CI/CD subscription can be used by all its jobs, every administrator can potentially read them, and anyone with write access to a connected repository can use them indirectly in a pipeline run. SAP recommends one subscription per team, not per company. For Calder that means the transport service key in the portal team's subscription is, in effect, held by everyone who can push to that repository; protect the main branch accordingly.
- **Security and authorizations.** Keep the LandscapeOperator role to the platform team: whoever changes routes can bypass every gate. Restrict import roles by node attribute, and remember the TransportOperator caveat. The deploy destinations hold platform credentials; treat them like any other secret.
- **Evaluation.** Each stage needs a test that can fail the release: unit tests in the build, WebdriverIO or API tests in acceptance, and a smoke test after the production import. For AI apps, the evaluation gate from Unit 7 belongs in the acceptance stage, so a prompt or model change is tested like code.
- **Cost.** Uploads are billed per started GB, so large archives uploaded many times a day add up; imports are free. Blue-green doubles memory during the switch, which the quota must allow.
- **Operations.** Watch the storage limit (50 GB on the standard plan) and set file retention to cover your rollback need. Send transport notifications to the team that imports. Review the landscape action logs after any change to nodes and routes. [Observability on BTP](https://erpfde.com/topics/btp-observability/) covers monitoring the apps themselves.
- **Clean core.** The release flow keeps S/4HANA clean only if its own parts are released objects: transports should carry released-API extensions and configuration, as in [extension patterns](https://erpfde.com/topics/btp-extension-patterns/). The flow doesn't make an unreleased modification safer; it just moves it faster.

### Where AI fits

Three things change when the apps in the flow are AI apps:

- **More things to release than code.** A prompt, a model version or a tool description changes behavior as much as code does. Keep them in Git, version them with the MTA, and let the acceptance stage run the evaluation set. [AI supply-chain controls](https://erpfde.com/topics/ai-supply-chain-controls/) showed what happens when a dependency changes without a gate.
- **Agents in the transport landscape.** SAP's content table lists Joule Studio projects as MTA content with design-time export, so agents built there travel the same routes as apps. Give their nodes the same forwarding and role rules.
- **AI helping the release manager, not replacing the gate.** A model can draft the release plan or summarize why an import failed from its log. Starting a production import stays a human decision, because it changes production.

As far as this run could find, SAP's documentation for the transport service and the CI/CD service describes no AI features as of 27 November 2026.

### Pitfalls

- **Leaving Pre-Import on test nodes.** It is the default, and it forwards failed imports.
- **Scheduling production imports.** Fine for test, a timer in production imports whatever arrived.
- **Rebuilding per stage.** Then production runs an archive nobody tested.
- **Putting stage values in the archive.** Use extension descriptors, and upload one to every node: they don't travel.
- **Reusing version numbers.** It removes the rollback backup and makes the audit trail ambiguous.
- **Giving developers TransportOperator.** Its node attribute doesn't restrict its imports.
- **Releasing the app before its S/4HANA field.** Plan hybrid features backend first, at every stage.
- **Assuming blue-green covers the database.** It switches apps; services and schemas must work for both versions.

### Exercise

Add a fifth feature and see the order rule work.

1. Open `unit21/calder_release_reviewed.json`.
2. Under `features`, add a feature whose agent change needs a new S/4HANA transport:

   ```json
   {"id": "F-105", "title": "Agent explains delivery block reasons",
    "parts": [{"kind": "abap", "item": "S4DK900436", "reached": "S4D"},
              {"kind": "mta", "item": "calder.orderexc 2.4.0",
               "path": ["AI_DEV", "AI_TEST", "AI_PROD"], "reached": "AI_TEST"}]}
   ```

3. Run `python unit21/release_flow.py --file unit21/calder_release_reviewed.json`. F-105 fails D11 and the last line reads `24 objects: 22 OK, 1 WARN, 1 FAIL`.
4. Run `python unit21/release_flow.py --plan F-105 --file unit21/calder_release_reviewed.json`. Step 4 shows *done, too early*.
5. Fix it as the release manager would: the transport is imported into the quality system. Change `"reached": "S4D"` to `"reached": "S4Q"` for `S4DK900436` and run the check again.
6. Now break a gate on purpose: change `EXT_TEST`'s `"forwarding"` to `"Post-Import"` and run `--simulate --file unit21/calder_release_reviewed.json`. Version 1.3.1 reaches `EXT_PROD`'s queue and is imported in Tuesday's window. Change it back to `"On Success"`.
7. Run `--write --file unit21/calder_release_reviewed.json` and fill in the decision record with the ADR above, adding F-105's plan.

**Done when:** the check prints `24 objects: 23 OK, 1 WARN, 0 FAIL`, `--plan F-105` shows the S/4HANA import into `S4P` as the next step, and your decision record is filled in. The release flow feeds the DevOps topic in Unit 28 and the transport topic in Unit 29.

### Check yourself

1. In the CI/CD service's Release stage, what is the difference between `export` and `upload`?
   - A. Export sends the archive to production directly; upload sends it to test
   - B. Export queues the request at the nodes after the named node; upload queues it at the named node
   - C. Export works only with SAP Cloud ALM; upload works only without it
   - D. Export changes the transport request later; upload seals it at once

   Answer: B. With export, the named node is the starting point and the request lands in the follow-on queues. With upload, it lands in the named node's own queue. In both cases the request can't be changed afterwards.

2. Calder's test node uses SAP's default forwarding mode and the import into test fails. Where is the request?
   - A. Only in the test queue, with status Error, until someone resets it
   - B. Deleted from every queue, because the import failed
   - C. Also in the production queue, forwarded before the test import ran
   - D. Back in the development node, waiting for a new export

   Answer: C. Pre-Import is the default, and it forwards to all target nodes before importing in the current node. Only On Success or Manual keeps a failed request out of production.

3. Why does every transport node that imports Calder's portal need its own extension descriptor?
   - A. Because the deploy service rejects archives that carry stage values
   - B. Because descriptors expire after 30 days like uploaded files
   - C. Because each node can hold only one MTA at a time
   - D. Because the transport service doesn't forward descriptors between nodes

   Answer: D. SAP states that extension descriptors aren't forwarded to target nodes, so each node needs its own upload. Otherwise the import uses the archive's own values, which are usually development values.

4. A developer has TransportOperator restricted with `TmsNodesTransportOperator` to the test nodes. What can still go wrong?
   - A. The developer can still import into production nodes
   - B. The developer can no longer reset requests in test nodes
   - C. The restriction applies to every user of the subaccount
   - D. The developer can change transport routes in production

   Answer: A. SAP's security page says that attribute restricts the TransportOperator tasks but not the import tasks the role includes. Restrict imports with ImportSelectedOperator and `TmsNodesImportSelected` instead.

5. The team redeploys `calder.orderexc` as 2.2.0 again after a fix, using blue-green with backup. What do they lose?
   - A. The blue-green switch, which needs a higher version
   - B. A rollback target, since backup happens only when the version changes
   - C. The extension descriptors, which bind only to new versions
   - D. Nothing, because the deploy service compares content, not versions

   Answer: B. SAP's experimental rollback backs up the previous version only when the MTA version changes. Reusing a version leaves no different version to switch back to, and blurs the audit trail too.

6. F-101's app is in the BTP test subaccount while its S/4HANA field is still in development. What do you do?
   - A. Import the app into production too, so both sides catch up together
   - B. Rebuild the app without the field and promote that version instead
   - C. Import the transport into S4Q first, then test the feature as one
   - D. Nothing: the transport service waits for S/4HANA automatically

   Answer: C. The app depends on the field, so testers would see errors unrelated to the app. The S/4HANA transport goes first at every stage; the transport service doesn't know about CTS, so a release plan or SAP Cloud ALM must enforce it.

7. Why can't Calder's MES listener on Kyma use the same transport route as the portal?
   - A. Kyma apps must be built with the npm build tool, which can't export
   - B. The transport service runs only in the Cloud Foundry environment
   - C. Kyma deployments need a CTS+ transport request in S/4HANA
   - D. None of the transport service's content types is a Kyma deployment

   Answer: D. The transport service carries MTAs, BTP ABAP references, application content and XSC delivery units. A Kyma app is promoted by its pipeline, so that pipeline needs its own manual gate before production.

8. For the ABAP environment, why does SAP recommend exporting a commit ID rather than a branch?
   - A. Because the transport service can't read branch names
   - B. Because a branch's latest commit can change, so the import isn't repeatable
   - C. Because commit IDs make the import faster in the target system
   - D. Because branches can only be imported through SAP Cloud ALM

   Answer: B. A reference by branch points to whatever is newest when the import runs. A commit ID pins the exact code that was tested, the same "build once" principle as for MTAs.

## Sources

- [What Is SAP Cloud Transport Management (SAP-docs on GitHub, last commit 2026-11-17, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/what-is-sap-cloud-transport-management-5fef9d6.md): transports development artifacts and application-specific content between accounts of different environments; audit trail and separation of concerns; cross-global-account transports in Cloud Foundry, within the same global account in the ABAP environment; complements CI/CD; scheduled imports; subscription for the UI, a service instance for API access
- [Supported Content Types (SAP Cloud Transport Management)](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/supported-content-types-8961dcb.md): MTA archives (not without modules), BTP ABAP references (software component, commit, branch, tag), application content, XSC delivery units; transports from an application, a CI pipeline or a local file; supported content table incl. HTML5 apps, Joule Studio projects, API Management, SAP Analytics Cloud
- [Create Transport Nodes (SAP Cloud Transport Management)](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/20-configure-landscape/create-transport-nodes-f71a4d5.md): forwarding modes Pre-Import (default), Post-Import, On Success, Manual; Allow Upload to Node; Send Notifications; Controlled By SAP Solution Manager; Virtual Node; content types Application Content, MTA, BTP ABAP, XSC Delivery Unit; deployment strategy default or blue-green, testing phase skipped
- [Security: role templates and node attributes (SAP Cloud Transport Management)](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/60-security/security-51939a4.md): Administrator, LandscapeOperator, TransportOperator, ImportSelectedOperator, ImportOperator, ExportOperator, Viewer; attributes TmsNodesTransportOperator, TmsNodesImport, TmsNodesExport, TmsNodesImportSelected; TmsNodesTransportOperator doesn't restrict the import tasks in TransportOperator; restricted role wins over unrestricted
- [Service Plans and Metering (SAP Cloud Transport Management)](https://github.com/SAP-docs/btp-cloud-transport-management/blob/main/docs/service-plans-and-metering-17c102d.md): standard, build-runtime and free application plans; standard 50 GB storage, 1 GB per file, 30 days retention configurable to 90; free 500 MB and 7 days; instance plans standard, export (for CI/CD pipelines), transport_operator; billed per started GB uploaded, metered once, imports free; included in Integration Suite Enhanced and Premium up to a cap
- [Configure a Cloud Foundry Environment Job in Your Repository (SAP Continuous Integration and Delivery, SAP-docs on GitHub)](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/configure-a-cloud-foundry-environment-job-in-your-repository-bfe48a4.md): .sap_cid/config.yaml; stages build (mta, npm, maven), additionalTests, malwareScan, acceptance (cfDeploy, webdriverIoTests), compliance (sonarScan), release (cfDeploy, cloudTransportManagement with nodeOperation export or upload, nodeName, credential); blue-green only with the mta build tool and extra memory quota; build retention 1-28 days, up to 99 builds; free and trial jobs deactivated after a week unchanged
- [Integrate Cloud Transport Management into Your Job (SAP Continuous Integration and Delivery)](https://github.com/SAP-docs/btp-continuous-integration-and-delivery/blob/main/docs/cicd/integrate-cloud-transport-management-into-your-job-a0f029b.md): Export from (request goes to the queues of the nodes after the export node) vs Upload to (request goes to the upload node's own queue); the transport request can't be changed; connect to SAP Cloud Transport Management or to SAP Cloud ALM, which includes it (export only)
- [Defining MTA Extension Descriptors (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/defining-mta-extension-descriptors-50df803.md): .mtaext files with extends; environment-specific data such as scaling and credentials; one archive deployed with different configurations; chains applied in order with cf deploy -e
- [(Experimental) Rollback of Multitarget Applications (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/30-development/experimental-rollback-of-multitarget-applications-d612be9.md): experimental; only Cloud Foundry apps and user-provided services; needs blue-green with --backup-previous-version; backup kept 3 days; backup only when the MTA version changes
- [SAP Cloud Transport Management Service setup (SAP Cloud ALM Setup and Administration, SAP-docs on GitHub, last commit 2026-11-11)](https://github.com/SAP-docs/cloud-alm-setup-admin-guide/blob/main/docs/02_integration_and_config_options/sap-cloud-transport-management-service-8b4af2f.md): connecting the transport service to SAP Cloud ALM makes its landscape and transports visible for the Features app; recommends a central administrative subaccount; BTP ABAP needs Import Up To, not Import Selected; no imports into nodes controlled by SAP Solution Manager
