# Hypercare and drift after go-live

> Run the weeks after an AI go-live with an exit plan, an on-call rota and incident playbooks, and tell a broken feed, a planned change and real drift apart.

- Course: Orchestrate, Unit 12 · The FDE operating system and capstone
- Page: https://erpfde.com/topics/hypercare-and-drift-after-go-live/
- Updated: 2026-11-23
- Reading time: Foundational 9 min, Deep 38 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

**Hypercare** is the agreed stretch of weeks right after go-live when the project team stays on hand and fixes problems fast. Then the system moves to normal operations, the **run** team.

For an AI system, go-live is when the real test starts. Three things can make its answers worse without any error message:

- **A broken feed.** A field arrives in a new format, and the model reads nonsense. This is a defect: fix the feed.
- **A planned business change.** A big customer doubles its volume. The data looks different, but the model may still be right. Watch it.
- **Drift.** The world changes, for example a carrier gets slower, and what the model learned stops being true. Retrain it.

All three look alike on a dashboard. The job after go-live is to **tell them apart quickly**, and to have a named person who acts on each. Hypercare ends on agreed criteria, not on a date alone, and the monitoring outlives it.

### Why it matters to the business

Take Calder Pumpworks, the fictional pump maker this course follows. Its late-delivery predictor scores every outbound delivery from the Rockford distribution center, and transport planners use the worklist each morning to expedite the risky ones. It went live on Monday 7 September 2026.

- **Week 3**: an extraction change started sending delivery weights in pounds while the model read kilograms. Heavy deliveries looked twice as heavy, and planners got more flags. Nobody saw an error. The weekly check caught it a week later; a daily check would have caught it the next morning.
- **Week 5**: Hallam's new distributor programme roughly doubled its volume on one route. The data changed sharply, yet the model's scores stayed right. Retraining would have cost effort for nothing.
- **Week 8**: after hypercare ended, the carrier on another route cut its pickups to three a week. Late deliveries on that route jumped from about one in five to about one in two. The inputs looked normal, so only a check on known outcomes saw it.

The cost of getting these wrong is concrete. A planner who stops trusting the worklist goes back to the old spreadsheet, and the business case is gone. A model retrained on the pound-weight rows learns the defect. A model nobody retrains misses half the late deliveries on the slow route, and customers wait.

> **Note** **For functional consultants.** Hypercare for AI adds work to yours. Business changes you configure or agree (a new route, a new carrier, a new order type, a changed shipping point) go on the AI system's **change calendar** before they happen, so a drift alarm can be explained. Changes to extraction views or field mappings are tested against the model's data checks, not only the report that uses them. And the test cases you wrote for UAT become the regression set the run team reruns after every retraining.

### How SAP does it

