# File and batch interfaces done properly: transfer, completeness, duplicates, restart and reconciliation

> Design file interfaces that never load half a file or a file twice, restart cleanly, reconcile nightly, and come with a specification an owner can sign.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/file-and-batch-interfaces/
- Updated: 2026-11-30
- 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

A **file interface** moves many records at once: one system writes a file, another picks it up on a schedule and loads it. A **batch interface** is the same idea with a job doing the work at a set time. Banks, payroll providers, carriers, test benches and old reports still work this way, and they will for years.

Files fail in quiet ways. A reader picks up a file the writer hasn't finished. The same file arrives twice under a new name. A load stops at record 70 and the rerun loads records 1 to 70 again. A row is rejected and nobody notices that 119 of 120 orders reached the other side. None of these shows up as an error unless you designed for it.

"Done properly" means six things, all of which you can write into one page of specification:

1. **Secure transfer**: encrypted channels, keys instead of passwords, signed or encrypted content where the data is sensitive.
2. **Completeness**: the reader knows the file is finished and checks a record count and a total against a control line.
3. **No duplicates**: every file carries a run ID, and the receiver remembers what it has loaded.
4. **Restartability**: a stopped load can run again without doubling anything.
5. **Scheduling**: the job runs after what it depends on, has a cut-off, and someone hears when the file is late.
6. **Reconciliation**: every night, someone compares the source, the file and the target, and owns the differences.

The decision for a leader: **no file interface goes live without a signed specification that answers these six points, with a named owner.** This topic uses the course's fictional company, **Calder Pumpworks**, and three of its file interfaces.

### Why it matters to the business

File interfaces carry money and plans. When one fails quietly, people act on wrong numbers until someone notices. Using Calder (all numbers are course values):

- **Half a file looks like a whole one.** Calder's nightly file of open order items for the CRM has 120 lines. If the CRM reads it while the report is still writing, it can load 47 lines and report success. Sales calls customers about orders the CRM doesn't show.
- **The same statement twice.** If the bank's statement file is sent again under a new name, a check on the file name alone lets it through. Cash looks higher than it is until the reconciliation catches it.
- **The rerun that doubles.** A load that stops after 70 records and is simply started again inserts those 70 a second time.
- **The missing row nobody owns.** One order item with an impossible date is rejected. Without a reconciliation report and an owner, 7,900.00 USD of orders silently disappear from the CRM.
- **Security.** Plain FTP sends credentials and content in readable form. A program that builds a file path from user input can be tricked into reading or writing files it shouldn't.

The cost of doing it right is small at design time: a control line, a run ID, a done file, a report. Retrofitting after an incident costs far more, because by then wrong data has already reached people.

### How SAP does it

As of November 2026, these SAP pieces cover file and batch interfaces:

