A pharmaceutical plant can't ship a batch of medicine because the machines finished it. A person in quality must review the whole record of how it was made and tested, and sign that it may go to patients. That step is batch release. Anything that went differently from the approved process is a deviation, and each one must be investigated and classified before the batch can be released. Every pack also carries a unique serial number that trading partners and regulators can check (serialization).
The rules around this work are called GxP: good manufacturing practice and its relatives. They demand validated systems, complete audit trails and named people taking named decisions.
AI helps by gathering the evidence, proposing how serious a deviation looks, and spotting broken serial data before it reaches a partner. It doesn't release a batch or close a deviation. And under the EU's draft rules, an AI model used in a critical step must be frozen, tested on data it has never seen and put under change control like any other validated system. Changing the model is a documented change, not a quiet update.
A finished batch waiting for release is cash on the shelf with an expiry date. Release delays are rarely about the product. They come from paperwork: an open deviation, a missing test result, a record nobody has reviewed. Quality teams spend their days assembling evidence from several systems before they can decide.
Take a fictional tablet maker, Tarnwood Pharma. A batch of its product TW-100 is packed and in quarantine. Two deviations are open against it: a temperature alarm during granulation and a missing second signature on a filter test record. The quality person has to read both, judge whether either affects the product, check the lab results and confirm the serial data matches the packs. An assistant that has already pulled the facts together and proposed "major" and "undecided" saves hours. An assistant that quietly decides "minor" on the wrong one could release a batch that should have been held.
Compare our running company. The fictional Calder Pumpworks inspects seal kits at goods receipt and makes a usage decision on each lot (see quality, projects and service). Pharma adds three things on top: the law names who must approve, every electronic signature has fixed content, and the system that helps must itself be validated.
The risks are uneven. A slow release costs money and shelf life, which is recoverable. A wrongly released batch can harm patients and lead to a recall. A model changed without change control turns a validated process into an unvalidated one, which an inspector will find.
As of November 2026, SAP covers this area with dedicated life sciences products and a few AI features on top. Each status below is what SAP's page said when opened for this topic.
Batch release.SAP Batch Release Hub for Life Sciences is a public cloud service that integrates with SAP S/4HANA (sap.com). Its feature scope description (dated 28 November 2025) describes worklists of batches to release, release checks that read the status from source systems such as a LIMS, QMS or MES, a check of each batch against the markets it is authorized for, and a release decision set with an e-signature (help.sap.com).
AI in batch release. The same document describes an AI-assisted custom release check that proposes an answer for a checklist item. Customers must enable the AI feature and buy AI Units (help.sap.com).
Serialization.SAP Advanced Track and Trace for Pharmaceuticals manages serial numbers, a serialization repository and country reporting; its pricing names SAP S/4HANA Cloud Private Edition (sap.com). SAP Traceability Hub is a cloud service for exchanging that data with partners and regulators, with preconfigured support for the EU's FMD and the US DSCSA. Its page describes AI-powered error insights that explain failed messages and suggest fixes (sap.com).
Deviations. The feature scope description names a QMS as a source system for batch release, so deviation records often live outside SAP and arrive as a release check status (help.sap.com). The pages opened for this topic name no SAP AI feature that classifies deviations.
Neither product page shows a GA, beta or early adopter label for its AI feature. Check the current status in SAP's Business AI catalog before you plan around one.
#Where AI fits in the release process, step by step
"A high accuracy lets AI release routine batches." The quality unit holds the authority to approve or reject. A system rule may release automatically only where the company has validated and configured it, and that is a deterministic rule, not a model's guess.
"We can use a chatbot for deviation classification." The EU's draft Annex 22 says generative AI and large language models should not be used in critical GMP applications. Drafting a summary for a person is a different, non-critical use.
"Retraining is maintenance." Under change control, a retrained model is a new version that must be tested and approved before use.
"Serialization is a packaging-line problem." It is also a release check: a duplicate serial or a wrong expiry on the serial data can block shipment to a market.
"Undecided means the model failed." Saying "I'm not sure" is a designed outcome. It sends the case to a person, which is what you want for the hard ones.
Pick one answer for each question. The explanation appears after you choose.
1Why does a batch of medicine sit in quarantine after it is packed?
Answer: D. Batch release is a documented decision by an authorized quality person after reviewing how the batch was made and tested. Open deviations or missing results keep the batch in quarantine.
2A vendor offers an AI that releases routine batches when it is 99% confident. What is the right response?
Answer: A. The quality unit holds the authority to approve or reject. Automatic release exists only as a validated, configured rule, not as a model's judgment, however confident.
3Under the EU's draft Annex 22, which kind of model may be used in a critical GMP step?
Answer: C. The draft limits critical use to static, deterministic models. Models that adapt in use, probabilistic models, and generative AI or large language models are named as not for critical GMP applications.
4Your team wants to retrain the deviation model on last quarter's data. What does that mean in a GxP plant?
Answer: B. A retrained model is a new version of a validated system. Change control requires testing it against agreed criteria and approving it before it replaces the old one.
5Which SAP product page describes AI that explains failed serialization messages to partners?
Answer: D. The SAP Traceability Hub page describes AI-powered error insights for failed track-and-trace messages. Batch Release Hub's AI feature proposes answers for release checklist items, and needs AI Units.
6The assistant marks a deviation "undecided". How should a quality leader read that?
Answer: C. Below its confidence threshold the model says it can't decide, and quality classifies alone. The share of undecided cases is one of the acceptance criteria to agree before testing.
In a GxP plant, the AI model is just another piece of validated equipment. A balance in the lab is calibrated, locked, used only for its stated purpose and re-qualified when anything changes. A deviation-triage model gets the same treatment: a written intended use, acceptance criteria set before the test, a test on data it never saw, a fingerprint of the approved version, and a change request for any new one.
Around that sits the same fence as in every regulated industry. The model writes proposals with their reasons and confidence. The quality unit classifies, closes and signs. A release gate checks the facts the law cares about, and refuses anything else.
A batch moves from production into quarantine, and release pulls evidence from several systems.
flowchart LR
P[Production<br/>MES, S/4HANA] --> Q[Batch in<br/>quarantine]
L[Lab results<br/>LIMS] --> R
D[Deviations<br/>QMS] --> T{{Triage<br/>proposal}}
T --> C[QA classifies<br/>and closes]
C --> R[Release checks]
S[Serial data<br/>track and trace] --> R
Q --> R
R --> G[Authorized person<br/>e-signs release]
G --> M[Ship to markets]
The double-bordered box is where the model works. Four mechanics matter.
The release rules come from law and are deterministic. In the US, production and control records must be reviewed and approved by the quality control unit before a batch is released, and every unexplained discrepancy must be investigated, extended to other batches where relevant, and written up with its conclusions (21 CFR 211.192). The quality control unit has the responsibility and authority to approve or reject drug products (21 CFR 211.22). A release gate checks these as rules, not predictions.
Electronic signatures have fixed content. A signed electronic record must show the printed name of the signer, the date and time, and the meaning of the signature, such as review or approval; and the signature must be linked to its record so it can't be copied to another (21 CFR 11.50 and 11.70). The same part asks for validation, secure time-stamped audit trails, authority checks and change control over system documentation (11.10). Those apply to the AI's records too.
The model is held to the draft EU Annex 22. The European Commission consulted from 7 July to 7 October 2025 on a new GMP Annex 22 for artificial intelligence, alongside revised Annex 11 and Chapter 4 (European Commission). When this topic was written, the only published text found was that consultation draft; check EudraLex Volume 4 for a final version. The draft (PDF) applies to models in critical applications with a direct impact on patient safety, product quality or data integrity, and asks for:
Draft section
What it asks
In the walkthrough
1 Scope
Static, deterministic models only in critical use; no generative AI or LLMs there
Naive Bayes, no sampling, frozen file
3.1, 3.3
Intended use approved by a process expert; if a person checks outputs, their duty is part of the intended use
Proposals only; QA classifies
4.2, 4.3
Acceptance criteria approved before testing, no lower than the process replaced
CRITERIA fixed in the code before any run
6
Test data kept independent of development
60 records held out from training
8
Record which features drove each decision
Top three words with direction
9
Log a confidence score; below a threshold, flag "undecided"
MIN_CONFIDENCE = 0.80
10.1, 10.2
Change control before deployment; detect unauthorized changes
Register with SHA-256 of the approved file
10.3, 10.4
Monitor performance and input drift
Exercise and production concerns
Serial data is a release check too. Each pack's serial must be unique and carry the batch's lot and expiry. In the US, the Drug Supply Chain Security Act's enhanced distribution security requirements apply to trading partners, and FDA has exempted only small business dispensers from some of them, until 27 November 2027 (FDA). Bad serial data that reaches a partner turns into a stopped shipment.
#Build it yourself: Tarnwood's triage model and release gate
You will build a script that does what a quality team at the fictional Tarnwood Pharma would need before using AI in release. It trains a small deviation-triage model, validates it against criteria fixed in advance, records its approval under a change number with a fingerprint, proposes classes for this week's deviations, and then runs a release gate that only an authorized person can pass.
Before you start: complete Set up your computer for this course. Unit 16 has no setup topic of its own; this script needs only Python's built-in modules.
flowchart LR
H[Synthetic history<br/>300 deviations, seed 42] --> TR[train v1<br/>240 records]
H --> VA[validate<br/>60 held out]
TR --> VA
VA --> AP{approve:<br/>QA + PASS +<br/>same hash?}
AP -->|yes| RG[(Model register)]
RG --> TG[triage: proposals]
TG --> CL[QA closes<br/>with rationale]
CL --> RL{release gate}
RL -->|all checks| OK[RELEASED<br/>name, time, meaning]
RL -->|any gap| NO[REFUSED]
In VS Code, create the file unit16/gxp_batch_release.py, paste the code below, and save.
"""Deviation triage under change control, and a batch release gate.
Unit 16, life sciences topic. Built-in modules only, seed 42.
Tarnwood Pharma is fictional; every record and number here is synthetic.
python unit16/gxp_batch_release.py train --version v1
python unit16/gxp_batch_release.py validate --version v1
python unit16/gxp_batch_release.py approve --version v1 --by QA-201 --change CC-0001
python unit16/gxp_batch_release.py triage
python unit16/gxp_batch_release.py close DEV-0912 --cls MAJOR --by QA-201 --rationale "..."
python unit16/gxp_batch_release.py release B-26-0417 --by QA-201 --meaning approval
"""
import argparse
import hashlib
import json
import math
import random
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
SEED = 42
CLASSES = ["MINOR", "MAJOR"]
FOLDER = Path(__file__).parent / "gxp"
# Words a deviation description draws from (course vocabulary, not a real taxonomy).
WORDS = {
"MINOR": ["label", "printer", "late", "entry", "logbook", "typo", "cleaning", "record",
"signature", "missing", "page", "date", "format", "corrected", "delay"],
"MAJOR": ["temperature", "excursion", "sterile", "filter", "integrity", "failed", "out",
"specification", "contamination", "particle", "mix", "wrong", "lot", "pressure", "alarm"],
"SHARED": ["batch", "line", "operator", "shift", "room", "step", "granulation", "tablet",
"blister", "found", "during", "check", "observed", "reported"],
}
# Acceptance criteria, approved by the process expert BEFORE any testing (course values).
# The manual process it supports finds about 90% of major deviations at first triage.
CRITERIA = {"major_recall_min": 0.90, "decided_accuracy_min": 0.90, "undecided_max": 0.30}
MIN_CONFIDENCE = 0.80 # below this the model answers UNDECIDED and QA classifies alone
# People who may classify deviations and release batches (course register, fictional IDs).
QA_STAFF = {"QA-201": "QA release manager 201", "QA-214": "QA specialist 214"}
RELEASERS = {"QA-201"}
AGENT_USER = "AGT_BATCH_ASSIST" # the assistant's own user: may propose, never classify or sign
# This week's open deviations (fictional) and the batches they belong to.
OPEN_DEVIATIONS = [
{"id": "DEV-0911", "batch": "B-26-0417", "text": "label printer late entry in logbook during shift"},
{"id": "DEV-0912", "batch": "B-26-0418", "text": "temperature excursion alarm in room during granulation step"},
{"id": "DEV-0913", "batch": "B-26-0418", "text": "operator observed signature missing on filter integrity record"},
{"id": "DEV-0914", "batch": "B-26-0419", "text": "filter integrity check reported during line step"},
]
BATCHES = {
"B-26-0417": {"product": "TW-100 tablets", "packed": 1200, "expiry": "2028-10-31",
"lab": {"assay": "PASS", "dissolution": "PASS", "micro": "PASS"}},
"B-26-0418": {"product": "TW-100 tablets", "packed": 1200, "expiry": "2028-10-31",
"lab": {"assay": "PASS", "dissolution": "PASS", "micro": "PASS"}},
"B-26-0419": {"product": "TW-100 tablets", "packed": 1200, "expiry": "2028-11-30",
"lab": {"assay": "PASS", "dissolution": "PASS", "micro": "PENDING"}},
}
def make_history(n=300):
"""Synthetic closed deviations, each classified by QA. Seed 42 fixes them."""
rng = random.Random(SEED)
rows = []
for i in range(n):
label = "MAJOR" if rng.random() < 0.3 else "MINOR"
other = "MINOR" if label == "MAJOR" else "MAJOR"
words = rng.sample(WORDS[label], 3) + rng.sample(WORDS["SHARED"], 4)
if rng.random() < 0.5: # real descriptions are noisy
words += rng.sample(WORDS[other], rng.choice([1, 2]))
if rng.random() < 0.05: # and a few past classifications were inconsistent
label = other
rng.shuffle(words)
rows.append({"id": f"H-{i + 1:04d}", "text": " ".join(words), "qa_class": label})
return rows
def split(rows):
"""First 240 for development, last 60 held out for validation only."""
return rows[:240], rows[240:]
def tokens(text):
return [w for w in text.lower().split() if w.isalpha()]
def fit(rows):
prior = Counter(r["qa_class"] for r in rows)
counts = {c: Counter() for c in CLASSES}
for r in rows:
counts[r["qa_class"]].update(tokens(r["text"]))
vocab = sorted(set().union(*counts.values()))
return {"prior": dict(prior), "counts": {c: dict(counts[c]) for c in CLASSES}, "vocab": vocab}
def predict(model, text):
"""Naive Bayes with add-one smoothing. Same input, same output: no sampling."""
vocab = set(model["vocab"])
total = sum(model["prior"].values())
scores, contrib = {}, {}
for c in CLASSES:
n = sum(model["counts"][c].values())
s = math.log(model["prior"][c] / total)
for w in tokens(text):
if w in vocab:
s += math.log((model["counts"][c].get(w, 0) + 1) / (n + len(vocab)))
scores[c] = s
top = max(scores.values())
probs = {c: math.exp(s - top) for c, s in scores.items()}
z = sum(probs.values())
probs = {c: p / z for c, p in probs.items()}
# Which words pushed toward MAJOR (positive) or MINOR (negative): the explanation.
nmaj = sum(model["counts"]["MAJOR"].values())
nmin = sum(model["counts"]["MINOR"].values())
for w in set(tokens(text)) & vocab:
contrib[w] = (math.log((model["counts"]["MAJOR"].get(w, 0) + 1) / (nmaj + len(vocab)))
- math.log((model["counts"]["MINOR"].get(w, 0) + 1) / (nmin + len(vocab))))
best = max(probs, key=probs.get)
answer = best if probs[best] >= model["min_confidence"] else "UNDECIDED"
why = sorted(contrib.items(), key=lambda kv: (-abs(kv[1]), kv[0]))[:3]
return answer, probs[best], why
def file_hash(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def load_json(path, default):
return json.loads(path.read_text()) if path.exists() else default
def now():
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
def cmd_train(version, min_conf):
FOLDER.mkdir(exist_ok=True)
path = FOLDER / f"model_{version}.json"
if path.exists():
raise SystemExit(f"REFUSED: {path.name} exists. A changed model gets a new version.")
dev, test = split(make_history())
model = fit(dev)
model.update(version=version, min_confidence=min_conf, trained_on=f"{dev[0]['id']}..{dev[-1]['id']}")
path.write_text(json.dumps(model, indent=1, sort_keys=True))
print(f"Trained {version} on {len(dev)} development records (H-0001..H-0240); "
f"{len(test)} held out, never seen")
print(f"Confidence threshold {min_conf:.2f}; sha256 {file_hash(path)[:12]}")
def cmd_validate(version):
path = FOLDER / f"model_{version}.json"
if not path.exists():
raise SystemExit(f"REFUSED: no {path.name}. Train it first.")
model = json.loads(path.read_text())
_, test = split(make_history())
cm = Counter()
for r in test:
answer, _, _ = predict(model, r["text"])
cm[(r["qa_class"], answer)] += 1
majors = sum(v for (t, _), v in cm.items() if t == "MAJOR")
decided = [(t, a) for (t, a), v in cm.items() for _ in range(v) if a != "UNDECIDED"]
recall = cm[("MAJOR", "MAJOR")] / majors
acc = sum(t == a for t, a in decided) / len(decided)
und = 1 - len(decided) / len(test)
# A MAJOR sent to UNDECIDED reaches QA anyway, so only MAJOR->MINOR counts as missed.
recall_safe = 1 - cm[("MAJOR", "MINOR")] / majors
checks = [
("MAJOR not called MINOR", recall_safe, ">=", CRITERIA["major_recall_min"]),
("accuracy on decided", acc, ">=", CRITERIA["decided_accuracy_min"]),
("undecided share", und, "<=", CRITERIA["undecided_max"]),
]
print(f"Validation of {version} on {len(test)} held-out records (H-0241..H-0300)")
print(" QA class -> model: " + " ".join(f"{t}->{a} {v}" for (t, a), v in sorted(cm.items())))
print(f" MAJOR found as MAJOR: {cm[('MAJOR', 'MAJOR')]}/{majors} ({recall:.0%})")
ok = True
for name, val, op, lim in checks:
good = val >= lim if op == ">=" else val <= lim
ok &= good
print(f" {'PASS' if good else 'FAIL'} {name:<24} {val:.2f} (needs {op} {lim:.2f})")
report = {"version": version, "model_sha256": file_hash(path), "result": "PASS" if ok else "FAIL",
"matrix": {f"{t}->{a}": v for (t, a), v in cm.items()}, "criteria": CRITERIA, "run": now()}
(FOLDER / f"validation_{version}.json").write_text(json.dumps(report, indent=1))
print(f"Result: {report['result']} (report validation_{version}.json)")
def cmd_approve(version, by, change):
if by not in QA_STAFF:
raise SystemExit(f"REFUSED: {by} is not QA")
path = FOLDER / f"model_{version}.json"
report = load_json(FOLDER / f"validation_{version}.json", None)
if report is None or report["result"] != "PASS":
raise SystemExit(f"REFUSED: {version} has no passed validation")
if report["model_sha256"] != file_hash(path):
raise SystemExit(f"REFUSED: model_{version}.json changed after validation; validate again")
reg = load_json(FOLDER / "model_register.json", {"approved": []})
for entry in reg["approved"]:
entry["active"] = False
reg["approved"].append({"version": version, "sha256": report["model_sha256"], "change": change,
"approved_by": by, "approved_at": now(), "active": True})
(FOLDER / "model_register.json").write_text(json.dumps(reg, indent=1))
print(f"APPROVED: {version} under change {change} by {by}; now the active model")
def active_model():
reg = load_json(FOLDER / "model_register.json", {"approved": []})
live = [e for e in reg["approved"] if e["active"]]
if not live:
raise SystemExit("REFUSED: no approved model. Triage by QA only.")
entry = live[-1]
path = FOLDER / f"model_{entry['version']}.json"
if not path.exists() or file_hash(path) != entry["sha256"]:
raise SystemExit(f"REFUSED: model_{entry['version']}.json differs from what QA approved")
return json.loads(path.read_text()), entry
def state():
return load_json(FOLDER / "deviations.json", {d["id"]: dict(d, status="OPEN") for d in OPEN_DEVIATIONS})
def save_state(devs):
(FOLDER / "deviations.json").write_text(json.dumps(devs, indent=1))
def cmd_triage():
model, entry = active_model()
devs = state()
print(f"Triage with {entry['version']} (approved under {entry['change']}); proposals only")
for d in devs.values():
if d["status"] != "OPEN":
continue
answer, conf, why = predict(model, d["text"])
d["proposal"] = {"class": answer, "confidence": round(conf, 2), "model": entry["version"],
"by": AGENT_USER, "why": [w for w, _ in why]}
shown = ", ".join(f"{w} {'+' if v > 0 else '-'}" for w, v in why)
print(f" {d['id']} {d['batch']} {answer:<9} conf {conf:.2f} because: {shown}")
save_state(devs)
def cmd_close(dev_id, cls, by, rationale):
devs = state()
d = devs.get(dev_id)
if d is None:
raise SystemExit(f"REFUSED: no deviation {dev_id}")
if by not in QA_STAFF:
raise SystemExit(f"REFUSED: {by} may not classify deviations (QA only)")
if not rationale:
raise SystemExit("REFUSED: a QA classification needs a rationale")
d.update(status="CLOSED", qa_class=cls, qa_by=by, qa_rationale=rationale, closed_at=now())
save_state(devs)
note = ""
if d.get("proposal") and d["proposal"]["class"] not in (cls, "UNDECIDED"):
note = f" (QA overrode the proposal {d['proposal']['class']})"
print(f"CLOSED: {dev_id} as {cls} by {by}{note}")
def serials(batch_id):
"""Synthetic serialization data for each batch: one serial per packed unit."""
b = BATCHES[batch_id]
rows = [{"sn": f"{batch_id[-4:]}{i:06d}", "lot": batch_id, "expiry": b["expiry"]} for i in range(b["packed"])]
if batch_id == "B-26-0417": # a rework on the packing line printed one number twice
rows[700]["sn"] = rows[699]["sn"]
return rows
def cmd_release(batch_id, by, meaning):
if batch_id not in BATCHES:
raise SystemExit(f"REFUSED: no batch {batch_id}")
b = BATCHES[batch_id]
problems = []
if by == AGENT_USER or by not in RELEASERS:
problems.append(f"{by} is not authorized to release batches")
if meaning != "approval":
problems.append("signature meaning must be 'approval' for a release")
for d in state().values():
if d["batch"] == batch_id and d["status"] != "CLOSED":
p = d.get("proposal", {}).get("class", "none")
problems.append(f"{d['id']} is open (assistant proposal: {p}); QA must close it")
for test, result in b["lab"].items():
if result != "PASS":
problems.append(f"lab test {test} is {result}")
sn = serials(batch_id)
dupes = len(sn) - len({r["sn"] for r in sn})
if dupes:
problems.append(f"serialization: {dupes} duplicate serial number(s)")
if len(sn) != b["packed"]:
problems.append(f"serialization: {len(sn)} serials for {b['packed']} packs")
if any(r["lot"] != batch_id or r["expiry"] != b["expiry"] for r in sn):
problems.append("serialization: lot or expiry differs from the batch")
if problems:
print(f"REFUSED: {batch_id} stays in QA hold")
for p in problems:
print(f" - {p}")
raise SystemExit(1)
sig = {"batch": batch_id, "decision": "RELEASED", "signer": by, "printed_name": QA_STAFF[by],
"signed_at": now(), "meaning": meaning}
log = load_json(FOLDER / "release_log.json", [])
log.append(sig)
(FOLDER / "release_log.json").write_text(json.dumps(log, indent=1))
print(f"RELEASED: {batch_id} by {QA_STAFF[by]} ({by}), meaning: {meaning}")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
t = sub.add_parser("train")
t.add_argument("--version", required=True)
t.add_argument("--min-confidence", type=float, default=MIN_CONFIDENCE)
sub.add_parser("validate").add_argument("--version", required=True)
a = sub.add_parser("approve")
a.add_argument("--version", required=True)
a.add_argument("--by", required=True)
a.add_argument("--change", required=True)
sub.add_parser("triage")
c = sub.add_parser("close")
c.add_argument("dev")
c.add_argument("--cls", required=True, choices=CLASSES)
c.add_argument("--by", required=True)
c.add_argument("--rationale", default="")
r = sub.add_parser("release")
r.add_argument("batch")
r.add_argument("--by", required=True)
r.add_argument("--meaning", default="")
x = ap.parse_args()
if x.cmd == "train":
cmd_train(x.version, x.min_confidence)
elif x.cmd == "validate":
cmd_validate(x.version)
elif x.cmd == "approve":
cmd_approve(x.version, x.by, x.change)
elif x.cmd == "triage":
cmd_triage()
elif x.cmd == "close":
cmd_close(x.dev, x.cls, x.by, x.rationale)
else:
cmd_release(x.batch, x.by, x.meaning)
if __name__ == "__main__":
main()
The history is generated, not real. Each deviation draws a class (about 30% major), then words from that class's list and a shared list, sometimes a word from the other class, and in 5% of cases the past classification is flipped to mimic inconsistent judgment. Tarnwood, its product TW-100, the batch numbers and the people are fictional, and MINOR and MAJOR are course classes, not a regulatory scale.
#Step 3: Try to triage before anything is approved
Run:
python unit16/gxp_batch_release.py triage
The script refuses, because no model has been validated and approved:
Trained v1 on 240 development records (H-0001..H-0240); 60 held out, never seen
Confidence threshold 0.80; sha256 45f56cdc4a4c
Validation of v1 on 60 held-out records (H-0241..H-0300)
QA class -> model: MAJOR->MAJOR 11 MAJOR->MINOR 1 MAJOR->UNDECIDED 10 MINOR->MINOR 31 MINOR->UNDECIDED 7
MAJOR found as MAJOR: 11/22 (50%)
PASS MAJOR not called MINOR 0.95 (needs >= 0.90)
PASS accuracy on decided 0.98 (needs >= 0.90)
PASS undecided share 0.28 (needs <= 0.30)
Result: PASS (report validation_v1.json)
APPROVED: v1 under change CC-0001 by QA-201; now the active model
Read it as a validation lead would. The model calls only one major deviation minor; the other ten majors it can't decide go to QA anyway, which is why the first criterion counts only the dangerous error. It decides 72% of cases, almost all correctly. The undecided share of 0.28 only just meets its limit, so the model saves QA little time on major cases: that is the honest trade a 0.80 threshold buys.
#Step 5: Propose classes for this week's deviations
Run:
python unit16/gxp_batch_release.py triage
Triage with v1 (approved under CC-0001); proposals only
DEV-0911 B-26-0417 MINOR conf 1.00 because: logbook -, late -, printer -
DEV-0912 B-26-0418 MAJOR conf 0.96 because: alarm +, temperature +, excursion +
DEV-0913 B-26-0418 UNDECIDED conf 0.76 because: filter +, integrity +, missing -
DEV-0914 B-26-0419 MAJOR conf 0.81 because: filter +, integrity +, reported +
A + word pushed toward MAJOR, a - word toward MINOR. DEV-0913 is a missing signature on a filter integrity record: the words pull both ways, so the model hands it to QA. The proposals are saved in unit16/gxp/deviations.json with the model version and the assistant's user, apart from any QA decision.
#Step 6: Try to release, then let QA close the deviations
Let the assistant try to release batch B-26-0418, then try to close a deviation as the assistant and as QA without a reason:
python unit16/gxp_batch_release.py release B-26-0418 --by AGT_BATCH_ASSIST --meaning approval
python unit16/gxp_batch_release.py close DEV-0912 --cls MAJOR --by AGT_BATCH_ASSIST --rationale x
python unit16/gxp_batch_release.py close DEV-0912 --cls MAJOR --by QA-214
REFUSED: B-26-0418 stays in QA hold
- AGT_BATCH_ASSIST is not authorized to release batches
- DEV-0912 is open (assistant proposal: MAJOR); QA must close it
- DEV-0913 is open (assistant proposal: UNDECIDED); QA must close it
REFUSED: AGT_BATCH_ASSIST may not classify deviations (QA only)
REFUSED: a QA classification needs a rationale
Close both deviations as the QA specialist, with the reasoning a reviewer would want to read:
python unit16/gxp_batch_release.py close DEV-0912 --cls MAJOR --by QA-214 --rationale "Room 4 at 31 C for 40 min during granulation; impact assessed, batch unaffected"
python unit16/gxp_batch_release.py close DEV-0913 --cls MINOR --by QA-214 --rationale "Second signature missing on the filter integrity record; the test passed and its printout is on file"
CLOSED: DEV-0912 as MAJOR by QA-214
CLOSED: DEV-0913 as MINOR by QA-214
RELEASED: B-26-0418 by QA release manager 201 (QA-201), meaning: approval
REFUSED: B-26-0417 stays in QA hold
- DEV-0911 is open (assistant proposal: MINOR); QA must close it
- serialization: 1 duplicate serial number(s)
REFUSED: B-26-0419 stays in QA hold
- DEV-0914 is open (assistant proposal: MAJOR); QA must close it
- lab test micro is PENDING
Open unit16/gxp/release_log.json. The entry holds the printed name, the date and time and the meaning, the three items a signed electronic record must show. Your time will differ from anyone else's.
B-26-0417 shows why serialization belongs in release: its deviation looks minor, but a rework on the packing line printed one serial twice, and that alone holds the batch.
REFUSED: model_v1.json differs from what QA approved
The fingerprint in the register no longer matches the file, so the system stops using it. This is draft Annex 22's configuration control in miniature: an unauthorized change is detected, not trusted. To start the walkthrough again, delete the unit16/gxp folder.
SAP Batch Release Hub for Life Sciences is offered as a public cloud deployment with native SAP S/4HANA integration, licensed per tenant and in blocks of 1,500 documents a year (sap.com). Its feature scope description of 28 November 2025 lists (help.sap.com):
worklists for batches and for packaging control numbers, where users prepare, review and set release decisions with an e-signature;
preconfigured release checks, each with a business rule that evaluates the status provided by the source system, and custom release checks built as checklist items;
jurisdictional control, which checks batches against the specifications authorized by each health authority using authorized supply chain maps, and can reevaluate batches already released;
automated batch release for release types you configure to release without an e-signature;
tracking of changes, including e-signature events, and PDF reports of decisions;
public APIs to SAP S/4HANA or any ERP, with LIMS, RIMS, QMS and MES named as source systems, and links to SAP Advanced Track and Trace for Pharmaceuticals and SAP Global Batch Traceability;
an AI-assisted custom release check that proposes an answer for a checklist item, which requires enabling the AI feature and buying AI Units.
Two observations for a builder. Automated release in the hub is a configured, rule-based path that your validation must cover; it is not a model deciding. And SAP's AI feature sits on custom checklist items, which is exactly where a human-in-the-loop duty belongs in the intended use.
No page opened for this topic names an SAP feature that classifies deviations. If you build one on SAP BTP, SAP doesn't validate it for you: your quality system does, under the same change control as the rest of the validated landscape.
Where it sits. S/4HANA holds batches, inspection results and stock status. The QMS holds deviations and the LIMS holds lab results. Batch Release Hub in the cloud reads them through APIs and records the decision. A triage service on SAP BTP reads deviation text, writes proposals back to the QMS, and keeps its model register. Serial data flows from packaging lines into Advanced Track and Trace and out to partners through Traceability Hub.
flowchart LR
subgraph S4[S/4HANA]
B[Batches, stock]
end
QMS[QMS<br/>deviations] --> BRH
LIMS[LIMS<br/>results] --> BRH
B --> BRH[Batch Release Hub<br/>e-signed decision]
subgraph BTP[SAP BTP]
TS[Triage service<br/>+ model register]
end
QMS --> TS
TS -->|proposal only| QMS
ATT[Track and Trace] --> BRH
ATT --> TH[Traceability Hub] --> PT[Partners,<br/>regulators]
Non-functional requirements.
Requirement
Typical target
What breaks if missed
Validation state
Every model version validated and approved before use
The process becomes unvalidated; an inspection finding
Audit trail
Every proposal stored with model version, confidence and reasons
You can't show what the person saw when they decided
Determinism
Same input, same output for the approved version
The validation evidence no longer describes the system
Availability
Release continues without the model
A model outage holds batches
Data protection
Deviation text may name people; access limited to quality
Personal data spread across tools
Integration and identity. The triage service runs under a technical user that can read deviations and write a proposal field. It holds no authority to close a deviation, make a usage decision or set a release decision; those stay with named people, signing in their own name. Batch Release Hub and the serialization products connect through the public APIs their documents name; check the current API catalog for the exact services.
The decision to record.
Context: QA spends release time triaging deviations; SAP names no deviation classifier; the draft Annex 22 limits critical AI to static, deterministic models.
Options: (1) keep triage manual; (2) use a large language model to classify; (3) a frozen classifier on BTP that proposes classes with confidence and reasons, under change control.
Decision: Option 3, proposals only, with an undecided band; option 2 is rejected for classification and allowed only for drafting summaries a person checks.
Consequences: Every retrain is a change request with validation evidence; performance is reviewed against QA's final classes; the model is retired if SAP ships an equivalent inside the release workflow.
What a design review will ask.
Show the acceptance criteria and the date they were approved, before the test.
How do you prove the test data never reached training?
What happens to release if the service is down, or its file changes?
Can the technical user close a deviation or release a batch? Show the role and the negative test.
Who approves the next model version, and what evidence will they see?
Authorizations. Give the assistant's user no release, usage decision or closing rights, and prove it with a negative test in every release (see human approval in AI workflows).
Validation and change control. Treat the model file, its threshold and its training data as configuration items. A threshold change is a model change, even if not a line of training code moved.
Monitoring. Compare proposals with QA's final classes every month, by deviation type and site, and watch the undecided share; draft Annex 22 asks for performance and input monitoring (section 10). See hypercare and drift after go-live for the mechanics and building an evaluation harness for the test set.
Language models. Keep them out of the classification. A summary of past deviations for an investigator is a different, non-critical use, with the investigator responsible for what they take from it.
Records. Keep the proposal and the QA decision as separate fields with separate authors. Both are part of the audit trail.
Cost. A small classifier costs almost nothing to run. The real cost is validation effort per version, so batch changes into planned releases.
Clean core. Keep the model and register on BTP; write back only proposals, through the QMS or SAP's released APIs.
Document a model change the way a quality system would.
Delete unit16/gxp and run Steps 4 to 7 again, so v1 is approved and B-26-0418 is released.
Train a second version with a lower threshold: python unit16/gxp_batch_release.py train --version v2 --min-confidence 0.70.
Run validate --version v2 and compare it with v1: write down the undecided share and the number of majors called minor.
In cmd_approve(), add a required --reason option and store it in the register entry, so every change says why it was made.
Approve v2 as QA-214 under change CC-0002 with the reason "Lower undecided share; no more majors called minor", then run triage.
Done whenvalidate --version v2 shows undecided share 0.15 and still one MAJOR->MINOR, unit16/gxp/model_register.json holds v1 (inactive) and v2 (active) each with its hash, change number and reason, and triage prints Triage with v2 (approved under CC-0002). Keep the register: it is the change record a later portfolio project can cite.
Pick one answer for each question. The explanation appears after you choose.
1In the walkthrough, why does validation count only MAJOR deviations called MINOR as missed, not MAJOR ones left undecided?
Answer: B. Below the threshold the model hands the case to QA, who classifies it alone. The dangerous error is a major deviation proposed as minor, so that is what the first criterion limits.
2Why does the script refuse to triage after one line is added to the approved model file?
Answer: C. The register stores the fingerprint of the file QA approved. Any change alters the hash, so the system treats the file as unapproved, which is the configuration control the draft Annex 22 asks for.
3Which draft Annex 22 requirement does the fixed CRITERIA dictionary in the code stand for?
Answer: D. The draft asks for acceptance criteria to be approved by a process expert before acceptance testing, and to be no lower than the process replaced. Writing them into the code before any run stands for that step.
4B-26-0417 has only one deviation, which the model proposes as MINOR. Why does the release gate still refuse it after QA closes the deviation?
Answer: B. The gate checks serialization as well as deviations and lab results. A rework on the packing line printed one serial twice, and that alone holds the batch.
5What must a signed release record show under 21 CFR 11.50?
Answer: D. Part 11 requires the printed name of the signer, the date and time of signing, and the meaning such as approval. The release log in the walkthrough stores exactly those three with the batch.
6What does SAP's feature scope description say about AI in SAP Batch Release Hub?
Answer: C. The document describes an AI-assisted custom release check that proposes an answer for a checklist item, enabled by the customer with AI Units. Automated release without an e-signature is a separate, configured rule for chosen release types.
7Your data scientists propose classifying deviations with a large language model because it reads free text better. As the architect, what do you decide?
Answer: C. The draft Annex 22 says generative AI and large language models should not be used in critical GMP applications. Drafting summaries for an investigator who stays responsible is a non-critical use and can be allowed.
8Lowering the confidence threshold from 0.80 to 0.70 cuts the undecided share. How do you put it into use?
Answer: A. The threshold is part of the model's behavior, so changing it is a model change. It needs a new version, validation against the same criteria and approval under change control before use.
SAP Batch Release Hub for Life Sciences (sap.com)— Opened 2026-11-26. No page date. Automates the batch release process to reduce the risk of quality noncompliance; public cloud deployment; native integration with SAP S/4HANA; priced per tenant and in blocks of 1,500 documents a year
Feature Scope Description for SAP Batch Release Hub for Life Sciences (help.sap.com, PDF)— Opened 2026-11-26; document dated 2025-11-28. Worklists for batches and packaging control numbers; preconfigured release checks with business rules that evaluate the status from the source system; custom release checks as checklist items; jurisdictional control against authorized supply chain maps; release decision set with an e-signature; automated batch release configurable for chosen release types without an e-signature; tracking of changes including e-signature events; AI-assisted custom release check that proposes a checklist item, needs the AI feature enabled and AI units bought; public APIs to SAP S/4HANA or any ERP; source systems named: LIMS, RIMS, QMS, MES
SAP Advanced Track and Trace for Pharmaceuticals on SAP S/4HANA (sap.com)— Opened 2026-11-26. No page date. Corporate serialization repository, serial number management (sequential ranges and randomized lists, aggregations), events from packaging lines, country-specific regulatory reporting; pricing section names SAP S/4HANA Cloud, private edition; billed per object in blocks of 12 million a year
SAP Traceability Hub (sap.com)— Opened 2026-11-26. No page date. Cloud service for exchanging track-and-trace data with trading partners and regulators; preconfigured support for FMD and DSCSA; AI-powered error insights that analyze message failures, point to root causes and recommend fixes (embedded SAP Business AI); billed per million documents a year
Annex 22: Artificial Intelligence, consultation draft (European Commission, PDF)— Opened 2026-11-26; July 2025 consultation draft. Scope: AI models in critical GMP applications; static, deterministic models only; dynamic and probabilistic models, generative AI and LLMs not for critical use; intended use approved by a process expert (3.1), human-in-the-loop responsibility (3.3); acceptance criteria set before testing and no lower than the process replaced (4.2, 4.3); independent test data (6); explainability (8); confidence score and threshold, low confidence flagged undecided (9); change control and configuration control, performance and input monitoring (10)
21 CFR 211.192: Production record review (eCFR)— Opened 2026-11-26 (eCFR up to date as of 13 August 2026). Production and control records reviewed and approved by the quality control unit before a batch is released or distributed; unexplained discrepancies thoroughly investigated, extended to other batches, with a written record of conclusions and follow-up
21 CFR Part 211 Subpart B: Organization and Personnel, including 211.22 (eCFR)— Opened 2026-11-26 (eCFR up to date as of 22 October 2026). 211.22: the quality control unit has the responsibility and authority to approve or reject components, in-process materials and drug products, and to review production records; procedures in writing and followed
21 CFR Part 11 Subpart B: Electronic Records, including 11.10, 11.50 and 11.70 (eCFR)— Opened 2026-11-26 (eCFR up to date as of 16 October 2026). 11.10: validation, secure time-stamped audit trails, access limits, authority checks, documentation change control; 11.50: signed records show printed name, date and time, and meaning of the signature; 11.70: signatures linked to their records
Exemptions under the Drug Supply Chain Security Act (FDA)— Opened 2026-11-26 (content current as of 26 August 2026). FDA exempts small business dispensers (25 or fewer full-time pharmacists and technicians) from certain enhanced drug distribution security requirements until 27 November 2027; other trading partners remain subject to them