SAP's implementation method, SAP Activate, has six phases: Discover, Prepare, Explore, Realize, Deploy and Run. SAP Learning's lesson on the methodology structure places **hypercare in the Deploy phase**, once the system is live, with the project team on hand for a period usually set in the contract or in a transition-to-operations plan. The **Run phase** covers incident and change management, system and application monitoring and upgrades ([SAP Learning](https://learning.sap.com/courses/discovering-sap-activate-implementation-tools-and-methodology/describing-the-methodology-structure)). SAP's change management course describes the end of hypercare as a systematic handover to the customer's IT and business departments ([SAP Learning](https://learning.sap.com/courses/acting-as-professional-change-manager-in-sap-cloud-projects/fostering-sustainable-user-adoption)). Neither page gives a standard length.

For monitoring, as of November 2026 SAP points to **SAP Cloud ALM for Operations**, available with a cloud subscription or Enterprise Support ([SAP Learning](https://learning.sap.com/courses/operating-sap-business-ai-platform/explaining-central-observability-tools_c3e8a8ad-76e5-43ec-a7b9-0705532a44fd)):

- **Health Monitoring** watches SAP cloud services and customer applications on SAP BTP, and can raise an alert, send an email, open a ServiceNow ticket or post to a chat channel ([SAP Learning](https://learning.sap.com/courses/operating-with-sap-cloud-alm/health-monitoring)).
- **Business Process Monitoring** tracks process KPIs for throughput, lead time, backlog and exceptions, for example in Lead to Cash ([SAP Learning](https://learning.sap.com/courses/operating-with-sap-cloud-alm/business-process-monitoring)).

The pages we read describe no check of a custom model's data or accuracy. So for a model or agent your team built, Cloud ALM tells you whether the application is up and whether the process is healthy, and your own checks tell you whether the AI is still right. The deep layer shows both.

### Three signals, three responses

| What you see | Likely cause | Response | Owner |
| --- | --- | --- | --- |
| A field has a new unit, format or many blanks | Broken feed (a defect) | **Incident**: fix the feed, rescore open items, keep bad rows out of training | Integration or data team |
| Inputs moved, and a planned change on the calendar explains it | Planned business change | **Watch**: confirm outcomes still hold next week | Model owner |
| Inputs moved and nothing explains it | Unknown change | **Investigate**: ask the process owner what changed | Model owner with process owner |
| Inputs look normal, but outcomes moved | Drift: the world changed | **Retrain**: train, backtest, second-person approval | Model owner |
| An agent's drafts get rejected far more often, or it acts oddly | Model change, prompt injection, broken tool or new kind of case | **Incident**: switch the agent off, keep the manual path running | AI platform team and process owner |

### Hypercare that ends well

Agree these before go-live, in writing:

1. **Length and exit criteria.** For example: no open severity 1 or 2 incidents, two clean weekly checks in a row, and the run team has handled one incident with the playbook.
2. **An on-call rota.** Who answers during business hours and after them, for the AI system and for its SAP interfaces. During hypercare the project team is first; after it, the run team.
3. **Playbooks.** One page per incident type: how to recognize it, the first action in 15 minutes, who decides, how to tell users.
4. **A kill switch that was tested.** Switching the AI off must leave a working manual process. Test that before go-live, not during the first incident.
5. **A change calendar.** The business tells the model owner about planned changes before they happen.
6. **A retraining plan.** Schedule, triggers, who approves, how to roll back.
7. **A named owner after hypercare.** Drift often arrives after the project team has left. In Calder's case it came three weeks later.

### Questions to ask

1. When does hypercare end, and what must be true before it does?
2. Who is on call for the AI system after the project team leaves, and do they have the playbooks?
3. How quickly would we notice if a field in the feed changed format? Daily, weekly, or when a user complains?
4. How long until we know whether a prediction was right, and what do we watch before then?
5. Who keeps the change calendar, and which business changes must go on it?
6. What triggers a retraining, who approves the new model, and how do we roll back?
7. If we switch the agent off at 9 a.m., can the team still do the work by hand?
8. Do we have the before and after numbers to show the system still earns its keep?

### Common misconceptions

- **"Hypercare is a fixed six weeks."** SAP's pages leave the length to the contract or the transition plan. Set it, but end it on criteria.
- **"Drift means retrain."** A broken feed needs a fix, and a planned change may need nothing. Retraining on a broken feed teaches the model the defect.
- **"If the inputs look normal, the model is fine."** Calder's slow carrier changed no input at all. Only known outcomes showed it.
- **"Our SAP monitoring covers the AI."** The application and the process can be healthy while the model is wrong.
- **"An agent incident is a bug ticket."** An agent drafting wrong actions at scale needs the kill switch first and the analysis second.

### Key terms

- **Hypercare:** the agreed period after go-live when the project team stays on hand and resolves problems quickly, before handing over to the run team.
- **Run team:** the people who operate the system after hypercare, under incident and change management.
- **Data drift:** the inputs a model sees change compared with what it learned from.
- **Concept drift:** the link between inputs and outcomes changes, so the same inputs now mean a different result.
- **Label delay:** the time between a prediction and knowing whether it was right.
- **Change calendar:** a list of planned business changes, used to explain monitoring alarms.
- **Kill switch:** a tested way to turn the AI off and fall back to the manual process.
- **Population stability index (PSI):** a number that measures how far a distribution has moved from a reference.

### Check yourself

1. In SAP Activate, where does hypercare sit?
   - A. In the Realize phase, before cutover starts
   - B. In the Deploy phase, once the system has gone live
   - C. In the Run phase, as part of upgrade management
   - D. In the Explore phase, as part of fit-to-standard

   Answer: B. SAP Learning places sustainment and hypercare in the Deploy phase after go-live. The Run phase follows, with incident and change management, monitoring and upgrades.

2. Calder's delivery weights start arriving in pounds while the model reads kilograms. What is the right response?
   - A. Retrain the model so it learns the new weights
   - B. Add the change to the calendar and watch next week
   - C. Treat it as an incident: fix the feed and rescore
   - D. Lower the threshold until the flags look normal again

   Answer: C. A changed unit is a defect in the feed, not a change in the world. Retraining on those rows would teach the model the defect, so the feed is fixed and the bad rows stay out of training.

3. Hallam doubles its volume on one route, and the model's known outcomes still match its predictions. What should the team do?
   - A. Retrain at once, because the input data has shifted
   - B. Note it as a planned change and keep watching outcomes
   - C. Switch the model off until the volume returns to normal
   - D. Open an incident with the integration team for the feed

   Answer: B. Inputs moved, but for a known business reason, and the outcomes still hold. Retraining would cost effort for nothing; the next weekly check confirms the model is still right.

4. Why did only a check on known outcomes catch Calder's slower carrier?
   - A. The carrier change was hidden in a new field the model ignored
   - B. The input checks were switched off after hypercare ended
   - C. Outcome checks run daily while input checks run weekly
   - D. The inputs did not change; only what they led to changed

   Answer: D. The routes, weights and dates looked the same as before. What changed was how often deliveries on that route ended up late, which is concept drift, and only known outcomes reveal it.

5. What should be true before a team declares hypercare over?
   - A. The contract's number of weeks has passed, whatever the state
   - B. Every user has been trained on the new process at least twice
   - C. Agreed exit criteria are met and a named run owner has the playbooks
   - D. The model has been retrained once on post-go-live data

   Answer: C. SAP leaves the length to the contract or transition plan, so the end should rest on criteria such as no open severe incidents and clean checks. Drift often arrives after hypercare, so a named owner with playbooks must exist.

6. An agent's drafted actions are suddenly rejected far more often than in testing. What comes first?
   - A. Ask the vendor for the model's new release notes
   - B. Switch the agent off and keep the manual process running
   - C. Retrain the agent on the rejected drafts from this week
   - D. Raise the approval threshold so fewer drafts reach people

   Answer: B. An agent producing wrong drafts at scale is an incident. The kill switch limits the damage while the cause, such as a model change or a broken tool, is found; that is why the manual path must be tested before go-live.

7. What does SAP Cloud ALM for Operations give an AI system your team built, based on the pages read?
   - A. A built-in check of the model's accuracy against outcomes
   - B. Automatic retraining when a process KPI turns red
   - C. A drift score for every feature the model reads
   - D. Application health and process KPIs, not model accuracy

   Answer: D. Health Monitoring covers applications on SAP BTP and Business Process Monitoring covers process KPIs. The pages read describe no model data or accuracy check, so the team adds its own.

## Deep layer

### Mental model

A live model makes promises about a world that keeps moving. After go-live you watch three layers, in this order, because each one is cheaper and faster to check than the next:

```mermaid
flowchart TB
  D["1. Data checks<br/>Is the feed intact?<br/>daily, no outcomes needed"] --> I["2. Input drift<br/>Do inputs look like training?<br/>weekly, no outcomes needed"]
  I --> O["3. Outcome checks<br/>Are predictions still right?<br/>needs known outcomes"]
  D -->|fail| INC[Incident: fix the feed]
  I -->|moved, calendar explains| W[Watch]
  I -->|moved, nothing explains| INV[Investigate]
  O -->|moved, inputs stable| R[Retrain]
```

The rule that makes the rest work: **every alarm gets a cause before it gets an action.** A broken feed, a planned change and concept drift can raise the same input alarm. The response differs, and the wrong response does damage: retraining on a broken feed bakes the defect in, and ignoring drift because "the inputs look fine" lets the model fail quietly.

Hypercare is the same watch at a higher frequency, with the project team on call and a written exit.

### How it works

#### Three kinds of change

| Kind | What changed | Example at Calder | Visible in inputs? | Visible in outcomes? |
| --- | --- | --- | --- | --- |
| **Feed defect** | How data is recorded or sent | Weights in pounds, read as kilograms | Yes, sharply | Sometimes, later |
| **Data drift** (covariate shift) | Which cases arrive | More deliveries on Hallam's route | Yes | Only if the model is weak there |
| **Concept drift** | What the inputs mean for the outcome | A carrier cuts pickups on route `RK0003` | No | Yes |

A fourth kind belongs to agents and LLM features: **the model itself changes** under you, because a provider retires a version or a route falls back to another model. [Running AI on SAP BTP in production](https://erpfde.com/topics/running-ai-on-btp/) and [Model tiers and prices in late 2026](https://erpfde.com/topics/model-tiers-and-prices-late-2026/) cover the retirement calendar; the playbook below covers the incident.

#### Label delay decides what you can watch

You only know whether a prediction was right when the outcome arrives. That delay differs by use case:

| Use case | Outcome known | Delay |
| --- | --- | --- |
| Late goods issue (this topic) | When the planned goods issue date passes: shipped by then is on time, not shipped is late | Days |
| Customer pays late | When the invoice is paid, or its due date passes unpaid | Weeks |
| Invoice extraction | When the AP accountant corrects or accepts the fields | Hours |
| Order-exception agent | When the reviewer approves or rejects the draft | Minutes to a day |

Until outcomes arrive, inputs and scores are the only early warning. That is why input drift checks exist even though they can't prove the model is wrong.

#### Measuring input drift with PSI

The **population stability index** compares how a feature's values spread across bins (or categories) in a reference period with a recent window:

```text
PSI = sum over bins of (recent share - reference share) x ln(recent share / reference share)
```

Zero means the same distribution; it grows as the shares move apart. Evidently, an open-source monitoring library, offers PSI for numerical and categorical columns and flags drift at a default threshold of 0.1. It also chooses a different default test by column type and data volume (for example Kolmogorov-Smirnov for small numerical samples), and calls a whole dataset drifted when more than half of its columns drift by default ([Evidently docs](https://docs.evidentlyai.com/metrics/customize_data_drift)). This topic uses PSI with a warning at 0.10 and an alarm at 0.25; both are course values.

Two cautions. PSI on a tiny window is noisy, so watch a week, not a day. And an empty bin makes the logarithm blow up, so implementations replace zero shares with a small number; the lab uses 0.0001.

Run the same check on the **model's scores**. A score distribution that moves says the model will behave differently even before outcomes arrive.

#### Outcome checks: calibration before recall

When outcomes are known, compare the **predicted late share** (the average score) with the **observed late share**. If the model says 21% and 31% turn out late, it is under-predicting. Do it per segment too: Calder's overall gap stayed under the alarm for a week while route `RK0003` showed 44% against 19%. Recall against the test recall is the second check; it is noisier, because it rests only on the late cases.

#### The change calendar

A change calendar lists planned business changes with dates and the features they will move. The check consults it: an input alarm that a calendar entry explains becomes WATCH, one that nothing explains becomes INVESTIGATE. It turns "the data looks different" into a conversation with the process owner before go-live, not after an alarm.

#### Retraining triggers

| Trigger | Example | Note |
| --- | --- | --- |
| Schedule | Monthly, on all known outcomes | The default; the backtest in the [late-delivery project](https://erpfde.com/topics/project-late-delivery-predictor/) shows what it is worth |
| Outcome alarm | A route's observed late share 15 points above predicted | Retrain early, after confirming the feed is clean |
| Planned change | A new shipping point goes live | Retrain once enough outcomes exist under the new setup |
| Never | A feed defect | Fix the feed and keep the bad rows out of training |

Retraining after concept drift raises a window question. Train on everything and the old rows outvote the new ones; train on the last few weeks and estimates get noisy. The lab lets you compare both.

#### Agents: what drifts and what breaks

An agent has no single score to watch, so watch its **outcomes** and its **behavior**: approval and rejection rate of its drafts, tool errors, steps per task, cost per task, and refused inputs. Then plan for these incidents:

| Incident | How you notice | First 15 minutes | Then |
| --- | --- | --- | --- |
| Model changed or retired | Rejections up after a provider date; fallback model in the logs | Pin or roll back the model route; if not possible, kill switch | Rerun the eval set on the new model before switching back on |
| Prompt injection got through | A draft follows text from a customer note | Kill switch for write tools; keep read-only | Quarantine the input; add it to the test set |
| Tool or API broken | Tool errors jump after an SAP change or a role change | Kill switch if drafts are wrong, otherwise let it fail closed | Fix the role or the API call; rerun regression tests |
| Loop or cost spike | Steps or tokens per task far above normal | Gateway budget or step cap stops it | Find the case that loops; add a test |
| New kind of case | Rejections concentrated on one order type or language | Route that kind to people | Extend the instructions or tools, then re-evaluate |

For Calder's order-exception agent, the UAT gates from [UAT and sign-off for AI in SAP programs](https://erpfde.com/topics/uat-and-sign-off-for-ai-in-sap-programs/) (C01 owner correct, C02 must-pass cases) become the weekly hypercare check, run on a fresh sample.

The kill switch is a flag the agent reads on every task, owned by the process owner and the run team, that leaves the manual worklist working. [Evaluating in production](https://erpfde.com/topics/online-evaluation-and-user-feedback/) covers the approval and override signals; [Observability for AI systems](https://erpfde.com/topics/observability-for-ai-systems/) covers the traces that make the "how you notice" column possible.

#### Who is on call

| Role | In hypercare | After hypercare |
| --- | --- | --- |
| First line for users | Project team's hypercare desk | Service desk of the run team |
| Model owner (checks, retraining) | The FDE or data scientist who built it | A named person in the AI platform or analytics team |
| Process owner (kill switch, business calls) | Logistics manager, Rockford DC | Same |
| SAP interfaces and extraction | Integration lead of the project | Run team for integration |
| AI platform (BTP subaccount, model access, gateway) | Platform team | Same |

Severity levels are a local agreement. A workable scale for AI: severity 1 when wrong actions or drafts reach many users or data leaks; severity 2 when quality drops below the signed threshold; severity 3 for a contained defect with a workaround; severity 4 for cosmetic issues.

### Build it yourself: a weekly drift watch for the late-delivery predictor

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 12](https://erpfde.com/topics/set-up-for-unit-12/). This walkthrough doesn't repeat those steps. [Predicting late deliveries with SAP data](https://erpfde.com/topics/predicting-late-deliveries-with-sap-data/) explains the model and its label; reading it first helps, but this lab runs on its own.

You will run Calder's drift watch for every Monday from go-live on 7 September to 23 November 2026. It generates outbound deliveries from shipping point `RK01`, trains a small stand-in for the late-delivery model, and checks each week in three layers: the feed, the inputs and the known outcomes. It reads a change calendar and gives each week a verdict. Then you retrain after the drift and compare two training windows.

```mermaid
flowchart LR
  G[Deliveries<br/>seed 42] --> M[Model m20260830<br/>trained Jun to Aug]
  G --> C[Monday checks<br/>feed, inputs, outcomes]
  M --> C
  K[change_calendar.json] --> C
  C --> V[Verdict per week<br/>watch_log.csv]
  C --> R[week_YYYYMMDD.md]
  V --> T[retrain --as-of<br/>old vs new]
```

> **Note** **New words.** A **reference** is the slice of training data that stands for "normal". A **window** is the recent slice you compare with it. A **verdict** is the script's one-word recommendation. A **seed** fixes the random numbers, so your run matches the page.

The model in this lab is a small naive Bayes classifier written in plain Python, so the lab needs no libraries. It stands in for the Unit 17 model; the checks work the same on any model's scores. All deliveries, routes, dates and thresholds are made up for Calder, a fictional company. Nothing connects to an SAP system.

#### What you need

- The course folder `orchestrate-course` with its `.venv`, from the setup topics.
- No account, no key, no new libraries. Unit 12 adds no lines to `requirements.txt`.
- Time: about 35 minutes. Cost: free.

#### Step 1: Open your 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. Turn on the virtual environment:

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. You should see `(.venv)` at the start of the prompt. The `unit12` folder exists from Set up for Unit 12. If it doesn't, create it with `mkdir unit12` (the same command works in both terminals).

Run every command from the course folder, not from inside `unit12`. On macOS or Linux, if `python` isn't found before `.venv` is active, use `python3`.

#### Step 2: Create the script

1. In VS Code's Explorer, right-click `unit12` and choose **New File**. Name it `drift_watch.py`.
2. Paste in the code below and save.

```python
"""Hypercare drift watch for Calder's late-delivery predictor (fictional data, built-in modules only).

Every Monday it compares last week's deliveries with what the model learned, checks the outcomes
that are already known, reads the change calendar and says what to do: OK, WATCH, INVESTIGATE,
INCIDENT or RETRAIN.

    python unit12/drift_watch.py watch                     # every Monday from go-live
    python unit12/drift_watch.py week --date 2026-11-09    # one Monday in detail, saved as a report
    python unit12/drift_watch.py watch --no-calendar       # the same weeks without the change calendar
    python unit12/drift_watch.py retrain --as-of 2026-11-09   # retrain and replay the weeks after
"""
import argparse
import csv
import json
import math
import random
from collections import Counter
from datetime import date, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent
OUT = HERE / "hypercare"
SEED = 42

TRAIN_START, TRAIN_END = date(2026, 6, 1), date(2026, 8, 30)   # the model learned from these deliveries
GO_LIVE = date(2026, 9, 7)
HYPERCARE_END = date(2026, 10, 16)                              # agreed exit: Friday of week 6
LAST_DAY = date(2026, 11, 22)

ROUTES = ["RK0001", "RK0002", "RK0003"]
THRESHOLD = 0.25          # flag a delivery for the planner at this score or above (course value)
PSI_WARN, PSI_ALARM = 0.10, 0.25
GAP_ALARM = 0.08          # observed late share above predicted by more than 8 points
RECALL_DROP = 0.15
MIN_KNOWN = 100           # fewer known outcomes than this: performance is not judged
MIN_ROUTE = 30            # per-route check needs this many known outcomes
ROUTE_GAP_ALARM = 0.15    # a route's observed late share above predicted by more than 15 points

# The change calendar: business changes known in advance. Course values; the exercise adds one.
DEFAULT_CALENDAR = [
    {"id": "CAL-01", "from": "2026-09-07", "to": "2026-09-13", "feature": "*",
     "note": "Go-live week: planners learn the worklist"},
    {"id": "CAL-02", "from": "2026-10-05", "to": "2026-12-31", "feature": "route",
     "note": "Hallam's distributor programme: about twice the volume on route RK0002"},
]


def weight_band(kg):
    return "<300" if kg < 300 else "300-800" if kg < 800 else "800-1500" if kg < 1500 else "1500+"


def lead_band(days):
    return "1 day" if days <= 1 else "2-3 days" if days <= 3 else "4+ days"


def make_deliveries():
    """Outbound deliveries from shipping point RK01, 1 June to 22 November 2026 (seed 42)."""
    rng = random.Random(SEED)
    rows, number, day = [], 82100001, TRAIN_START
    while day <= LAST_DAY:
        if day.weekday() < 5:
            hallam_up = day >= date(2026, 10, 5)                        # CAL-02: a planned change
            share = [0.30, 0.50, 0.20] if hallam_up else [0.45, 0.25, 0.30]
            for _ in range(rng.randint(24, 32) + (8 if hallam_up else 0)):
                route = rng.choices(ROUTES, weights=share)[0]
                pumps = rng.choice([1, 2, 2, 4, 4, 6, 8])
                kg = round(pumps * rng.choice([205, 285]) + rng.uniform(0, 60), 1)
                lead = rng.choice([1, 1, 2, 2, 3, 3, 4, 5])
                planned = day + timedelta(days=lead)
                while planned.weekday() >= 5:
                    planned += timedelta(days=1)
                p = 0.08 + (0.10 if kg >= 800 else 0) + (0.08 if lead <= 1 else 0)
                p += {"RK0001": 0.0, "RK0002": 0.07, "RK0003": 0.02}[route]
                p += 0.06 if planned.weekday() == 4 else 0
                if route == "RK0003" and day >= date(2026, 10, 26):    # not in any calendar
                    p += 0.40       # the RK0003 carrier cut its pickups to three a week
                late = rng.random() < p
                actual = planned + timedelta(days=rng.randint(1, 3)) if late else planned - timedelta(days=rng.randint(0, 1))
                unit, sent_kg = "KG", kg
                if date(2026, 9, 21) <= day <= date(2026, 9, 29):       # an extraction change, fixed on 30 Sep
                    unit, sent_kg = "LB", round(kg * 2.20462, 1)
                rows.append({"delivery": str(number), "created": day, "planned_gi": planned, "actual_gi": actual,
                             "route": route, "weight": sent_kg, "unit": unit, "true_kg": kg, "lead_days": lead,
                             "late": late})
                number += 1
        day += timedelta(days=1)
    return rows


def features(r):
    """What the model sees at creation. Like a pipeline that ignores the unit field, it reads the number as kg."""
    return {"route": r["route"], "weight": weight_band(r["weight"]), "lead": lead_band(r["lead_days"]),
            "gi_friday": "yes" if r["planned_gi"].weekday() == 4 else "no"}


class Model:
    """A small naive Bayes stand-in for the Unit 17 model, so the lab needs no libraries."""

    def __init__(self, rows, version):
        self.version = version
        self.n = len(rows)
        self.late = sum(r["late"] for r in rows)
        self.counts = {c: Counter() for c in (True, False)}
        self.values = {}
        for r in rows:
            for k, v in features(r).items():
                self.counts[r["late"]][(k, v)] += 1
                self.values.setdefault(k, set()).add(v)

    def score(self, r):
        logit = math.log((self.late + 1) / (self.n - self.late + 1))
        for k, v in features(r).items():
            m = len(self.values[k])
            pl = (self.counts[True][(k, v)] + 1) / (self.late + m)
            po = (self.counts[False][(k, v)] + 1) / (self.n - self.late + m)
            logit += math.log(pl / po)
        return 1 / (1 + math.exp(-logit))


def psi(expected, actual, keys):
    """Population stability index between two lists of category values. 0.0001 stands in for empty bins."""
    e, a = Counter(expected), Counter(actual)
    total = 0.0
    for k in keys:
        pe = max(e[k] / len(expected), 0.0001)
        pa = max(a[k] / len(actual), 0.0001)
        total += (pa - pe) * math.log(pa / pe)
    return total


def score_band(p):
    return min(int(p * 10), 6)   # 0.0-0.1, ..., 0.6+


def performance(model, rows):
    """Recall, predicted and observed late share for deliveries whose outcome is known."""
    if not rows:
        return None
    scores = [model.score(r) for r in rows]
    late = [r["late"] for r in rows]
    caught = sum(1 for s, y in zip(scores, late) if y and s >= THRESHOLD)
    return {"n": len(rows), "predicted": sum(scores) / len(rows), "observed": sum(late) / len(rows),
            "recall": caught / sum(late) if sum(late) else None,
            "flag_rate": sum(1 for s in scores if s >= THRESHOLD) / len(rows)}


def in_calendar(calendar, feature, monday):
    week_start = monday - timedelta(days=7)
    for c in calendar:
        if c["feature"] in (feature, "*") and date.fromisoformat(c["from"]) <= monday - timedelta(days=1) \
                and date.fromisoformat(c["to"]) >= week_start:
            return c["id"]
    return None


def check_week(model, reference, test_perf, rows, monday, calendar):
    """All checks for the Monday `monday`. Inputs: deliveries created last week. Outcomes: planned goods issue
    in the 14 days before Monday (an outcome is known once its planned goods issue date has passed)."""
    week = [r for r in rows if monday - timedelta(days=7) <= r["created"] < monday]
    known = [r for r in rows if monday - timedelta(days=14) <= r["planned_gi"] < monday and r["created"] >= GO_LIVE]
    checks = []

    bad_unit = sum(1 for r in week if r["unit"] != "KG")
    checks.append(("Weight unit is KG", f"{bad_unit} of {len(week)} not KG", "FAIL" if bad_unit else "ok", "data"))

    ref_f = [features(r) for r in reference]
    week_f = [features(r) for r in week]
    for k in ("route", "weight", "lead", "gi_friday"):
        keys = sorted({f[k] for f in ref_f} | {f[k] for f in week_f})
        value = psi([f[k] for f in ref_f], [f[k] for f in week_f], keys)
        status = "ALARM" if value >= PSI_ALARM else "warn" if value >= PSI_WARN else "ok"
        cal = in_calendar(calendar, k, monday) if status != "ok" else None
        checks.append((f"Input PSI {k}", f"{value:.2f}" + (f" ({cal})" if cal else ""), status, "input" if not cal else "explained"))

    sb_ref = [score_band(model.score(r)) for r in reference]
    sb_week = [score_band(model.score(r)) for r in week]
    value = psi(sb_ref, sb_week, range(7))
    status = "ALARM" if value >= PSI_ALARM else "warn" if value >= PSI_WARN else "ok"
    cal = in_calendar(calendar, "score", monday) if status != "ok" else None
    checks.append(("Score PSI", f"{value:.2f}", status, "input" if not cal else "explained"))

    perf = performance(model, known)
    if perf is None or perf["n"] < MIN_KNOWN:
        checks.append(("Known outcomes", f"{perf['n'] if perf else 0}, too few to judge", "wait", "perf"))
    else:
        gap = perf["observed"] - perf["predicted"]
        checks.append(("Observed vs predicted late", f"{perf['observed']:.0%} vs {perf['predicted']:.0%} ({perf['n']} known)",
                       "ALARM" if gap > GAP_ALARM else "ok", "perf"))
        drop = test_perf["recall"] - perf["recall"]
        checks.append(("Recall vs test", f"{perf['recall']:.2f} vs {test_perf['recall']:.2f}",
                       "ALARM" if drop > RECALL_DROP else "ok", "perf"))
        for route in ROUTES:
            sub = [r for r in known if r["route"] == route]
            if len(sub) >= MIN_ROUTE:
                rp = performance(model, sub)
                checks.append((f"Route {route} observed vs predicted", f"{rp['observed']:.0%} vs {rp['predicted']:.0%} ({rp['n']} known)",
                               "ALARM" if rp["observed"] - rp["predicted"] > ROUTE_GAP_ALARM else "ok", "perf"))
        checks.append(("Flags per delivery", f"{perf['flag_rate']:.0%} vs {test_perf['flag_rate']:.0%}", "info", "perf"))

    fails = {kind for _, _, s, kind in checks if s in ("FAIL", "ALARM")}
    explained = any(kind == "explained" and s in ("ALARM", "warn") for _, _, s, kind in checks)
    if "data" in fails:
        verdict = "INCIDENT", "Data feed broken: fix the feed, rescore open deliveries. Don't retrain on bad data."
    elif "perf" in fails and "input" not in fails:
        verdict = "RETRAIN", "Inputs look normal but outcomes moved: the world changed (concept drift). Retrain, backtest, second-person approval."
    elif "perf" in fails:
        verdict = "INVESTIGATE", "Inputs and outcomes both moved: find the cause before retraining."
    elif "input" in fails:
        verdict = "INVESTIGATE", "Inputs moved and no calendar entry explains it: ask the process owner what changed."
    elif explained:
        verdict = "WATCH", "Inputs moved as the change calendar said they would; outcomes still hold."
    elif any(s == "warn" for _, _, s, _k in checks):
        verdict = "WATCH", "An input moved a little; outcomes still hold. Look again next Monday."
    else:
        verdict = "OK", "Nothing moved."
    return {"monday": monday, "deliveries": len(week), "checks": checks, "verdict": verdict}


def setup(as_of=None, days=None):
    rows = make_deliveries()
    train = [r for r in rows if TRAIN_START <= r["created"] <= TRAIN_END]
    split = date(2026, 8, 3)
    fit = [r for r in train if r["created"] < split]
    test = [r for r in train if r["created"] >= split]
    model = Model(fit, "m20260830")
    test_perf = performance(model, test)
    model = Model(train, "m20260830")      # refit on all training rows, as Unit 17 does
    reference = train[-(len(train) // 3):]  # "normal": the last month or so of training rows
    if as_of:
        known = [r for r in rows if r["planned_gi"] < as_of and r["unit"] == "KG"]
        recent = [r for r in known if r["created"] >= as_of - timedelta(days=days)] if days else known[-len(train):]
        model = Model(recent, f"m{as_of:%Y%m%d}")
        reference = recent[-(len(recent) // 3):]
    return rows, model, reference, test_perf


def mondays(start):
    d = start + timedelta(days=(7 - start.weekday()) % 7)
    while d <= LAST_DAY + timedelta(days=1):
        yield d
        d += timedelta(days=7)


def load_calendar(path, use):
    if not use:
        return []
    if path.exists():
        return json.loads(path.read_text())
    path.parent.mkdir(exist_ok=True)
    path.write_text(json.dumps(DEFAULT_CALENDAR, indent=2))
    print(f"Wrote the change calendar to {path.relative_to(HERE.parent)}")
    return DEFAULT_CALENDAR


def phase(monday):
    return "hypercare" if monday <= HYPERCARE_END + timedelta(days=3) else "run"


def cmd_watch(args, calendar):
    rows, model, reference, test_perf = setup()
    print(f"Model {model.version}: trained on {TRAIN_START} to {TRAIN_END}, live since {GO_LIVE}. "
          f"Test recall {test_perf['recall']:.2f}, threshold {THRESHOLD}.")
    print(f"{'Monday':<11} {'phase':<10} {'deliv':>5}  {'alarms':<44} verdict")
    log = []
    for monday in mondays(GO_LIVE + timedelta(days=1)):
        res = check_week(model, reference, test_perf, rows, monday, calendar)
        alarms = ", ".join(n.replace("Input PSI ", "PSI ").replace("Observed vs predicted late", "Late gap")
                           .replace(" observed vs predicted", " gap") for n, _, s, _k in res["checks"] if s in ("FAIL", "ALARM")) or "-"
        print(f"{monday}  {phase(monday):<10} {res['deliveries']:>5}  {alarms[:44]:<44} {res['verdict'][0]}")
        log.append({"monday": str(monday), "phase": phase(monday), "verdict": res["verdict"][0]})
    OUT.mkdir(exist_ok=True)
    with open(OUT / "watch_log.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["monday", "phase", "verdict"])
        w.writeheader()
        w.writerows(log)
    print(f"Saved {(OUT / 'watch_log.csv').relative_to(HERE.parent)}")


def cmd_week(args, calendar):
    rows, model, reference, test_perf = setup()
    monday = date.fromisoformat(args.date)
    if monday.weekday() != 0:
        raise SystemExit(f"{monday} is not a Monday. The watch runs on Mondays.")
    res = check_week(model, reference, test_perf, rows, monday, calendar)
    print(f"Drift watch for {monday} ({phase(monday)}), model {model.version}, {res['deliveries']} deliveries created last week.\n")
    for name, value, status, _ in res["checks"]:
        print(f"  {name:<36} {value:<26} {status}")
    print(f"\n{res['verdict'][0]}: {res['verdict'][1]}")
    OUT.mkdir(exist_ok=True)
    out = OUT / f"week_{monday:%Y%m%d}.md"
    lines = [f"# Drift watch {monday}", "", f"Model {model.version}; phase {phase(monday)}.", "",
             "| Check | Value | Status |", "| --- | --- | --- |"]
    lines += [f"| {n} | {v} | {s} |" for n, v, s, _ in res["checks"]]
    lines += ["", f"**{res['verdict'][0]}**: {res['verdict'][1]}", ""]
    out.write_text("\n".join(lines))
    print(f"Saved {out.relative_to(HERE.parent)}")


def cmd_retrain(args, calendar):
    as_of = date.fromisoformat(args.as_of)
    rows, old, _, test_perf = setup()
    _, new, _, _ = setup(as_of, args.days)
    window = f"{new.n} deliveries created in the {args.days} days before" if args.days else \
        f"the {new.n} most recent deliveries with a known outcome before"
    print(f"Retrained {new.version} on {window} {as_of} (rows sent in LB left out).")
    after = [r for r in rows if r["planned_gi"] >= as_of and r["planned_gi"] < LAST_DAY]
    for label, m in (("old " + old.version, old), ("new " + new.version, new)):
        p = performance(m, after)
        print(f"  {label:<14} on {p['n']} deliveries due {as_of} to {LAST_DAY - timedelta(days=1)}: "
              f"recall {p['recall']:.2f}, predicted {p['predicted']:.0%} vs observed {p['observed']:.0%}")
    rk3 = [r for r in after if r["route"] == "RK0003"]
    for label, m in (("old", old), ("new", new)):
        avg = sum(m.score(r) for r in rk3) / len(rk3)
        print(f"  {label} model's average score on route RK0003: {avg:.2f} (observed late {sum(r['late'] for r in rk3) / len(rk3):.0%})")
    print("Next: backtest, then a second person promotes it. Keep the old model ready for rollback.")


def main():
    parser = argparse.ArgumentParser(description="Weekly drift watch for the late-delivery predictor (fictional Calder data).")
    parser.add_argument("--no-calendar", action="store_true", help="ignore the change calendar")
    sub = parser.add_subparsers(dest="cmd", required=True)
    sub.add_parser("watch", help="every Monday from go-live")
    w = sub.add_parser("week", help="one Monday in detail")
    w.add_argument("--date", required=True)
    r = sub.add_parser("retrain", help="retrain as of a date and compare on the weeks after")
    r.add_argument("--as-of", required=True)
    r.add_argument("--days", type=int, help="train only on deliveries created in this many days before --as-of")
    args = parser.parse_args()
    calendar = load_calendar(OUT / "change_calendar.json", not args.no_calendar)
    {"watch": cmd_watch, "week": cmd_week, "retrain": cmd_retrain}[args.cmd](args, calendar)


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

#### Step 3: Watch every Monday since go-live

1. Run:

   ```bash
   python unit12/drift_watch.py watch
   ```

**What success looks like:**

```text
Wrote the change calendar to unit12/hypercare/change_calendar.json
Model m20260830: trained on 2026-06-01 to 2026-08-30, live since 2026-09-07. Test recall 0.37, threshold 0.25.
Monday      phase      deliv  alarms                                       verdict
2026-09-14  hypercare    140  -                                            OK
2026-09-21  hypercare    133  -                                            OK
2026-09-28  hypercare    139  Weight unit is KG, PSI weight, Score PSI     INCIDENT
2026-10-05  hypercare    141  Weight unit is KG                            INCIDENT
2026-10-12  hypercare    183  -                                            WATCH
2026-10-19  hypercare    185  PSI route                                    WATCH
2026-10-26  run          179  -                                            WATCH
2026-11-02  run          173  PSI route                                    WATCH
2026-11-09  run          179  PSI route, Route RK0003 gap                  RETRAIN
2026-11-16  run          179  PSI route, Late gap, Route RK0003 gap        RETRAIN
2026-11-23  run          183  PSI route, Late gap, Route RK0003 gap        RETRAIN
Saved unit12/hypercare/watch_log.csv
```

The first line appears only on the first run. Your numbers should match exactly: the data comes from seed 42.

2. Read it as three stories:

   - **28 September and 5 October: INCIDENT.** Deliveries created from 21 to 29 September were sent in pounds. The unit check fails, and the weight and score distributions jump. The outcomes still look fine, because the known outcomes lag the inputs by a week or more. A model owner who waited for the outcomes would have waited too long.
   - **12 October to 2 November: WATCH.** From 5 October the route mix moves (PSI up to 0.34), but calendar entry `CAL-02` explains it and the outcomes hold.
   - **9 November onward: RETRAIN.** Route `RK0003` got slower on 26 October. No input moved for it. Two weeks later enough of its outcomes are known, and the route's observed late share is far above the prediction.

3. Notice where hypercare ended: the exit review on Monday 19 October saw a clean feed and an explained change. The drift arrived a week later, in the run phase.

#### Step 4: Look at two Mondays in detail

1. Run:

   ```bash
   python unit12/drift_watch.py week --date 2026-09-28
   ```

   ```text
   Drift watch for 2026-09-28 (hypercare), model m20260830, 139 deliveries created last week.

     Weight unit is KG                    139 of 139 not KG          FAIL
     Input PSI route                      0.01                       ok
     Input PSI weight                     1.28                       ALARM
     Input PSI lead                       0.02                       ok
     Input PSI gi_friday                  0.01                       ok
     Score PSI                            0.42                       ALARM
     Observed vs predicted late           18% vs 20% (277 known)     ok
     Recall vs test                       0.42 vs 0.37               ok
     Route RK0001 observed vs predicted   11% vs 18% (124 known)     ok
     Route RK0002 observed vs predicted   28% vs 24% (64 known)      ok
     Route RK0003 observed vs predicted   20% vs 20% (89 known)      ok
     Flags per delivery                   25% vs 27%                 info

   INCIDENT: Data feed broken: fix the feed, rescore open deliveries. Don't retrain on bad data.
   Saved unit12/hypercare/week_20260928.md
   ```

2. Run:

   ```bash
   python unit12/drift_watch.py week --date 2026-11-09
   ```

   ```text
   Drift watch for 2026-11-09 (run), model m20260830, 179 deliveries created last week.

     Weight unit is KG                    0 of 179 not KG            ok
     Input PSI route                      0.34 (CAL-02)              ALARM
     Input PSI weight                     0.01                       ok
     Input PSI lead                       0.01                       ok
     Input PSI gi_friday                  0.01                       ok
     Score PSI                            0.07                       ok
     Observed vs predicted late           26% vs 21% (342 known)     ok
     Recall vs test                       0.42 vs 0.37               ok
     Route RK0001 observed vs predicted   18% vs 20% (110 known)     ok
     Route RK0002 observed vs predicted   23% vs 23% (161 known)     ok
     Route RK0003 observed vs predicted   44% vs 19% (71 known)      ALARM
     Flags per delivery                   27% vs 27%                 info

   RETRAIN: Inputs look normal but outcomes moved: the world changed (concept drift). Retrain, backtest, second-person approval.
   Saved unit12/hypercare/week_20261109.md
   ```

3. Compare them. On 28 September everything about the inputs screams and the outcomes are calm. On 9 November the only unexplained alarm is an outcome on one route, while the overall gap (26% against 21%) is still under its 8-point alarm. Segment checks catch drift that totals hide.

> **Note** These results come from synthetic data generated by the script. They show the method, not results from a real SAP system.

#### Step 5: Switch the calendar off

1. Run:

   ```bash
   python unit12/drift_watch.py --no-calendar watch
   ```

2. The weeks with the route change now say `INVESTIGATE` instead of `WATCH` (an excerpt):

   ```text
   2026-10-19  hypercare    185  PSI route                                    INVESTIGATE
   2026-11-02  run          173  PSI route                                    INVESTIGATE
   2026-11-09  run          179  PSI route, Route RK0003 gap                  INVESTIGATE
   ```

   Without the calendar, the planned change and the real drift look like one muddle, and the 9 November verdict can no longer say "retrain". The calendar is cheap, and it is what lets the check name the cause.

3. Run `python unit12/drift_watch.py watch` once more, so `watch_log.csv` again holds the run with the calendar.

#### Step 6: Retrain, with two training windows

1. Retrain as of 9 November on as many recent deliveries as the original training set had:

   ```bash
   python unit12/drift_watch.py retrain --as-of 2026-11-09
   ```

   ```text
   Retrained m20261109 on the 1798 most recent deliveries with a known outcome before 2026-11-09 (rows sent in LB left out).
     old m20260830  on 365 deliveries due 2026-11-09 to 2026-11-21: recall 0.30, predicted 21% vs observed 31%
     new m20261109  on 365 deliveries due 2026-11-09 to 2026-11-21: recall 0.42, predicted 22% vs observed 31%
     old model's average score on route RK0003: 0.19 (observed late 51%)
     new model's average score on route RK0003: 0.24 (observed late 51%)
   Next: backtest, then a second person promotes it. Keep the old model ready for rollback.
   ```

2. Now only the last 28 days:

   ```bash
   python unit12/drift_watch.py retrain --as-of 2026-11-09 --days 28
   ```

   ```text
   Retrained m20261109 on 614 deliveries created in the 28 days before 2026-11-09 (rows sent in LB left out).
     old m20260830  on 365 deliveries due 2026-11-09 to 2026-11-21: recall 0.30, predicted 21% vs observed 31%
     new m20261109  on 365 deliveries due 2026-11-09 to 2026-11-21: recall 0.54, predicted 26% vs observed 31%
     old model's average score on route RK0003: 0.19 (observed late 51%)
     new model's average score on route RK0003: 0.34 (observed late 51%)
   Next: backtest, then a second person promotes it. Keep the old model ready for rollback.
   ```

3. Read the trade-off. With the long window, two weeks of the slow route are outvoted by three months of the old world: the route's average score moves only from 0.19 to 0.24. The 28-day window moves it to 0.34 and recall from 0.30 to 0.54, on a third of the rows. Neither catches up fully yet. Until it does, the process owner can add a plain business rule ("flag every `RK0003` delivery") next to the model, and remove it when a retrained model is promoted.

4. Notice the phrase "rows sent in LB left out". The defect rows are quarantined, not fed into training.

> **Note** These numbers come from synthetic data. They show how to compare retraining windows, not what a real retraining would gain.

#### Step 7: Save your work in Git

```bash
git add unit12/drift_watch.py unit12/hypercare
git commit -m "Unit 12: weekly drift watch with change calendar and retraining windows"
```

Check with `git status` first: you must not see `.env`.

#### How the code works

| Part of the script | What it does |
| --- | --- |
| `make_deliveries()` | Generates deliveries for 1 June to 22 November 2026 with seed 42, including the three built-in changes: pounds from 21 to 29 September, Hallam's volume from 5 October, the slow `RK0003` carrier from 26 October |
| `features()` | What the model reads at creation: route, weight band, lead time band, Friday goods issue. Like a careless pipeline, it ignores the unit field |
| `Model` | A naive Bayes classifier with add-one smoothing, the stand-in for the Unit 17 model |
| `psi()` | The population stability index over category shares, with 0.0001 for empty bins |
| `check_week()` | The Monday checks: unit, input PSI per feature, score PSI, then outcome checks on deliveries whose planned goods issue fell in the last 14 days, overall and per route |
| verdict logic in `check_week()` | Data failure is an INCIDENT; outcome alarm with calm inputs is RETRAIN; unexplained input alarm is INVESTIGATE; explained or small moves are WATCH |
| `in_calendar()` | Finds a calendar entry for the feature that overlaps the week |
| `setup()` | Trains `m20260830` on June to August, measures test recall on August, picks the reference slice; with `--as-of` trains a new model on recent clean rows |
| `cmd_watch()`, `cmd_week()`, `cmd_retrain()` | The three commands; `watch` writes `watch_log.csv`, `week` writes a markdown report |

#### 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 | Windows: repeat Unit 2, Step 1, then open a new terminal. macOS/Linux: use `python3` until `.venv` is active |
| `can't open file ... drift_watch.py` | You are not in the course folder, or the file has another name | Run `cd` to `orchestrate-course`, check the file is `unit12/drift_watch.py` |
| `ModuleNotFoundError` | A line was cut while pasting; the script needs no libraries | Paste the whole script again |
| `is not a Monday. The watch runs on Mondays.` | `--date` named another weekday | Use a Monday such as `2026-11-09` |
| `the following arguments are required: --as-of` | `retrain` needs a date | Add `--as-of 2026-11-09` |
| Your numbers differ from the page | The script was changed, or the calendar file was edited | Paste the script again, delete `unit12/hypercare/change_calendar.json`, and rerun |
| A network or proxy error | Not possible here: the lab makes no network calls | Check you ran this script and not another one |

### The SAP way

As of November 2026, the SAP pages read for this topic cover the frame and the technical monitoring; the model checks are yours to build.

- **Hypercare in SAP Activate.** The methodology structure lesson puts hypercare in the Deploy phase after go-live, with the duration set in the contract or a transition-to-operations plan, and puts incident management, change management, monitoring and upgrades in the Run phase, under the Operations and Support workstream ([SAP Learning](https://learning.sap.com/courses/discovering-sap-activate-implementation-tools-and-methodology/describing-the-methodology-structure)). Write the AI system's exit criteria, playbooks and owners into that transition plan.
- **SAP Cloud ALM for Operations.** SAP's lesson on central observability tools lists Business Process Monitoring, Integration & Exception Monitoring, Real User and Synthetic User Monitoring, Job & Automation Monitoring, Configuration & Security Analysis and Health Monitoring, for customers with a cloud subscription or Enterprise Support ([SAP Learning](https://learning.sap.com/courses/operating-sap-business-ai-platform/explaining-central-observability-tools_c3e8a8ad-76e5-43ec-a7b9-0705532a44fd)).
  - **Health Monitoring** takes technical metrics and events from customer applications on SAP BTP, rates them, and can react with an alert, an email, an operation flow, a ServiceNow ticket or a chat notification ([SAP Learning](https://learning.sap.com/courses/operating-with-sap-cloud-alm/health-monitoring)). That is where an AI app's availability and error rate belong, and a natural target for your drift watch's INCIDENT verdicts.
  - **Business Process Monitoring** measures throughput, lead time, backlog and exception KPIs for end-to-end processes such as Lead to Cash, and needs data collection activated per component ([SAP Learning](https://learning.sap.com/courses/operating-with-sap-cloud-alm/business-process-monitoring), [SAP Support](https://support.sap.com/en/alm/sap-cloud-alm/operations/expert-portal/business-process-monitoring.html)). For the late-delivery predictor, it shows whether deliveries leave on time, the business result the model is meant to move.
  - **Integration & Exception Monitoring** is where a broken extraction or interface usually shows first; [AI-accelerated delivery on SAP programs](https://erpfde.com/topics/ai-accelerated-sap-delivery/) describes it for hypercare triage.
- **What the pages don't cover.** None of the pages read describes data drift, concept drift or accuracy monitoring for a model a customer built, or a model-retraining workflow. For models on SAP AI Core, the platform's own operations (versions, limits, keys) are in [Running AI on SAP BTP in production](https://erpfde.com/topics/running-ai-on-btp/); for SAP's embedded and pretrained models, ask SAP how their quality is monitored and what you are told when it changes.

**Licensing notes.** The SAP Learning lesson ties SAP Cloud ALM for Operations to a cloud subscription or Enterprise Support; confirm your entitlement and the data collection setup for each component. Drift checks like the lab's cost compute time only; the cost that matters is the model owner's hours each week.

### Build vs. SAP

| Need | Use | Why |
| --- | --- | --- |
| Is the AI app up, fast, error-free? | Cloud ALM Health Monitoring | Application metrics and alerts with tickets and chat notifications |
| Did the business process get better? | Cloud ALM Business Process Monitoring | Throughput, lead time, backlog and exception KPIs per process |
| Is the feed intact? | Your own data checks, run daily | Unit, blanks and ranges are specific to your model's fields |
| Are inputs still like training? | Your own PSI checks, or an open library such as Evidently | Needs the training reference, which only your team has |
| Is the model still right? | Your own outcome checks per segment | Needs the predictions and the outcomes joined |
| Agent incidents | Your kill switch, gateway budgets and approval logs | Behavior and approvals live in your agent's logs |

### Architecture view

**Where it sits.** The drift watch runs next to the model, reads the same extraction as the scoring job, and writes verdicts where the run team already looks.

```mermaid
flowchart LR
  S4[S/4HANA CP10<br/>outbound deliveries] -->|extraction| X[Feature store or files]
  X --> SC[Scoring job]
  SC --> WL[Planner worklist]
  X --> DW[Drift watch<br/>daily data, weekly drift]
  SC -->|scores| DW
  S4 -->|goods issue outcomes| DW
  CAL[Change calendar] --> DW
  DW -->|INCIDENT| ALM[Cloud ALM<br/>Health Monitoring alert]
  DW -->|RETRAIN| MO[Model owner:<br/>train, backtest, approve]
  ALM --> ON[On-call rota]
```

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

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Time to detect a feed defect | Next business morning | A week of bad scores, as at Calder |
| Time to detect concept drift | Label delay plus one week | Planners act on stale risk for months |
| Kill switch response | AI off within 15 minutes, manual path working | Wrong drafts keep flowing while people debate |
| Reproducibility | Every verdict traceable to model version, reference and calendar | Nobody can explain last month's retraining |
| Cost of the watch | A few hours of model owner time per week | The watch is dropped after hypercare |

**Integration and identity.** The watch reads deliveries and outcomes through the same extraction as the model, with a technical user that has read access only. It holds no SAP write authorization. Alerts go to Cloud ALM or the run team's ticket tool. Promotion of a new model is a separate step by a named second person, as in the [late-delivery project](https://erpfde.com/topics/project-late-delivery-predictor/).

**The decision to record** (short ADR form, as in [Writing a solution design doc](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- *Context:* the late-delivery predictor is live at Rockford; hypercare ends on 16 October 2026; the project team leaves after it.
- *Options:* A, rely on Cloud ALM's application and process monitoring. B, A plus a daily data check and a weekly drift watch with a change calendar, verdicts sent to Cloud ALM, owned by a named model owner. C, retrain monthly and monitor nothing.
- *Decision:* B. Only it separates a broken feed from drift and names who acts.
- *Consequences:* a model owner role after hypercare; the business keeps the change calendar; extraction changes are tested against the data checks.

**What a design review will ask:**

1. How soon would we notice a changed field, and who is paged?
2. What is the label delay, and what do we watch until outcomes arrive?
3. Who owns the model after hypercare, and is that written into the transition plan?
4. How are defect rows kept out of training?
5. What happens to the process when the AI is switched off?

### Production concerns

**Security and authorizations.** The watch reads delivery data and outcomes; give it a read-only technical user and keep its reports free of customer details beyond what the run team needs. For agents, the kill switch and the rollback of a model route are privileged actions: restrict them to the process owner and the run team, and log who used them, as in [Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/).

**Evaluation.** Every retrained model passes the same gates as the first: the backtest, the regression cases from [UAT and sign-off for AI in SAP programs](https://erpfde.com/topics/uat-and-sign-off-for-ai-in-sap-programs/), and a second person's approval. Keep the incident cases (the pound-weight rows, the injection text) in the test set.

**Cost.** Most cost is people: a daily glance in hypercare, a weekly review after. Put it in the business case, or the watch quietly stops.

**Operations.** Version the reference, the thresholds and the calendar with the model. Review thresholds after the first month: thresholds set before go-live are guesses.

**Clean core.** The watch lives outside S/4HANA and reads released extraction interfaces; it needs no modification. Extraction changes go through transport and testing like any other change, now including the model's data checks.

### Pitfalls

- **No end criteria.** Hypercare ends on a date, with open incidents and no owner.
- **Retraining on a broken feed.** The defect becomes part of the model.
- **Only input checks.** Concept drift leaves inputs alone.
- **Only totals.** One route's drift hides inside the overall rate.
- **Alarms without causes.** Teams retrain or ignore by habit; the change calendar is missing.
- **An untested kill switch.** The manual process no longer works when it is needed.
- **The project team owns the model forever.** Drift arrives after they leave.
- **Thresholds never revisited.** Too many alarms and people stop reading them.

### Exercise

Add a daily data check, so the next feed defect is caught the morning after instead of a week later. Your runbook note goes into your capstone's operations evidence.

**Before you start:** finish Build it yourself above.

1. Open `unit12/drift_watch.py`. Above the line `def main():`, add this function:

   ```python
   def cmd_daily(args, calendar):
       rows = make_deliveries()
       day = date.fromisoformat(args.start)
       while day <= date.fromisoformat(args.end):
           today = [r for r in rows if r["created"] == day]
           if today:
               bad = sum(1 for r in today if r["unit"] != "KG")
               print(f"{day}  {len(today):>3} deliveries  {bad:>3} not KG  {'FAIL' if bad else 'ok'}")
           day += timedelta(days=1)
   ```

2. In `main()`, just above `args = parser.parse_args()`, add the command and its options:

   ```python
       dly = sub.add_parser("daily", help="data checks for each day")
       dly.add_argument("--start", default="2026-09-14")
       dly.add_argument("--end", default="2026-10-02")
   ```

3. In the last line of `main()`, add `"daily": cmd_daily` to the dictionary of commands, so it reads `{"watch": cmd_watch, "week": cmd_week, "retrain": cmd_retrain, "daily": cmd_daily}`.
4. Save and run:

   ```bash
   python unit12/drift_watch.py daily
   ```

   ```text
   2026-09-18   31 deliveries    0 not KG  ok
   2026-09-21   24 deliveries   24 not KG  FAIL
   2026-09-22   24 deliveries   24 not KG  FAIL
   ...
   2026-09-29   30 deliveries   30 not KG  FAIL
   2026-09-30   27 deliveries    0 not KG  ok
   ```

5. Add a second check of your choice to `cmd_daily`, for example the share of deliveries above 5,000 kg (no pump delivery in the sample weighs that much in kilograms). Print it on the same line.
6. Create `unit12/hypercare/RUNBOOK.md` with three sentences: on which morning the daily check would have caught the pound weights (the first `FAIL` day plus one), how many days earlier that is than the 28 September weekly verdict, and who gets the alert in hypercare and who after it.
7. Commit: `git add unit12` and `git commit -m "Unit 12: daily data check and runbook note"`.

**Done when** `daily` prints `FAIL` for 2026-09-21 to 2026-09-29 and `ok` on the other days, your second check appears on each line, and `RUNBOOK.md` is committed.

### Check yourself

1. Why does the drift watch check the feed and the inputs at all, if only outcomes prove the model is wrong?
   - A. Input checks are more accurate than outcome checks on small windows
   - B. Outcomes arrive late, so feed and input checks warn first
   - C. Outcome checks need SAP Cloud ALM, which only the run team can use
   - D. PSI on inputs replaces the need to join predictions with outcomes

   Answer: B. Label delay means the newest predictions can't be judged yet. In the lab the pound weights showed in the inputs on 28 September while the known outcomes still looked fine.

2. In the lab, 9 November shows the overall late share 26% against 21% predicted, and route RK0003 at 44% against 19%. Why is the verdict RETRAIN?
   - A. The overall gap is above its 8-point alarm, so the whole model is off
   - B. The route PSI alarm has no calendar entry to explain it that week
   - C. An outcome check fails while unexplained inputs stay calm
   - D. Recall fell more than 0.15 below the test recall on that Monday

   Answer: C. The verdict logic calls it concept drift when outcomes move and inputs don't. The route PSI alarm is explained by CAL-02, and the overall gap is under its alarm; the per-route check is what fails.

3. What does the population stability index compare?
   - A. The model's predictions with the outcomes that arrived later
   - B. The accuracy of the old model with that of the retrained one
   - C. The number of deliveries this week with the weekly average
   - D. A feature's spread over bins now and in the reference

   Answer: D. PSI sums, over bins, the difference in shares times the log of their ratio. It measures how far a distribution moved, and says nothing directly about correctness.

4. Why does `retrain` leave out the rows sent in LB?
   - A. They record a feed defect that training would teach the model
   - B. They are too few to change the model, so they only slow training
   - C. The naive Bayes model can't read weights above 5,000 kilograms
   - D. They were created during hypercare, which is never used for training

   Answer: A. The pound weights are wrong data, not a new reality. Quarantining defect rows keeps the fix of the feed from being undone by the model.

5. Retraining on the 1,798 most recent rows moved route RK0003's average score from 0.19 to 0.24; the last 28 days moved it to 0.34. What is the trade-off?
   - A. The long window is always better because it has more rows
   - B. The short window is always better because drift only gets worse
   - C. Old rows outvote the new world, while a short window is noisier
   - D. Both windows fail, so retraining can't help with concept drift

   Answer: C. Two weeks of the slow route are a small share of three months of data. A recent window adapts faster on fewer rows, which makes its estimates less stable; a business rule can bridge until a model catches up.

6. Calder's Rockford DC will move half its deliveries to a new shipping point next month. What should happen before the switch?
   - A. Nothing until the weekly watch raises an alarm on the new code
   - B. A calendar entry, and retraining once outcomes exist
   - C. Retrain now on last year's data so the model is fresh for the move
   - D. Switch the model off for the month the shipping point changes

   Answer: B. A planned change goes on the calendar so the input alarm reads as expected, and retraining waits until there are outcomes under the new setup. Retraining now would use data that knows nothing of the new point.

7. The order-exception agent's drafts start following an instruction hidden in a customer note. What are the first 15 minutes for?
   - A. Retraining the agent on the note so it learns to ignore it
   - B. Raising the gateway's token budget to keep the agent responsive
   - C. Switching off its write tools while read-only work goes on
   - D. Rolling the model route back to the version used at go-live

   Answer: C. A prompt injection that gets through is an incident; the playbook stops writes first and quarantines the input afterward. A model rollback addresses a model change, not an injected instruction.

8. Which part of the drift watch would SAP Cloud ALM's Health Monitoring most naturally carry?
   - A. The per-route comparison of predicted and observed late shares
   - B. The change calendar that explains planned business changes
   - C. The PSI calculation for each feature against the reference
   - D. The alert and ticket when a verdict says INCIDENT

   Answer: D. Health Monitoring takes metrics and events from applications on SAP BTP and reacts with alerts, tickets or chat notifications. The checks themselves need the training reference and outcomes, which the team builds.

## Sources

- [Describing the Methodology Structure (SAP Learning, Discovering SAP Activate Implementation Tools and Methodology)](https://learning.sap.com/courses/discovering-sap-activate-implementation-tools-and-methodology/describing-the-methodology-structure): Opened 2026-11-23. Phases Discover, Prepare, Explore, Realize, Deploy, Run; sustainment and hypercare are performed in the Deploy phase once the system goes live, with the team on hand for a period usually set in the contract or a transition-to-operations plan; Run covers incident and change management, system and application monitoring and upgrade management; Operations and Support workstream
- [Fostering Sustainable User Adoption (SAP Learning, Acting as Professional Change Manager in SAP Cloud Projects)](https://learning.sap.com/courses/acting-as-professional-change-manager-in-sap-cloud-projects/fostering-sustainable-user-adoption): Opened 2026-11-23. Hypercare ending with operations handed to the customer's IT; a systematic handover from the project team to IT and business departments; Run phase focus on ongoing operations, continuous improvement, new scope and onboarding new users
- [Explaining Central Observability Tools (SAP Learning, Operating SAP Business AI Platform)](https://learning.sap.com/courses/operating-sap-business-ai-platform/explaining-central-observability-tools_c3e8a8ad-76e5-43ec-a7b9-0705532a44fd): Opened 2026-11-23. Names SAP Cloud ALM for Operations as the central tool, for customers with a cloud subscription or Enterprise Support; use cases Business Process Monitoring, Integration & Exception Monitoring, Real User and Synthetic User Monitoring, Job & Automation Monitoring, Configuration & Security Analysis, Health Monitoring; the part read verbatim names no model-drift monitoring
- [Health Monitoring (SAP Learning, Operating with SAP Cloud ALM)](https://learning.sap.com/courses/operating-with-sap-cloud-alm/health-monitoring): Opened 2026-11-23. Monitoring, analytics, alerting and resolution for SAP SaaS and PaaS services and customer applications on SAP BTP (technical metrics and events); alerts from metric ratings or events; reactions include alert, email, operation flow, ServiceNow ticket and chat notification
- [Business Process Monitoring (SAP Learning, Operating with SAP Cloud ALM)](https://learning.sap.com/courses/operating-with-sap-cloud-alm/business-process-monitoring): Opened 2026-11-23. End-to-end process health from predefined KPIs in four categories (throughput, lead time, backlog, exception); critical and warning alerts per KPI; processes Recruit to Retire, Lead to Cash, Source to Pay, Design to Operate; data collection must be activated per component
- [Business Process Monitoring (SAP Support, SAP Cloud ALM expert portal)](https://support.sap.com/en/alm/sap-cloud-alm/operations/expert-portal/business-process-monitoring.html): Opened 2026-11-23. Supports the detect-to-correct lifecycle along end-to-end processes of the Intelligent Suite, based on predefined KPIs; no mention of AI or machine learning
- [Customize Data Drift (Evidently documentation)](https://docs.evidentlyai.com/metrics/customize_data_drift): Opened 2026-11-23. Method chosen by column type and volume; PSI for numerical and categorical columns with drift when the value is at or above the threshold, default 0.1; KS and chi-square p-value 0.05; Jensen-Shannon and Wasserstein 0.1; dataset drift when the share of drifted columns exceeds drift_share, default 0.5