- **SAP Integration Suite, Cloud Integration** reads and writes files over SFTP and FTP. Its SFTP sender adapter can wait for a done file or for the file to stop changing, keeps a record of processed files, and archives or deletes them after processing. It reaches servers inside your network through the Cloud Connector ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). Plant file shares on NFS need the Edge Integration Cell, covered in the [edge topic](https://erpfde.com/topics/edge-integration-cell/).
- **SAP Process Orchestration**, where you still run it, has file and FTP adapters with similar controls, such as writing to a temporary file first ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/44/69d7cfa4b633eae10000000a1553f6/content.htm)). The [PI/PO migration topic](https://erpfde.com/topics/migrating-from-pi-po/) covers moving them.
- **Inside ABAP systems**, programs read and write server files through **logical file names**, maintained in transaction `FILE`, so paths aren't hard-coded and can be checked ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/fc/eb3dc4358411d1829f0000e829fbfe/content.htm)).
- **Scheduling** in SAP S/4HANA uses **application jobs**, with the *Application Jobs* and *Application Job Templates* apps ([SAP Learning](https://learning.sap.com/courses/administrating-sap-s-4hana-cloud-public-edition/introducing-application-jobs_cf77594e-9dd1-454b-b8d1-05079dfee508)).
- **Banks** get their own managed channel: **SAP Multi-Bank Connectivity** exchanges payment files and statements with banks over SWIFT, bank APIs, SFTP or EBICS, with message-level security ([SAP Community](https://community.sap.com/t5/financial-management-blog-posts-by-sap/sap-multi-bank-connectivity-mbc-all-you-need-to-know/ba-p/13619921)).

SAP gives you the transport and the switches. The run ID, the control line, the reconciliation and the owner are yours to design.

### A decision guide: keep, fix or replace each file interface

| Situation | What to do | Why |
| --- | --- | --- |
| A partner only works with files (bank, payroll provider, carrier) | Keep files; make them meet the six points | The partner sets the style; your controls decide the risk |
| Bank payments and statements over a self-built SFTP link | Plan a move to SAP Multi-Bank Connectivity | A managed channel with message-level security and bank formats |
| A nightly CSV from a custom report feeding another app | Fix what's unsafe now; plan events or a released API | Custom reports reading SAP data are hard to keep through upgrades |
| Plant equipment that drops result files on a share | Keep files; add a done file and a reconciliation per serial | The equipment can't call an API; the share is the interface |
| Large data loads for analytics | Use an extraction path, not a hand-built file | The [reporting topic](https://erpfde.com/topics/reporting-and-analytics-architecture/) covers the options |
| Files over plain FTP or email | Replace the transport first | Credentials and content travel readable |

> **Note** **For functional consultants.** File interfaces change your test plan more than your configuration. Add test cases for a file that arrives half written, the same file sent twice, a load that stops in the middle, one bad record, and no file at all by the cut-off. Agree who reads the reconciliation report each morning and what they do with a difference.

### Questions to ask

- Do we have a list of every file interface, with an owner and an error contact for each?
- How does the reader know a file is complete? Is there a control line with a count and a total?
- What happens if the same file is sent twice under a different name?
- If a load stops halfway, what does a rerun do?
- What runs before this job, what is its cut-off, and who is alerted when the file is late?
- Which files contain payments, bank data or personal data, and how are they signed or encrypted?
- Who compares source and target every day, and who fixes the difference?
- How long are processed files kept, and can we replay one?

### Common misconceptions

- **"Files are old, so we should replace them all."** Many partners only offer files, and files are often the right style for large, once-a-day volumes. The risk is in missing controls, not in the format.
- **"SFTP makes a file interface safe."** It protects the transfer. It doesn't tell the reader the file is complete, stop duplicates or prove the load was whole.
- **"The job finished, so the data is there."** SAP's own training notes that a finished job doesn't automatically mean a successful one. Only a reconciliation proves the data arrived.
- **"Checking the file name stops duplicates."** A resend under a new name passes. A run ID or a content checksum catches it.
- **"If it fails, we just run it again."** Only if the load was designed to be repeated. Otherwise the rerun doubles what had already loaded.

### Key terms

- **File interface:** an interface in which one system writes a file and another reads and loads it.
- **Batch job:** a program that runs at a set time or after another job, without a user waiting.
- **SFTP:** file transfer over an encrypted SSH connection.
- **Done file:** an empty file written after the data file to say "this file is complete".
- **Control record (trailer):** a last line with the record count and a total, so the reader can check completeness.
- **Hash total:** a sum of a field, such as net value, used only to check that nothing was lost or changed.
- **Run ID:** a unique identifier for one run of the interface, carried in the file name and header.
- **Idempotent load:** a load that gives the same result however many times it runs, usually by updating records by their key.
- **Cut-off:** the time by which a file must arrive or be processed before someone acts.
- **Reconciliation:** comparing counts and totals in the source, the file and the target, and resolving differences.

### Check yourself

1. Calder's CRM loaded 47 of 120 order items and reported success. Which control would have stopped this?
   - A. Moving the file transfer from FTP to SFTP
   - B. A done file and a trailer with count and total
   - C. Running the CRM load one hour later each night
   - D. Checking the file name against yesterday's file name

   Answer: B. The reader took a file that was still being written. A done file tells it to wait, and a trailer with a count and total lets it reject an incomplete file. SFTP protects the transfer, not completeness.

2. The bank resends yesterday's statement file under a new name. What catches it?
   - A. A duplicate check on the file name in the reader
   - B. A larger maximum file size in the SFTP adapter
   - C. A check on the run ID or a checksum of the content
   - D. Deleting each file from the server after reading it

   Answer: C. A new name defeats a check on the file name. The run ID in the header or a checksum of the content is the same in both files, so the second load is skipped.

3. A nightly load stops after 70 of 120 records. What must the design guarantee before anyone reruns it?
   - A. That the rerun starts at a quieter time of night
   - B. That the first 70 records are deleted by hand first
   - C. That the file is renamed so the reader picks it up again
   - D. That the rerun updates by key, so nothing doubles

   Answer: D. An idempotent load, which updates records by their business key, or a load that resumes after a checkpoint gives 120 records however often it runs. A rerun that inserts from the top creates 70 duplicates.

4. Which file interface should Calder move to SAP Multi-Bank Connectivity?
   - A. The nightly open-order file from S/4HANA to the CRM
   - B. Bank statements sent over a self-built SFTP link
   - C. Test bench result files on the Rockford plant share
   - D. The supplier's monthly price list for purchasing

   Answer: B. Multi-Bank Connectivity is SAP's managed channel to banks for payment files and statements, with message-level security. The other interfaces aren't bank traffic; they need their own fixes or a different target.

5. The job log says the nightly export finished. What should a leader still ask for?
   - A. A screenshot of the job log for the audit evidence file
   - B. A second run of the job the following night
   - C. Proof that the file was written over SFTP
   - D. The reconciliation of counts and totals, and its owner

   Answer: D. SAP's own training notes that a finished job is not automatically a successful one. Only a comparison of source, file and target shows whether every record arrived, and an owner makes sure differences are fixed.

6. What should a file interface specification always name?
   - A. An owner, an error contact and who resolves differences
   - B. The programming language used for the export report
   - C. The vendor of the SFTP server at the receiving end
   - D. The number of developers who built and tested the interface

   Answer: A. Most file failures are quiet. A named owner, an error contact and an owner of reconciliation differences make sure someone acts. The technical details matter less than who is accountable.

## Deep layer

### Mental model

A file interface is a **promise about a set of records**, not about a file. Every design decision answers one of five questions about that set:

1. **Is it complete?** The reader must know the writer has finished (done file, temporary name, or a wait), and must check a control line before loading.
2. **Is it new?** The receiver must recognize a set it has already loaded, by a run ID or a checksum, and records it already holds, by a business key.
3. **Can it be loaded again safely?** A load that stops halfway must be repeatable without doubling: update by key, or resume from a checkpoint.
4. **Did it arrive on time?** The job runs after its predecessor, and a cut-off triggers an alert when nothing came.
5. **Did every record arrive?** Source, file and target counts and totals are compared every run, and someone owns the difference.

Transport security (SFTP, keys, signatures) is the sixth concern, and the only one most teams remember. The other five are where file interfaces actually fail.

### How it works

#### The life of one file

```mermaid
sequenceDiagram
  participant J as Job in S/4HANA
  participant W as Writer
  participant S as SFTP server
  participant R as Reader (Cloud Integration)
  participant T as Target app
  J->>W: start after predecessor job
  W->>S: write data file (temp name)
  W->>S: rename, then write .done
  R->>S: poll: data file and .done present?
  R->>R: check header, trailer, run ID
  R->>T: load by business key
  T-->>R: counts and totals loaded
  R->>S: move file to archive
  R->>R: reconciliation report to owner
```

Each arrow is a place to fail. The rest of this section walks through the controls SAP's tools offer at each one, and the ones you must add.

#### Completeness: never read a half-written file

A reader that polls a folder can see a file the moment its first bytes land. Two families of controls stop it from reading too early:

- **Writer-side.** Write under a temporary name and rename when done, or write a separate **done file** after the data file. SAP Process Orchestration's receiver FTP adapter offers *Use Temporary File* with a *Temporary File Name Scheme*, and file construction modes such as *Add Time Stamp*, *Add Message ID* and *Add Counter* for unique names ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/44/69d7cfa4b633eae10000000a1553f6/content.htm)).
- **Reader-side.** Cloud Integration's SFTP sender adapter has a *Read Lock Strategy* with four options ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)):

| Option | What it does | When it is enough |
| --- | --- | --- |
| *None* (default) | Reads the file as soon as it sees it | Only when the writer uses a temporary name and renames |
| *Content Change* | Waits until length and modification time stop changing for at least a second | A fallback when the writer can't change; a writer that pauses can still fool it |
| *Done File Expected* | Waits for a done file in the same folder, by default `${file:name}.done` | The safest agreement with a writer you can influence |
| *Rename* | Renames the file on the server before reading it | Stops two readers from taking the same file; doesn't prove the writer is finished |

In PI/PO, the sender file adapter's *Msecs to Wait Before Modification Check* plays the role of *Content Change* ([SAP Learning](https://learning.sap.com/courses/sap-java-process-integration/configuring-a-sender-file-adapter_f8626d18-4742-432b-8266-8c12b4b281be)). Look for it in a migration: if it was set, the writer probably never signaled completion.

Even with a done file, the reader checks the content. A **control record** in the course's layout looks like this:

```text
H;I03;R20261130-0200;2026-11-30T02:04:00
D;1003001;10;10000001;CP-ES200;1;3950.00;USD;2026-12-01
...
T;120;951210.00
```

The header carries interface and run ID; the trailer carries the record count and a **hash total** of net value. A file without a trailer, or whose rows don't add up to it, is rejected whole. Standard formats have their own equivalents, such as the entry counts and sums inside an ISO 20022 statement; use them rather than inventing a second check.

#### Duplicates: the same set, twice

Files are delivered **at least once**. A sender that didn't get a confirmation sends again; an operator resends a file "to be sure". SAP's guidance for exactly-once flows in Cloud Integration says the same of messages in general: guaranteed delivery gives at-least-once, and the receiver must be idempotent and discard duplicates, using a message ID or a value in the payload such as an order ID ([SAP blog](https://blogs.sap.com/2021/12/06/integration-flow-design-guidelines-for-exactly-once-scenarios/)).

Three levels of check, from weakest to strongest:

| Check | What it catches | What it misses |
| --- | --- | --- |
| File name | The same file picked up twice | A resend under a new name |
| Run ID or content checksum | Any resend of the same set | A corrected file for the same run (decide whether it replaces) |
| Business key in the target | Any record loaded twice, from any file | Nothing, if every record has a stable key |

The SFTP sender's *Keep File and Mark as Processed in Idempotent Repository* is a file-level check. SAP's documentation says the database repository identifies a file by user, host and file name, not by size or timestamp, and that the idempotent option doesn't work for file names longer than 100 characters ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). Use it, but don't rely on it alone. Inside a flow, the *Idempotent Process Call* step records an ID once a step has succeeded; the [Cloud Integration flows topic](https://erpfde.com/topics/cloud-integration-flows-in-depth/) covers it and its limits.

#### Restart: a load that stops halfway

A load commits in chunks. If it stops after 70 of 120 records, the target holds 70. The rerun then has three choices:

- **Insert from the top**: 190 records, 70 duplicates. Never acceptable for anything that posts.
- **Resume after a checkpoint**: the load stores how far it got and continues from record 71.
- **Upsert by business key**: insert or update each record by its key (order and item, statement and entry). Any number of reruns gives the same result.

Upsert is simpler to operate, because nobody has to know where the load stopped. A checkpoint suits targets that can only insert.

#### Order and batches in Cloud Integration

Two SFTP sender settings decide how files in one poll are handled ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)):

- *Max. Messages per Poll* (1 to 500, default 20). Each runtime node polls on its own. SAP's page says that after an error the rest of the batch continues, so a failed file may be retried later and **out of order**.
- *Poll on One Worker Only*, with *Sorting* by file name, size or timestamp. SAP's page says it is needed for order-sensitive processing, and that strict order needs one message per poll.

If order matters (a price list that replaces yesterday's, a correction after an original), sort by a name that carries the run ID, poll on one worker and take one file at a time. If it doesn't, keep the defaults and let the business key absorb repeats.

For large files, SAP's tutorial on migrating advanced file selection uses *Poll Enrich*, file name patterns and an *Iterating Splitter*, which has a *Streaming* option ([SAP Developers](https://developers.sap.com/tutorials/ci-sftp-file-polling.html)). Splitting a file into records is where you lose the file's control totals: check the trailer before you split.

#### After processing: archive, don't just delete

The SFTP sender's *Post-Processing* options are *Delete File* (default), *Keep File and Mark as Processed in Idempotent Repository*, *Keep File and Process Again* and *Move File* to an archive directory. SAP's page describes *Keep File and Process Again* as an option for testing ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). In production it reads the same file on every poll.

Archiving keeps a replay source. The [edge topic](https://erpfde.com/topics/edge-integration-cell/) already relies on it: Calder's test bench share keeps files for 30 days, which is what lets the edge replay them after an outage.

#### Files inside ABAP systems

When an ABAP program writes or reads a file on the application server (a custom export report, an upload), three SAP controls apply:

- **Logical file names.** File names in ABAP are physical and operating-system specific. Logical names map to physical paths through tables, `FILE_GET_NAME` returns the physical name, and you maintain them in transaction `FILE` ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/fc/eb3dc4358411d1829f0000e829fbfe/content.htm)).
- **Path validation.** `FILE_VALIDATE_NAME` checks that a physical name fits a logical file's rules, to counter path traversal; a logical file of data format `DIR` covers relative names, and the exceptions are `VALIDATION_FAILED` and `LOGICAL_FILENAME_NOT_FOUND`. Validate again just before `OPEN DATASET` if the name may have changed ([SAP Help Portal](https://help.sap.com/saphelp_em92/helpdata/en/38/bffdace37d4429998beb1e4acb11b7/content.htm)).
- **Authorizations.** `OPEN DATASET` works in the `DIR_HOME` directory by default and can reach any file if input isn't restricted. Authorization object `S_DATASET` is checked for all file access, and `S_PATH` for paths protected in table `SPTH` ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/a8/d3c2aa14b04bf8bb2718aefeb478f5/content.htm)).

> **Note** Server file access like this belongs to classic ABAP in ECC and in S/4HANA on premise or in a private cloud. In ABAP Cloud and SAP S/4HANA Cloud Public Edition, plan files through released APIs and Integration Suite instead; Unit 24 covers what ABAP Cloud allows.

#### Scheduling and cut-offs

A batch job should start **after its predecessor**, not at a clock time that usually works. Calder's open-order export must run after the night billing job, or it misses the orders billed that night.

In SAP S/4HANA, jobs are **application jobs**, created from templates in the *Application Jobs* app, with *Maintain Job Users* for the user a job runs as. Jobs run in a user's context. Their statuses are *Scheduled*, *In Process*, *User Error*, *Failed*, *Canceled* and *Finished*, and SAP's training warns that *Finished* doesn't automatically mean successful: read the job log ([SAP Learning](https://learning.sap.com/courses/administrating-sap-s-4hana-cloud-public-edition/introducing-application-jobs_cf77594e-9dd1-454b-b8d1-05079dfee508)). That lesson is from the Public Edition course; on-premise and private cloud systems also keep classic background jobs.

Every scheduled file gets a **cut-off** (the time by which it must have arrived) and a **late alert** to a named contact. A poll that runs every 10 minutes needs one too: "no file for two hours during a shift" is an incident at the test bench.

#### Security

- **Transport.** SFTP, not FTP. The SFTP adapter supports public key authentication, and reaches servers inside your network with *Proxy Type* *On-Premise* through the Cloud Connector and its location ID ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). The [BTP connectivity topic](https://erpfde.com/topics/btp-connectivity/) covers location IDs.
- **Content.** Payment files and statements need signatures or encryption on the content, not just on the channel. SAP Multi-Bank Connectivity requires message-level security between the customer and the service ([SAP Community](https://community.sap.com/t5/financial-management-blog-posts-by-sap/sap-multi-bank-connectivity-mbc-all-you-need-to-know/ba-p/13619921)). Where you exchange files with a bank yourself, agree PGP or the bank's own scheme.
- **Paths and users.** Validate paths in ABAP, restrict `S_DATASET`, and give each SFTP user one folder.

#### Reconciliation

Reconciliation compares three numbers each run: what the source holds, what the file says (trailer), and what the target loaded. Each comparison catches different failures:

| Comparison | Catches |
| --- | --- |
| Source vs file | The export missed records (wrong selection, run before its predecessor) |
| File vs trailer | The file is incomplete or damaged |
| File vs target | Records rejected or lost during the load |

The report names its owner, and a difference has a due time ("by 08:00"). For bank statements, the classic check is the closing balance per account against the bank's figure.

### Build it yourself: review Calder's file interfaces and write a specification

You will run a lab with three parts. **Review** checks three of Calder's file interfaces against twelve course rules. **Spec** writes a one-page specification for an interface, from a template. **Simulate** shows why the rules exist: a half-written file, a renamed resend, a load that stops halfway, and a reconciliation that finds a missing row.

```mermaid
flowchart LR
  I[--init] --> D[specs_draft.json]
  I --> V[specs_reviewed.json]
  I --> F[sample file + .done]
  D --> R[review: FB01-FB12]
  V --> R
  V --> S[spec I03] --> M[spec_I03.md]
  F --> X[simulate partial, duplicate,<br/>restart, reconcile]
```

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

> **Note** New words. **JSON** is a text format for structured data; the lab keeps each interface's specification in it. **CSV** is a text file with one record per line and fields separated by a character, here `;`. A **checksum** (here SHA-256) is a short fingerprint of a file's content: two files with the same content have the same checksum, whatever their names. **Exit code** is the number a program returns; `2` means at least one rule failed, which a pipeline can use to block a change.

> **Warning** The rule IDs `FB01` to `FB12`, the file layout, the interface details, users and values are course labels, not SAP formats. The rules follow the behavior SAP documents for its adapters and jobs, plus course choices marked in the table in Step 4.

The three interfaces come from Calder's register in the [integration platform topic](https://erpfde.com/topics/integration-platform-and-clean-core/): `I03` (open order items to the CRM by a nightly CSV from a custom report), `I08` (bank statements by SFTP, moving to SAP Multi-Bank Connectivity under ADR-001) and `I14` (test bench result files from the Rockford share, through the edge).

#### What you need

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

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

     ```bash
     mkdir -p unit26
     ```

#### Step 2: Create the script

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

```python
"""Review file interfaces, write their specifications, and see why the rules exist.

Course lab for Unit 26, "File and batch interfaces done properly".
Built-in modules only, no randomness, no network, no SAP system.

  python unit26/file_lab.py --init                 write the sample specs
  python unit26/file_lab.py review                 review unit26/files/specs_draft.json
  python unit26/file_lab.py review --file unit26/files/specs_reviewed.json
  python unit26/file_lab.py spec I03 --file unit26/files/specs_reviewed.json
  python unit26/file_lab.py simulate partial       a reader meets a file still being written
  python unit26/file_lab.py simulate duplicate     the same file sent again under a new name
  python unit26/file_lab.py simulate restart       a load stops halfway and runs again
  python unit26/file_lab.py simulate reconcile     source, file and target totals compared
  python unit26/file_lab.py --self-test            check the built-in samples

The file layout, rule IDs FB01 to FB12, names, users and values are course
labels for the fictional Calder Pumpworks. The stand-in writer, reader and
loader only imitate behavior described in the topic; they are not SAP
software.
"""

import argparse
import copy
import hashlib
import json
import sys
from datetime import date, timedelta
from pathlib import Path

FOLDER = Path("unit26/files")
AS_OF = "2026-11-30"
RUN_ID = "R20261130-0200"
FILE_NAME = f"CP10_I03_OPENITEMS_{RUN_ID}.csv"

# ---------------------------------------------------------------- the specs

DRAFT = [
    {"id": "I03", "name": "Open sales order items from CP10 to the CRM, nightly",
     "direction": "outbound", "sender": "S/4HANA S4P (custom report)", "receiver": "CRM",
     "transport": "ftp", "network": "internet", "auth": "password",
     "sensitive": False, "protection": "none", "format": "CSV, course layout H/D/T",
     "writer": "direct", "reader": "none", "naming": "fixed",
     "file_name": "OPENITEMS.CSV",
     "control": {"count": False, "hash_total": None},
     "duplicates": [], "load": "insert", "restart": "rerun_all",
     "schedule": {"kind": "batch", "at": "02:00", "after": None, "cutoff": None,
                  "late_alert": False},
     "post": "delete", "retention_days": 0,
     "expected_max_mb": 6, "reader_limit_mb": None,
     "reconciliation": None, "owner": "00100292", "error_contact": None, "plan": None},
    {"id": "I08", "name": "Bank statements from the bank to CP10",
     "direction": "inbound", "sender": "Calder's bank", "receiver": "S/4HANA S4P",
     "transport": "sftp", "network": "internet", "auth": "password",
     "sensitive": True, "protection": "none", "format": "camt.053 (ISO 20022)",
     "writer": "direct", "reader": "content_change", "naming": "timestamp",
     "file_name": "STMT_<yyyyMMddHHmm>.xml",
     "control": {"count": True, "hash_total": None},
     "duplicates": ["file_name"], "load": "insert", "restart": "rerun_all",
     "schedule": {"kind": "batch", "at": "06:30", "after": "bank delivery by 06:00",
                  "cutoff": "07:30", "late_alert": False},
     "post": "delete", "retention_days": 0,
     "expected_max_mb": 2, "reader_limit_mb": 40,
     "reconciliation": {"report": "closing balance per account vs bank", "owner": None},
     "owner": None, "error_contact": "Treasury", "plan": None},
    {"id": "I14", "name": "Test bench result files from the Rockford share",
     "direction": "inbound", "sender": "Test bench PC (TB-1)", "receiver": "S/4HANA S4P via the edge",
     "transport": "nfs", "network": "plant", "auth": "host",
     "sensitive": False, "protection": "none", "format": "CSV, one file per test",
     "writer": "direct", "reader": "none", "naming": "timestamp",
     "file_name": "TB1_<yyyyMMddHHmmss>.csv",
     "control": {"count": False, "hash_total": None},
     "duplicates": ["file_name"], "load": "upsert", "restart": "rerun_all",
     "schedule": {"kind": "poll", "every_min": 10, "late_alert": False},
     "post": "keep_process_again", "retention_days": 30,
     "expected_max_mb": 0.1, "reader_limit_mb": 40,
     "reconciliation": None, "owner": "00100314", "error_contact": None, "plan": None},
]


def reviewed_specs():
    specs = copy.deepcopy(DRAFT)
    by = {s["id"]: s for s in specs}
    by["I03"].update(
        transport="sftp", auth="public_key", writer="done_file", reader="done_file",
        naming="run_id", file_name="CP10_I03_OPENITEMS_<run ID>.csv (+ .done)",
        control={"count": True, "hash_total": "net value"},
        duplicates=["run_id", "business_key"], load="upsert", restart="upsert",
        schedule={"kind": "batch", "at": "02:00", "after": "night job BILL",
                  "cutoff": "05:00", "late_alert": True},
        post="archive", retention_days=30,
        reconciliation={"report": "items and net value: CP10 vs file vs CRM",
                        "owner": "00100296"},
        error_contact="Sales IT",
        plan={"action": "RETIRE", "by": "2027-03-31",
              "with": "sales order events and the released API (ADR-001)"})
    by["I08"].update(
        auth="public_key", protection="pgp", writer="temp_rename",
        naming="run_id", file_name="<bank message ID>_<statement number>.xml",
        control={"count": True, "hash_total": "entry amounts"},
        duplicates=["checksum", "business_key"], load="upsert", restart="upsert",
        schedule={"kind": "batch", "at": "06:30", "after": "bank delivery by 06:00",
                  "cutoff": "07:30", "late_alert": True},
        post="archive", retention_days=90,
        reconciliation={"report": "closing balance per account vs bank",
                        "owner": "00100280"},
        owner="00100280",
        plan={"action": "REPLACE", "by": "2027-03-31",
              "with": "SAP Multi-Bank Connectivity (ADR-001)"})
    by["I14"].update(
        writer="done_file", reader="done_file", naming="run_id",
        file_name="TB1_<serial>_<test number>.csv (+ .done)",
        control={"count": True, "hash_total": "flow readings"},
        duplicates=["checksum", "business_key"], restart="upsert",
        schedule={"kind": "poll", "every_min": 10, "late_alert": True},
        post="archive",
        reconciliation={"report": "serials tested on TB-1 vs results received",
                        "owner": "00100314"},
        error_contact="Production supervisors",
        plan={"action": "KEEP", "by": "2027-06-30", "with": "review with the edge runtime"})
    return {"company": "Calder Pumpworks (fictional)", "as_of": AS_OF, "interfaces": specs}


# ---------------------------------------------------------------- the rules

SECURE = {"sftp", "https", "mbc"}
SHARES = {"nfs", "smb"}
WRITER_SAFE = {"temp_rename", "done_file"}
MIN_RETENTION = 30  # course rule


def check(s):
    """Return (rule, level, text) tuples for one interface spec."""
    out = []

    def add(rule, level, text):
        out.append((rule, level, text))

    # FB01 owner and error contact
    if not s.get("owner"):
        add("FB01", "FAIL", "no owner")
    elif not s.get("error_contact"):
        add("FB01", "WARN", "owner named, but no error contact")
    else:
        add("FB01", "OK", f"owner {s['owner']}, errors to {s['error_contact']}")

    # FB02 transport and authentication
    t = s["transport"]
    if t in SECURE:
        if s["auth"] == "password":
            add("FB02", "WARN", f"{t} with a password; use a key or certificate")
        else:
            add("FB02", "OK", f"{t} with {s['auth']}")
    elif t in SHARES and s.get("network") == "plant":
        add("FB02", "OK", f"{t} share inside the plant network")
    else:
        add("FB02", "FAIL", f"{t} over {s.get('network')}: not encrypted")

    # FB03 content protection for sensitive data
    if s["sensitive"] and s["protection"] == "none":
        add("FB03", "FAIL", "sensitive content without signature or encryption")
    else:
        add("FB03", "OK", "protected" if s["sensitive"] else "not sensitive")

    # FB04 arrival signal: the reader must never take a half-written file
    if s["writer"] in WRITER_SAFE or s["reader"] == "done_file":
        add("FB04", "OK", f"writer {s['writer']}, reader {s['reader']}")
    elif s["reader"] in ("content_change", "rename"):
        add("FB04", "WARN", f"reader guesses with {s['reader']}; agree a done file or temp name")
    else:
        add("FB04", "FAIL", "writer writes in place and the reader reads at once")

    # FB05 unique name with a run ID
    if s["naming"] == "run_id":
        add("FB05", "OK", "name carries a run ID")
    elif s["naming"] == "timestamp":
        add("FB05", "WARN", "timestamp name: unique, but a resend gets a new one")
    else:
        add("FB05", "FAIL", f"fixed name {s['file_name']}: the next file overwrites it")

    # FB06 control record
    c = s["control"]
    if c["count"] and c["hash_total"]:
        add("FB06", "OK", f"count and hash total ({c['hash_total']})")
    elif c["count"]:
        add("FB06", "WARN", "record count only; add a hash total")
    else:
        add("FB06", "FAIL", "no control record: a short file looks complete")

    # FB07 duplicate checks
    d = set(s["duplicates"])
    if not d:
        add("FB07", "FAIL", "no duplicate check")
    elif d <= {"file_name"}:
        add("FB07", "WARN", "file name only: a renamed resend passes")
    elif "business_key" not in d and s["load"] != "upsert":
        add("FB07", "WARN", "file-level check only; records can still double")
    else:
        add("FB07", "OK", " + ".join(sorted(d)))

    # FB08 restart
    if s["restart"] == "rerun_all" and s["load"] == "insert":
        add("FB08", "FAIL", "rerun from the top inserts the first records again")
    elif s["restart"] in ("checkpoint", "upsert") or s["load"] == "upsert":
        add("FB08", "OK", f"restart by {s['restart'] if s['restart'] != 'rerun_all' else 'upsert'}")
    else:
        add("FB08", "WARN", f"restart '{s['restart']}' not proven")

    # FB09 schedule
    sc = s["schedule"]
    if sc["kind"] == "poll":
        if sc.get("late_alert"):
            add("FB09", "OK", f"polls every {sc['every_min']} min, alert when files stop")
        else:
            add("FB09", "FAIL", "polls, but nobody hears when files stop")
    else:
        missing = [w for w, k in (("a cut-off", "cutoff"), ("a late alert", "late_alert"))
                   if not sc.get(k)]
        if missing:
            add("FB09", "FAIL", f"runs at {sc['at']} without {' or '.join(missing)}")
        elif not sc.get("after"):
            add("FB09", "WARN", f"runs at {sc['at']} by clock, not after its predecessor")
        else:
            add("FB09", "OK", f"after {sc['after']}, cut-off {sc['cutoff']}, late alert")

    # FB10 post-processing and retention
    if s["post"] == "keep_process_again":
        add("FB10", "FAIL", "keep file and process again: every poll reads it again")
    elif s["post"] == "delete" or s["retention_days"] < MIN_RETENTION:
        add("FB10", "WARN", f"{s['post']}, kept {s['retention_days']} days: nothing to replay")
    else:
        add("FB10", "OK", f"{s['post']}, kept {s['retention_days']} days")

    # FB11 size within the reader's limit
    lim = s.get("reader_limit_mb")
    if lim is None:
        add("FB11", "OK", "no reader limit recorded")
    elif s["expected_max_mb"] > lim:
        add("FB11", "FAIL", f"up to {s['expected_max_mb']} MB, reader skips files above {lim} MB")
    else:
        add("FB11", "OK", f"up to {s['expected_max_mb']} MB, limit {lim} MB")

    # FB12 reconciliation
    r = s.get("reconciliation")
    if not r:
        add("FB12", "FAIL", "no reconciliation")
    elif not r.get("owner"):
        add("FB12", "FAIL", f"report '{r['report']}' has no owner")
    else:
        add("FB12", "OK", f"{r['report']} (owner {r['owner']})")
    return out


def verdict(results, spec):
    if any(level == "FAIL" for _, level, _ in results):
        return "FIX"
    plan = spec.get("plan")
    return plan["action"] if plan else "KEEP"


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


def review(path, quiet=False):
    data = load_specs(path)
    totals = {"OK": 0, "WARN": 0, "FAIL": 0}
    for s in data["interfaces"]:
        res = check(s)
        v = verdict(res, s)
        if not quiet:
            print(f"{s['id']}  {s['name']}")
            for rule, level, text in res:
                if level != "OK":
                    print(f"  {level:<4} {rule}  {text}")
            print(f"  verdict {v}")
        for _, level, _ in res:
            totals[level] += 1
    n = len(data["interfaces"])
    line = f"{totals['OK']} OK, {totals['WARN']} WARN, {totals['FAIL']} FAIL across {n} interfaces"
    if not quiet:
        print(line)
    return totals, line


# ---------------------------------------------------------------- the spec template

SECTIONS = [
    ("1. Purpose and owner", lambda s: [
        f"- Interface: {s['id']}, {s['name']}",
        f"- Owner: {s.get('owner') or 'TO DECIDE'}; error contact: {s.get('error_contact') or 'TO DECIDE'}",
        f"- Plan: {plan_text(s)}"]),
    ("2. Parties and transport", lambda s: [
        f"- Direction: {s['direction']}; sender: {s['sender']}; receiver: {s['receiver']}",
        f"- Transport: {s['transport']} over {s.get('network')}; authentication: {s['auth']}",
        f"- Content protection: {s['protection']} (sensitive: {'yes' if s['sensitive'] else 'no'})"]),
    ("3. Format and naming", lambda s: [
        f"- Format: {s['format']}",
        f"- File name: {s['file_name']} ({s['naming']})",
        f"- Expected size: up to {s['expected_max_mb']} MB; reader limit: {s.get('reader_limit_mb') or 'none recorded'}"]),
    ("4. Arrival and completeness", lambda s: [
        f"- Writer: {s['writer']}; reader: {s['reader']}",
        f"- Control record: count {'yes' if s['control']['count'] else 'no'}, "
        f"hash total {s['control']['hash_total'] or 'none'}"]),
    ("5. Duplicates and restart", lambda s: [
        f"- Duplicate checks: {', '.join(s['duplicates']) or 'none'}",
        f"- Load: {s['load']}; restart: {s['restart']}"]),
    ("6. Schedule and cut-off", lambda s: [schedule_text(s['schedule'])]),
    ("7. Archive and retention", lambda s: [
        f"- After processing: {s['post']}; kept {s['retention_days']} days"]),
    ("8. Reconciliation", lambda s: [
        f"- Report: {(s.get('reconciliation') or {}).get('report', 'TO DECIDE')}",
        f"- Owner of differences: {(s.get('reconciliation') or {}).get('owner') or 'TO DECIDE'}"]),
]


def plan_text(s):
    p = s.get("plan")
    return f"{p['action']} by {p['by']}: {p['with']}" if p else "TO DECIDE"


def schedule_text(sc):
    if sc["kind"] == "poll":
        return f"- Polls every {sc['every_min']} min; late alert: {'yes' if sc.get('late_alert') else 'no'}"
    return (f"- Runs at {sc['at']} after {sc.get('after') or 'nothing (clock only)'}; "
            f"cut-off {sc.get('cutoff') or 'none'}; late alert: {'yes' if sc.get('late_alert') else 'no'}")


def write_spec(path, iface_id):
    data = load_specs(path)
    spec = next((s for s in data["interfaces"] if s["id"] == iface_id), None)
    if spec is None:
        sys.exit(f"{iface_id} is not in {path}")
    res = check(spec)
    lines = [f"# File interface specification: {spec['id']}", "",
             f"Company: {data['company']} · as of {data['as_of']} · verdict {verdict(res, spec)}", ""]
    for title, body in SECTIONS:
        lines += [f"## {title}", ""] + body(spec) + [""]
    lines += ["## 9. Review result", ""]
    lines += [f"- {level} {rule}: {text}" for rule, level, text in res]
    lines += ["", "## 10. Test cases", "",
              "- File arrives while still being written",
              "- Same file sent again under a new name",
              "- Load stops halfway and is started again",
              "- One record rejected: does the reconciliation show it?",
              "- No file by the cut-off: who is alerted?", ""]
    out = FOLDER / f"spec_{iface_id}.md"
    out.write_text("\n".join(lines), encoding="utf-8")
    todo = sum(1 for l in lines if "TO DECIDE" in l)
    print(f"Wrote {out.as_posix()} ({len(lines)} lines, {todo} still TO DECIDE)")


# ---------------------------------------------------------------- the sample file

CUSTOMERS = ["10000001", "10000002", "10000021", "10000031", "10000022", "10000023"]
MATERIALS = [("CP-ES200", 395000), ("CP-ES300", 640000), ("CP-SK200", 9500), ("CP-BRG6310", 12400)]


def source_items():
    """CP10's open order items as the stand-in source system holds them (cents)."""
    items = []
    for i in range(120):
        mat, price = MATERIALS[i % 4]
        qty = i % 5 + 1
        items.append({
            "order": str(1003001 + i // 2), "item": str(10 * (i % 2 + 1)),
            "customer": CUSTOMERS[(i // 2) % 6], "material": mat, "qty": qty,
            "net": qty * price,
            "requested": (date(2026, 12, 1) + timedelta(days=i % 20)).isoformat()})
    return items


def money(cents, sep=","):
    return f"{cents // 100:{sep}}.{cents % 100:02d}" if sep else f"{cents // 100}.{cents % 100:02d}"


def file_lines(items, bad_date_at=None):
    lines = [f"H;I03;{RUN_ID};2026-11-30T02:04:00"]
    for n, it in enumerate(items):
        req = "2026-11-31" if n == bad_date_at else it["requested"]
        lines.append(";".join(["D", it["order"], it["item"], it["customer"], it["material"],
                               str(it["qty"]), money(it["net"], ""), "USD", req]))
    total = sum(it["net"] for it in items)
    lines.append(f"T;{len(items)};{money(total, '')}")
    return lines


def parse(text):
    """Read a file: header, detail rows and trailer (None if missing)."""
    rows, header, trailer = [], None, None
    for line in text.splitlines():
        parts = line.split(";")
        if parts[0] == "H":
            header = parts
        elif parts[0] == "D" and len(parts) == 9:
            rows.append(parts)
        elif parts[0] == "T":
            trailer = parts
    return header, rows, trailer


def cents(text):
    whole, frac = text.split(".")
    return int(whole) * 100 + int(frac)


def control_ok(rows, trailer):
    if trailer is None:
        return False, "no trailer: file incomplete"
    count, total = int(trailer[1]), cents(trailer[2])
    got_total = sum(cents(r[6]) for r in rows)
    if count != len(rows) or total != got_total:
        return False, f"trailer says {count} rows / {money(total)}, file has {len(rows)} / {money(got_total)}"
    return True, f"{count} rows, {money(total)} USD"


# ---------------------------------------------------------------- simulations

def sim_partial():
    lines = file_lines(source_items())
    full = "\n".join(lines) + "\n"
    half = "\n".join(lines[:48]) + "\n"  # the writer has written 47 items so far
    print("The writer has written 47 of 120 items when the reader polls.")
    _, rows, _ = parse(half)
    print(f"  reader 'none', no control check     loads {len(rows)} rows, reports success")
    _, rows, trailer = parse(half)
    ok, why = control_ok(rows, trailer)
    print(f"  reader 'none', control check        rejects the file: {why}")
    print("  reader waits for the done file      skips this poll; no .done yet")
    _, rows, trailer = parse(full)
    ok, why = control_ok(rows, trailer)
    print(f"  next poll, .done present            loads {len(rows)} rows, control {'OK' if ok else 'FAIL'}: {why}")
    return len(rows)


def sim_duplicate():
    text = "\n".join(file_lines(source_items())) + "\n"
    first, resend = FILE_NAME, FILE_NAME.replace(".csv", "_RESEND.csv")
    digest = hashlib.sha256(text.encode()).hexdigest()
    print(f"{first} loaded at 02:05. At 07:40 operations send it again as {resend}.")
    results = {}
    for check_by in ("file_name", "checksum", "run_id"):
        seen, loaded = set(), 0
        for name in (first, resend):
            key = {"file_name": name, "checksum": digest, "run_id": RUN_ID}[check_by]
            if key in seen:
                continue
            seen.add(key)
            loaded += len(parse(text)[1])
        results[check_by] = loaded
        verdict_ = "second file skipped" if loaded == 120 else "second file loaded too"
        print(f"  duplicate check by {check_by:<10} {loaded:>3} rows in the CRM ({verdict_})")
    print(f"  SHA-256 of both files: {digest[:16]}...")
    return results


def sim_restart():
    rows = parse("\n".join(file_lines(source_items())))[1]
    print("The load commits every 10 rows and stops after row 70 (the CRM restarted).")
    out = {}
    # rerun from the top with insert
    table = rows[:70] + rows
    keys = {(r[1], r[2]) for r in table}
    out["rerun_insert"] = len(table)
    print(f"  rerun from the top, insert          {len(table)} rows, {len(table) - len(keys)} duplicates")
    # checkpoint
    checkpoint = 70
    table = rows[:70] + rows[checkpoint:]
    out["checkpoint"] = len(table)
    print(f"  resume after checkpoint 70          {len(table)} rows, 0 duplicates")
    # upsert by business key
    table = {}
    for r in rows[:70] + rows:
        table[(r[1], r[2])] = r
    out["upsert"] = len(table)
    print(f"  rerun from the top, upsert by key   {len(table)} rows, 0 duplicates")
    return out


def sim_reconcile():
    items = source_items()
    lines = file_lines(items, bad_date_at=56)
    header, rows, trailer = parse("\n".join(lines))
    loaded, rejected = [], []
    for r in rows:
        try:
            date.fromisoformat(r[8])
            loaded.append(r)
        except ValueError:
            rejected.append(r)
    src_n, src_v = len(items), sum(it["net"] for it in items)
    file_n, file_v = int(trailer[1]), cents(trailer[2])
    tgt_n, tgt_v = len(loaded), sum(cents(r[6]) for r in loaded)
    print(f"Reconciliation for run {RUN_ID}")
    print(f"  {'':<10}{'items':>6}{'net value USD':>16}")
    for name, n, v in (("CP10", src_n, src_v), ("file", file_n, file_v), ("CRM", tgt_n, tgt_v)):
        print(f"  {name:<10}{n:>6}{money(v):>16}")
    for r in rejected:
        print(f"  DIFF  order {r[1]} item {r[2]}: {money(cents(r[6]))} USD rejected (requested date {r[8]})")
    status = "BALANCED" if (src_n, src_v) == (tgt_n, tgt_v) else "OPEN DIFFERENCE"
    print(f"  {status}: to 00100296 (sales operations) by 08:00")
    return src_n - tgt_n, src_v - tgt_v


# ---------------------------------------------------------------- init and self-test

def init():
    FOLDER.mkdir(parents=True, exist_ok=True)
    targets = {"specs_draft.json": {"company": "Calder Pumpworks (fictional)",
                                    "as_of": AS_OF, "interfaces": DRAFT},
               "specs_reviewed.json": reviewed_specs()}
    for name, content in targets.items():
        p = FOLDER / name
        if p.exists():
            print(f"{p.as_posix()} already exists; delete it first to get the sample back")
            continue
        p.write_text(json.dumps(content, indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {p.as_posix()}")
    sample = FOLDER / FILE_NAME
    if not sample.exists():
        sample.write_text("\n".join(file_lines(source_items())) + "\n", encoding="utf-8")
        (FOLDER / (FILE_NAME + ".done")).write_text("", encoding="utf-8")
        print(f"Wrote {sample.as_posix()} and its .done file")


def self_test():
    import io
    import contextlib
    import tempfile
    checks = []
    with contextlib.redirect_stdout(io.StringIO()):
        with tempfile.TemporaryDirectory() as tmp:
            d = Path(tmp) / "d.json"
            r = Path(tmp) / "r.json"
            d.write_text(json.dumps({"company": "x", "as_of": AS_OF, "interfaces": DRAFT}))
            r.write_text(json.dumps(reviewed_specs()))
            td, _ = review(d, quiet=True)
            tr, _ = review(r, quiet=True)
        part = sim_partial()
        dup = sim_duplicate()
        rst = sim_restart()
        rec = sim_reconcile()
    items = source_items()
    checks += [
        ("120 source items", len(items) == 120),
        ("source net value 951,210.00", sum(i["net"] for i in items) == 95121000),
        ("draft: 7 OK", td["OK"] == 7),
        ("draft: 11 WARN", td["WARN"] == 11),
        ("draft: 18 FAIL", td["FAIL"] == 18),
        ("reviewed: 36 OK, 0 WARN, 0 FAIL", tr == {"OK": 36, "WARN": 0, "FAIL": 0}),
        ("draft verdicts all FIX", all(verdict(check(s), s) == "FIX" for s in DRAFT)),
        ("partial: full file 120 rows", part == 120),
        ("duplicate: file name lets it through", dup["file_name"] == 240),
        ("duplicate: checksum and run ID catch it", dup["checksum"] == dup["run_id"] == 120),
        ("restart: rerun insert gives 190", rst["rerun_insert"] == 190),
        ("restart: checkpoint and upsert give 120", rst["checkpoint"] == rst["upsert"] == 120),
        ("reconcile: one item missing", rec[0] == 1),
        ("reconcile: 7,900.00 missing", rec[1] == 790000),
    ]
    passed = sum(1 for _, ok in checks if ok)
    for name, ok in checks:
        if not ok:
            print(f"  FAILED: {name}")
    print(f"{passed} of {len(checks)} self-test checks passed")
    return passed == len(checks)


def main():
    ap = argparse.ArgumentParser(description="File and batch interface lab (Unit 26)")
    ap.add_argument("command", nargs="?", choices=["review", "spec", "simulate"])
    ap.add_argument("arg", nargs="?", help="interface ID for spec, case for simulate")
    ap.add_argument("--file", default=str(FOLDER / "specs_draft.json"))
    ap.add_argument("--init", action="store_true", help="write the sample specs and file")
    ap.add_argument("--self-test", action="store_true", help="check the built-in samples")
    a = ap.parse_args()
    if a.init:
        init()
    elif a.self_test:
        sys.exit(0 if self_test() else 1)
    elif a.command == "review":
        totals, _ = review(a.file)
        sys.exit(2 if totals["FAIL"] else 0)
    elif a.command == "spec":
        if not a.arg:
            sys.exit("Name an interface, for example: spec I03")
        FOLDER.mkdir(parents=True, exist_ok=True)
        write_spec(a.file, a.arg)
    elif a.command == "simulate":
        cases = {"partial": sim_partial, "duplicate": sim_duplicate,
                 "restart": sim_restart, "reconcile": sim_reconcile}
        if a.arg not in cases:
            sys.exit(f"Choose one of: {', '.join(cases)}")
        cases[a.arg]()
    else:
        ap.print_help()


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

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

1. Write the specifications and the sample file:

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

   ```text
   Wrote unit26/files/specs_draft.json
   Wrote unit26/files/specs_reviewed.json
   Wrote unit26/files/CP10_I03_OPENITEMS_R20261130-0200.csv and its .done file
   ```

2. Run the self-test:

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

   ```text
   14 of 14 self-test checks passed
   ```

3. Open `unit26/files/CP10_I03_OPENITEMS_R20261130-0200.csv` in VS Code. The first line is the header with the run ID, the last is the trailer: `T;120;951210.00`. The empty `.done` file next to it is the writer's signal that the data file is complete.

> **Note** The 120 order items are generated by a fixed rule in `source_items()` (orders from `1003001`, Calder's customers and four products at course prices). They are synthetic data and show the method, not figures from a real SAP system.

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

1. Run the review on the draft:

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

   The output starts like this:

   ```text
   I03  Open sales order items from CP10 to the CRM, nightly
     WARN FB01  owner named, but no error contact
     FAIL FB02  ftp over internet: not encrypted
     FAIL FB04  writer writes in place and the reader reads at once
     FAIL FB05  fixed name OPENITEMS.CSV: the next file overwrites it
     FAIL FB06  no control record: a short file looks complete
     FAIL FB07  no duplicate check
     FAIL FB08  rerun from the top inserts the first records again
     FAIL FB09  runs at 02:00 without a cut-off or a late alert
     WARN FB10  delete, kept 0 days: nothing to replay
     FAIL FB12  no reconciliation
     verdict FIX
   I08  Bank statements from the bank to CP10
     FAIL FB01  no owner
     WARN FB02  sftp with a password; use a key or certificate
     FAIL FB03  sensitive content without signature or encryption
     WARN FB04  reader guesses with content_change; agree a done file or temp name
     WARN FB05  timestamp name: unique, but a resend gets a new one
     WARN FB06  record count only; add a hash total
     WARN FB07  file name only: a renamed resend passes
     FAIL FB08  rerun from the top inserts the first records again
     FAIL FB09  runs at 06:30 without a late alert
     WARN FB10  delete, kept 0 days: nothing to replay
     FAIL FB12  report 'closing balance per account vs bank' has no owner
     verdict FIX
   ```

   and ends with:

   ```text
   7 OK, 11 WARN, 18 FAIL across 3 interfaces
   ```

2. Read the rules behind the findings:

| Rule | Checks | Based on |
| --- | --- | --- |
| FB01 | An owner (FAIL if missing) and an error contact (WARN) | Course rule |
| FB02 | SFTP, HTTPS or Multi-Bank Connectivity; a plant share only inside the plant network; a password only as WARN | SFTP adapter authentication options; course rule |
| FB03 | Sensitive content is signed or encrypted | Multi-Bank Connectivity's message-level security; course rule |
| FB04 | The writer uses a temporary name or a done file, or the reader waits for a done file; *Content Change* alone is WARN | SFTP sender *Read Lock Strategy*; PI temporary file |
| FB05 | The name carries a run ID; a timestamp is WARN, a fixed name FAIL | PI file construction modes; course rule |
| FB06 | A trailer with a count and a hash total | Course rule |
| FB07 | Duplicates caught by run ID or checksum, and records by business key; file name only is WARN | SFTP idempotent repository identifies files by name; SAP's exactly-once guidance |
| FB08 | A rerun doesn't insert twice: upsert or checkpoint | Course rule |
| FB09 | Batch jobs have a cut-off and a late alert (FAIL), and run after a predecessor (WARN); polls have a late alert | Application job statuses; course rule |
| FB10 | No *Keep File and Process Again* in production; files kept at least 30 days | SFTP post-processing options; 30 days is a course rule |
| FB11 | Expected size within the reader's recorded limit | SFTP sender maximum file size |
| FB12 | A reconciliation report with an owner | Course rule |

#### Step 5: See why FB04 and FB06 exist

1. Run:

   ```bash
   python unit26/file_lab.py simulate partial
   ```

   ```text
   The writer has written 47 of 120 items when the reader polls.
     reader 'none', no control check     loads 47 rows, reports success
     reader 'none', control check        rejects the file: no trailer: file incomplete
     reader waits for the done file      skips this poll; no .done yet
     next poll, .done present            loads 120 rows, control OK: 120 rows, 951,210.00 USD
   ```

2. Read the four lines. Without either control, the CRM loads 47 items and calls it a success. The trailer turns that into a rejected file. The done file stops the reader from looking at all until the writer has finished. Use both: the done file prevents the problem, the trailer detects the cases it misses.

#### Step 6: See why FB05 and FB07 exist

1. Run:

   ```bash
   python unit26/file_lab.py simulate duplicate
   ```

   ```text
   CP10_I03_OPENITEMS_R20261130-0200.csv loaded at 02:05. At 07:40 operations send it again as CP10_I03_OPENITEMS_R20261130-0200_RESEND.csv.
     duplicate check by file_name  240 rows in the CRM (second file loaded too)
     duplicate check by checksum   120 rows in the CRM (second file skipped)
     duplicate check by run_id     120 rows in the CRM (second file skipped)
     SHA-256 of both files: 5b376466d55b994c...
   ```

2. The name changed, so a check on the name lets the resend through. The run ID in the header and the content checksum are the same in both files, so either check skips it. This is why the SFTP sender's idempotent repository, which identifies files by name, is a first line and not the only one.

#### Step 7: See why FB08 exists

1. Run:

   ```bash
   python unit26/file_lab.py simulate restart
   ```

   ```text
   The load commits every 10 rows and stops after row 70 (the CRM restarted).
     rerun from the top, insert          190 rows, 70 duplicates
     resume after checkpoint 70          120 rows, 0 duplicates
     rerun from the top, upsert by key   120 rows, 0 duplicates
   ```

2. Only the first option is wrong, and it is the one people reach for at 03:00. The specification must say which of the other two the load uses.

#### Step 8: See why FB12 exists

1. Run:

   ```bash
   python unit26/file_lab.py simulate reconcile
   ```

   ```text
   Reconciliation for run R20261130-0200
                items   net value USD
     CP10         120      951,210.00
     file         120      951,210.00
     CRM          119      943,310.00
     DIFF  order 1003029 item 10: 7,900.00 USD rejected (requested date 2026-11-31)
     OPEN DIFFERENCE: to 00100296 (sales operations) by 08:00
   ```

2. Source and file agree, so the export worked. The CRM rejected one item with an impossible date. Without the report, nobody would know; with it, the sales operations manager has a named row and a deadline.

> **Note** These counts and amounts come from synthetic data and course rules. They show the method, not results from a real SAP system.

#### Step 9: Review the corrected design and write a specification

1. Review the corrected specifications:

   ```bash
   python unit26/file_lab.py review --file unit26/files/specs_reviewed.json
   ```

   ```text
   I03  Open sales order items from CP10 to the CRM, nightly
     verdict RETIRE
   I08  Bank statements from the bank to CP10
     verdict REPLACE
   I14  Test bench result files from the Rockford share
     verdict KEEP
   36 OK, 0 WARN, 0 FAIL across 3 interfaces
   ```

   Every rule passes, and each interface now has a plan: `I03` retires when the CRM moves to sales order events under ADR-001, `I08` moves to SAP Multi-Bank Connectivity, `I14` stays.

2. Write the specification for `I03`:

   ```bash
   python unit26/file_lab.py spec I03 --file unit26/files/specs_reviewed.json
   ```

   ```text
   Wrote unit26/files/spec_I03.md (68 lines, 0 still TO DECIDE)
   ```

3. Open `unit26/files/spec_I03.md`. It has ten sections: purpose and owner, parties and transport, format and naming, arrival and completeness, duplicates and restart, schedule and cut-off, archive and retention, reconciliation, the review result, and the test cases. This is the template the brief asked for; an owner can read and sign it.

4. Try the same on the draft: `python unit26/file_lab.py spec I08` writes a specification with `3 still TO DECIDE`, one for each gap a reviewer must close.

#### Step 10 (sketch): Apply it to a real landscape

> **Note** This step is a **sketch**. It needs access to an SAP Integration Suite tenant and an SAP system, which Units 21 and 26's setup topics describe.

1. In Cloud Integration, open each SFTP sender channel and record its *Read Lock Strategy*, *Post-Processing*, *Max. Messages per Poll* and *Poll on One Worker Only* in the specification.
2. In the S/4HANA system, list the application jobs that write or read files, with their predecessor and the job user.
3. In ECC or on-premise systems, list the logical file names in transaction `FILE` and the roles with `S_DATASET`.
4. Fill one JSON entry per interface and run the review.

#### Step 11: Save your work

```bash
git add unit26/file_lab.py unit26/files
git commit -m "Unit 26: file interface review and specifications for Calder"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `DRAFT`, `reviewed_specs()` | The partner's three specifications and the corrected ones, written to JSON by `--init` |
| `check()` | Applies `FB01` to `FB12` to one specification and returns OK, WARN or FAIL lines |
| `verdict()` | `FIX` if anything fails, otherwise the plan's action (`KEEP`, `REPLACE`, `RETIRE`) |
| `SECTIONS`, `write_spec()` | The specification template: ten sections filled from the JSON, with `TO DECIDE` where a value is missing |
| `source_items()`, `file_lines()` | The 120 synthetic order items and the file with header, details and trailer, amounts in cents |
| `parse()`, `control_ok()` | Read a file and check its trailer against the rows |
| `sim_partial()` to `sim_reconcile()` | The four simulations from Steps 5 to 8 |
| `self_test()` | Fourteen checks on the built-in samples, so you can tell a broken copy from an edited file |

#### If something goes wrong

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

### The SAP way

What SAP provides, as of 30 November 2026:

- **Cloud Integration file adapters.** SFTP and FTP sender and receiver adapters, with read lock strategies, an idempotent repository, post-processing and archive options, ordering controls, and on-premise access through the Cloud Connector ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). Advanced file selection uses *Poll Enrich* and splitters ([SAP Developers](https://developers.sap.com/tutorials/ci-sftp-file-polling.html)). The [Cloud Integration flows topic](https://erpfde.com/topics/cloud-integration-flows-in-depth/) covers flow design, JMS retries and the *Idempotent Process Call*.
- **Edge Integration Cell** for files on plant shares that need adapters only the edge offers; see the [edge topic](https://erpfde.com/topics/edge-integration-cell/).
- **SAP Process Orchestration** file adapters with quality of service *Exactly Once* and *Exactly Once In Order*, temporary file writing and archive processing ([SAP Learning](https://learning.sap.com/courses/sap-java-process-integration/configuring-a-sender-file-adapter_f8626d18-4742-432b-8266-8c12b4b281be), [SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/44/69d7cfa4b633eae10000000a1553f6/content.htm)), until you migrate.
- **ABAP file handling**: logical file names in transaction `FILE`, `FILE_VALIDATE_NAME`, `S_DATASET` and `S_PATH` ([SAP Help Portal](https://help.sap.com/saphelp_em92/helpdata/en/38/bffdace37d4429998beb1e4acb11b7/content.htm), [SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/a8/d3c2aa14b04bf8bb2718aefeb478f5/content.htm)).
- **Application jobs** in SAP S/4HANA for scheduling, with job templates, job users and job logs ([SAP Learning](https://learning.sap.com/courses/administrating-sap-s-4hana-cloud-public-edition/introducing-application-jobs_cf77594e-9dd1-454b-b8d1-05079dfee508)).
- **SAP Multi-Bank Connectivity** for bank files: payments (`pain.001`) with status messages (`pain.002`), statements (`camt.053`, `MT940`, `BAI2` and others), through a connector in S/4HANA, monitored in the *Manage Bank Messages* app ([SAP Community](https://community.sap.com/t5/financial-management-blog-posts-by-sap/sap-multi-bank-connectivity-mbc-all-you-need-to-know/ba-p/13619921)).
- **Licensing note.** Integration Suite and Multi-Bank Connectivity are separately licensed cloud services; check your contract for which capabilities and message volumes it covers. Logical file names, application jobs and ABAP file handling come with the system.

### Build vs. SAP

| Need | SAP | Your own | Use which |
| --- | --- | --- | --- |
| Transfer to and from SFTP servers | Cloud Integration SFTP adapters | Scripts with an SFTP client on a server | SAP's: monitored, with keys held in the tenant |
| Waiting for complete files | *Done File Expected*, temporary file names | A sleep before reading | SAP's settings, agreed with the writer |
| Duplicate files | Idempotent repository (by file name) | Run ID and checksum checks in the flow | Both: SAP's as a first line, yours for resends |
| Duplicate records | *Idempotent Process Call*, receiver keys | Upsert by business key in the target | Your design; SAP's step where the target can't upsert |
| Completeness | Standard formats' own counts (ISO 20022) | Header and trailer in your layout | The format's checks if it has them, else your trailer |
| Bank connectivity | SAP Multi-Bank Connectivity | Host-to-host SFTP per bank | SAP's where your banks are reachable through it |
| Reconciliation | Monitors show messages, not business totals | A report per interface with an owner | Yours; no tool knows your totals |

### Architecture view

**Where it sits.** Calder's three file interfaces cross three boundaries: the internet to the bank, BTP to the CRM's server, and the plant network to the edge.

```mermaid
flowchart LR
  S4P[S/4HANA S4P<br/>CP10, RISE] -- I03 job after BILL --> CI[Cloud Integration<br/>calder-int-prod]
  CI -- SFTP, key --> CRM[CRM SFTP folder]
  BANK[Bank] -- I08 SFTP today --> CI
  BANK -. I08 target .-> MBC[Multi-Bank Connectivity] -.-> S4P
  TB[Test bench TB-1] -- I14 file + .done --> NFS[Rockford share]
  NFS --> EIC[Edge Integration Cell<br/>eic-rockford-prod] --> S4P
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Completeness | No partial file ever loaded; trailer checked every run | Half the data reaches users as if it were all |
| Duplicates | Zero double-loaded records | Inflated cash, orders or stock |
| Timeliness | File processed by the cut-off; alert within minutes of it | Morning work starts on yesterday's data |
| Restart | Any rerun gives the same result | Operators fear reruns and fix data by hand |
| Size | Largest expected file under the reader's limit, with headroom | The reader skips the file and nobody notices |
| Security | Encrypted transport, key authentication, content signed or encrypted where sensitive | Credentials or bank data exposed |
| Retention | Files kept long enough to replay (Calder: 30 days, 90 for bank files) | No way to recover after an outage |

**Integration and identity.** Cloud Integration authenticates to SFTP servers with keys held in the tenant; on-premise servers are reached through the Cloud Connector's location ID. Jobs in S/4HANA run under a job user, which is the identity every record they write carries; keep it a named technical user with narrow authorizations, never a person's account. The [non-functional design topic](https://erpfde.com/topics/non-functional-design-for-sap/) sizes Calder's night jobs, including the order in which they run.

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

- **Context.** `I03` sends open order items from a custom report to the CRM every night. It falls short on 10 of the 12 course rules today (8 FAIL, 2 WARN). ADR-001 replaces it with sales order events and the released API, but not before spring 2027.
- **Options.** A: leave it until it retires. B: fix it now to the full standard: SFTP with a key, done file, trailer, run ID, upsert, cut-off, reconciliation. C: bring the event-based replacement forward.
- **Decision.** B, limited to configuration and the report's output format: the gaps cause silent data loss today, the fixes are days of work, and C needs the CRM team's capacity that is committed elsewhere.
- **Consequences.** The report writes a trailer and a done file; the CRM load changes to upsert by order and item. Sales operations reads the reconciliation each morning until `I03` retires on 2027-03-31.

**What a design review will ask.**

1. How does the reader know each file is complete, and what does it do with one that isn't?
2. What happens when the same file arrives twice under a different name?
3. If the load stops halfway, what does a rerun do?
4. What is the cut-off, who is alerted, and who owns reconciliation differences?
5. Which files carry sensitive data, and how is the content protected?

### Production concerns

- **Security and authorizations.** One SFTP user per partner and folder, key authentication, keys rotated on a calendar. In ABAP, logical file names with validation and narrow `S_DATASET`. Content signatures for anything that moves money.
- **Evaluation.** Each interface has the five test cases the specification lists: partial file, resend, stopped load, one bad record, no file by the cut-off. Run them before go-live and after every change to either side.
- **Cost.** Controls cost little at design time. The expensive part is retrofitting a control line or an upsert into a partner's system; negotiate it when the interface is new.
- **Operations.** Monitors in Cloud Integration show messages, not business totals; the reconciliation report is what operations reads. Archive files for replay. The [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/) builds the run book.
- **Clean core.** A custom report writing a file is custom code reading SAP data; plan its replacement by released APIs or events, as ADR-001 does for `I03`. The [API policy page](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) covers what bulk extraction SAP endorses.

### Where AI fits

AI changes little in how files move, and a few things around them, as of November 2026:

- **Reading partners' file layouts.** A model can draft a mapping or a specification from a sample file and a partner's description. Treat it as a draft: the control totals and the review decide. [Calling AI from SAP Integration Suite](https://erpfde.com/topics/ai-in-sap-integration-suite/) covers putting an AI step inside a flow, with the checks it needs.
- **Explaining reconciliation differences.** An agent can read the reconciliation report and the rejected rows, and draft the note to the owner. It shouldn't correct data in the target; a person does.
- **Batch jobs that call models.** A nightly job that sends records to a model is a batch interface with the same five questions; the [batch topic](https://erpfde.com/topics/batch-and-observability-in-the-generative-ai-hub/) covers SAP's batch option for that.
- **Agents as consumers of extracts.** An agent fed by a file inherits its gaps. Give it the reconciliation status too, so it knows when yesterday's data is incomplete.

### Pitfalls

- **Reading on sight.** *Read Lock Strategy* *None* with a writer that writes in place loads half files.
- **Trusting the name.** A file-name check misses resends under a new name.
- **Insert-only loads.** The first rerun after a failure doubles everything before the failure point.
- **Clock-based schedules.** A job at 02:00 that should run after billing will miss the night billing is late.
- **"Keep File and Process Again" left on.** Fine in a test; in production every poll reads the same file again.
- **Splitting before checking.** Once a file is split into records, its trailer is gone. Check first.
- **Deleting on success.** Nothing to replay after an outage or a wrong load.
- **Monitors instead of reconciliation.** A green message monitor says the file moved, not that every record arrived.

### Exercise

Ridgeline Bearing Supply (`20000003`) offers to send Calder a monthly price list as a CSV file over SFTP, to update purchasing info records in `CP10`. Add it as `I16` and fix it before anyone builds it.

1. Open `unit26/files/specs_reviewed.json` and add this entry at the end of the `interfaces` list (put a comma after the closing brace of `I14`):

   ```json
   {"id": "I16", "name": "Ridgeline's monthly price list for CP10", "direction": "inbound",
    "sender": "Ridgeline Bearing Supply (20000003)", "receiver": "S/4HANA S4P (info records)",
    "transport": "sftp", "network": "internet", "auth": "public_key", "sensitive": false,
    "protection": "none", "format": "CSV, Ridgeline's layout", "writer": "direct",
    "reader": "none", "naming": "fixed", "file_name": "PRICES.CSV",
    "control": {"count": true, "hash_total": null}, "duplicates": ["file_name"],
    "load": "upsert", "restart": "upsert",
    "schedule": {"kind": "batch", "at": "03:00", "after": null,
                 "cutoff": "first working day 12:00", "late_alert": true},
    "post": "archive", "retention_days": 90, "expected_max_mb": 48, "reader_limit_mb": 40,
    "reconciliation": null, "owner": "00100211", "error_contact": "Purchasing", "plan": null}
   ```

2. Run `python unit26/file_lab.py review --file unit26/files/specs_reviewed.json`. `I16` shows `FAIL` on `FB04`, `FB05`, `FB11` and `FB12` and `WARN` on `FB06`, `FB07` and `FB09`, and the last line reads `41 OK, 3 WARN, 4 FAIL across 4 interfaces`.
3. Fix `I16`:
   - `"writer": "done_file"` (Ridgeline writes a done file after the data file)
   - `"naming": "run_id"` and `"file_name": "RBS_PRICES_<yyyyMM>.csv (+ .done)"`
   - `"control": {"count": true, "hash_total": "prices"}`
   - `"duplicates": ["checksum", "business_key"]`
   - in `schedule`, `"after": "Ridgeline's upload on the last working day"`
   - `"expected_max_mb": 2` (Ridgeline sends only Calder's items, not its whole catalogue)
   - `"reconciliation": {"report": "items in file vs info records updated", "owner": "00100211"}`
   - `"plan": {"action": "KEEP", "by": "2027-06-30", "with": "review after the CP20 rollout"}`
4. Run the review again. `I16` reads `verdict KEEP` and the last line reads `48 OK, 0 WARN, 0 FAIL across 4 interfaces`.
5. Write its specification: `python unit26/file_lab.py spec I16 --file unit26/files/specs_reviewed.json`, which reports `0 still TO DECIDE`. Add one test case of your own to section 10 of `spec_I16.md`: what happens when a price in the file is 20% above the current info record?

**Done when:** the review prints `48 OK, 0 WARN, 0 FAIL across 4 interfaces` and `spec_I16.md` has your extra test case. The specifications feed the [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/).

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

### Going further

For readers who want the reasoning behind the controls and SAP's own reference material.

- **At least once plus idempotent equals exactly once.** No transport can promise exactly-once delivery on its own across a failure; the sender must resend when unsure, and the receiver must recognize what it already has. SAP's design guidelines for Cloud Integration put it in the same two parts, with a JMS queue to retry when the sender can't ([SAP blog](https://blogs.sap.com/2021/12/06/integration-flow-design-guidelines-for-exactly-once-scenarios/)). Files are the oldest case of the same rule.
- **Ordering versus throughput.** SAP's SFTP sender page explains that each runtime node polls independently and that strict order needs one worker and one message per poll ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md)). Design file names so that only files that truly depend on each other need ordering, and let everything else run in parallel.
- **Corrections.** A partner sometimes sends a corrected file for the same run. Decide in the specification whether a second file with the same run ID replaces the first (and how the target undoes the first load) or is rejected. A checksum then tells a resend from a correction.
- **Path traversal in ABAP.** SAP's secure programming guide explains how unrestricted file names reach any file the application server can open, and how logical file names with validation close it ([SAP Help Portal](https://help.sap.com/saphelp_nw73/helpdata/en/a8/d3c2aa14b04bf8bb2718aefeb478f5/content.htm)).

### Check yourself

1. The SFTP sender's Read Lock Strategy is None and the writer writes in place. What happens?
   - A. The adapter waits a second after the last change before reading
   - B. The reader can pick up a file the writer hasn't finished
   - C. The adapter renames the file before reading, so it is safe
   - D. The file is skipped until a done file appears next to it

   Answer: B. SAP's page says None, the default, reads the file as soon as it is seen. Only a writer that uses a temporary name and renames makes that safe; otherwise use Done File Expected.

2. Why isn't the SFTP sender's idempotent repository enough on its own to stop duplicates?
   - A. It keeps entries only while the integration flow is deployed
   - B. It compares file sizes, so two equal files look the same
   - C. It identifies files by name, so a renamed resend passes
   - D. It works only when Max. Messages per Poll is set to 1

   Answer: C. SAP's documentation says the database repository identifies a file by user, host and file name, not size or timestamp. The lab shows the renamed resend loading 240 rows; a run ID or checksum catches it.

3. A load stopped after 70 of 120 records. Which design lets an operator rerun it from the top safely?
   - A. Upsert by the business key, such as order and item
   - B. Insert all records again, then delete the extra rows
   - C. Rename the file so the reader treats it as a new one
   - D. Lower the commit interval from 10 rows to 1 row

   Answer: A. An upsert by key gives 120 records however many times it runs. Inserting from the top gives 190, and renaming only makes the reader load it again.

4. Bank statements must be processed in the order the bank sends them. What do you set on the SFTP sender?
   - A. Post-Processing to Keep File and Process Again
   - B. Read Lock Strategy to Rename, with an archive directory
   - C. Max. Messages per Poll to 500, so all arrive together
   - D. Poll on One Worker Only, sorting by name, one message per poll

   Answer: D. SAP's page says order-sensitive processing needs one worker, with sorting, and that strict order needs one message per poll. Otherwise a failed file can be retried later and out of order.

5. Source and file both show 120 items, the CRM shows 119. What does that tell you?
   - A. The export report missed an item in its selection
   - B. The CRM rejected or lost one record during the load
   - C. The file was incomplete when the reader picked it up
   - D. The trailer was written before the last data line

   Answer: B. Source against file checks the export; file against target checks the load. Here only the load differs, and the lab's report names the rejected item and its owner.

6. An ABAP report builds the output path from a parameter a user types. What closes the path traversal risk?
   - A. Running the report only as a background job at night
   - B. Granting S_DATASET with a wildcard to the report's users
   - C. A logical file name, checked with FILE_VALIDATE_NAME
   - D. Writing the file to the DIR_HOME directory by default

   Answer: C. SAP's guidance is to map paths through logical file names and validate the physical name with FILE_VALIDATE_NAME before OPEN DATASET. A wildcard in S_DATASET widens the risk, and DIR_HOME is only the default starting point.

7. The application job for I03 shows Finished. What do you still check?
   - A. Nothing, Finished means every record was written
   - B. That the job ran under a person's own user account
   - C. The job log and the morning's reconciliation report
   - D. That a second job is scheduled for the next night

   Answer: C. SAP's training says Finished does not automatically mean successful, so the job log matters. The reconciliation then shows whether every record reached the target.

## Sources

- [Configure the SFTP Sender Adapter (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-sftp-sender-adapter-2de9ee5.md): Proxy Type Internet, Manual (edge only) or On-Premise through the Cloud Connector with a Location ID; Read Lock Strategy None (default, read at once), Content Change (waits until length and timestamp stop changing for at least a second), Done File Expected (default ${file:name}.done), Rename; Poll on One Worker Only for order-sensitive processing; Max. Messages per Poll 1 to 500, default 20, 1 for strict order; Lock Timeout default 15 min; Post-Processing Delete File (default), Keep File and Mark as Processed in Idempotent Repository, Keep File and Process Again (for testing), Move File; database repository identifies files by user, host and file name; after an error the rest of the batch continues, so a failed file may be retried later and out of order; file names over 100 characters are not covered by the idempotent option
- [Learn how to migrate SFTP Advanced File Selection from SAP Process Orchestration to Cloud Integration (SAP Developers tutorial, read 2026-11-30)](https://developers.sap.com/tutorials/ci-sftp-file-polling.html): File selection with Poll Enrich, a Content Modifier holding file name patterns and an Iterating Splitter with a Streaming option; headers CamelFileParent and CamelFileNameOnly carry folder and file name
- [Configuring the Receiver FTP Adapter (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/saphelp_nw73/helpdata/en/44/69d7cfa4b633eae10000000a1553f6/content.htm): PI receiver: File Construction Mode Create, Append, Add Time Stamp, Add Message ID, Add Counter; Put File Directly or Use Temporary File with a Temporary File Name Scheme; Empty Message Handling
- [Configuring a Sender File Adapter (SAP Learning, SAP Process Orchestration course, read 2026-11-30)](https://learning.sap.com/courses/sap-java-process-integration/configuring-a-sender-file-adapter_f8626d18-4742-432b-8266-8c12b4b281be): Quality of service Best Effort, Exactly Once, Exactly Once In Order; Msecs to Wait Before Modification Check so files still being written are not read; Processing Mode Archive with an archive directory; file content conversion
- [Platform-independent file names (SAP Help Portal, SAP NetWeaver 7.3 library, read 2026-11-30)](https://help.sap.com/saphelp_nw73/helpdata/en/fc/eb3dc4358411d1829f0000e829fbfe/content.htm): ABAP file names are physical and operating-system specific; logical names map to physical names and paths through tables; FILE_GET_NAME returns the physical name; maintained in Customizing or transaction FILE
- [Validating Physical Filenames Entered by the User (SAP Help Portal, SAP Enterprise Services library, read 2026-11-30)](https://help.sap.com/saphelp_em92/helpdata/en/38/bffdace37d4429998beb1e4acb11b7/content.htm): Use FILE_GET_NAME and FILE_VALIDATE_NAME to counter file path traversal; logical file of data format DIR for relative names; exceptions VALIDATION_FAILED and LOGICAL_FILENAME_NOT_FOUND; validate again before OPEN DATASET
- [Directory Traversal (SAP Help Portal, SAP NetWeaver 7.3 secure programming, read 2026-11-30)](https://help.sap.com/saphelp_nw73/helpdata/en/a8/d3c2aa14b04bf8bb2718aefeb478f5/content.htm): OPEN DATASET works in DIR_HOME by default and can reach any file if input is unrestricted; S_DATASET checked for all file access; S_PATH for paths in table SPTH; call FILE_VALIDATE_NAME before access
- [Introducing Application Jobs (SAP Learning, Administrating SAP S/4HANA Cloud Public Edition, read 2026-11-30)](https://learning.sap.com/courses/administrating-sap-s-4hana-cloud-public-edition/introducing-application-jobs_cf77594e-9dd1-454b-b8d1-05079dfee508): Apps Application Jobs, Application Job Templates and Maintain Job Users; statuses Scheduled, In Process, User Error, Failed, Canceled, Finished; Finished does not automatically mean successful; job log for errors; jobs run in a user's context
- [Integration flow design guidelines for exactly once scenarios (SAP blog, read 2026-11-30)](https://blogs.sap.com/2021/12/06/integration-flow-design-guidelines-for-exactly-once-scenarios/): Exactly once = guaranteed delivery (at least once) plus an idempotent receiver that discards duplicates; a JMS queue retries when the sender can't; the unique ID is a message ID or a payload value such as an order ID; ID Mapper for splits
- [SAP Multi-Bank Connectivity (MBC): all you need to know (SAP Community, blog post by SAP, read 2026-11-30)](https://community.sap.com/t5/financial-management-blog-posts-by-sap/sap-multi-bank-connectivity-mbc-all-you-need-to-know/ba-p/13619921): SAP-managed BTP solution between ERP and banks; pain.001 and pain.002, camt.052, camt.053, camt.054, MT940, BAI2; TLS plus message level security, mandatory between customer and MBC; connector for MBC in S/4HANA; app Manage Bank Messages (F4385); channels SWIFT, bank APIs, SFTP, host-to-host and EBICS
