Capstone 8 — Deployment
The retention team now trusts the churn model of Capstone 4. It has a budget of 1,000 calls per month and a call threshold of 0.335: the break-even churn probability, above which a call is expected to pay off. Today, an analyst runs a script once a month and emails a CSV file of customers to call. The CRM team wants the scores inside the CRM: when an agent opens a customer record, and every night for the call list.
The head of the CRM team asks you for an HTTP service that the CRM can call. Two teams give you their requirements:
- The CRM developers want a stable contract: a documented request and response shape, clear error answers that they can code against, one customer per call for the agent screen, a batch call for the nightly job and the model version in every answer.
- The operations team wants a health check for the load balancer (the component that spreads the incoming requests over the running copies of a service), logs that they can search, a container image that runs anywhere, and a way to roll back to the previous model in minutes.
The service supports one decision: which customers get a retention call. It applies the threshold of Capstone 4, so the CRM never needs to know how the model works.
Module 44 built a one-file API with one endpoint. This capstone turns it into a small, real service:
| Module 44 gave you | This capstone adds |
|---|---|
a script app.py with a module-level app |
a package churn_service/ with an app factory, create_app(settings) |
| a fixed model path | settings from CHURN_* environment variables, validated at start-up |
| one pickle bundle and its sidecar | the two Capstone 4 files, golden cases and a manifest that hashes all of them, with an optional release hash |
| a bad bundle stops the service | a bad folder gives 503 and a log line; the process stays up |
/health and /predict |
also /live, /predict/batch with a size limit and /model-info |
| FastAPI’s default errors | one documented error shape for 422, 404, 503 and 500, with a request id |
| one log line on failure | JSON logs for every request, with the request id and the error stack |
| tests of one endpoint | 61 tests: golden predictions, 13 kinds of broken model folder, log privacy |
| — | a Dockerfile, a run command, a release check and a runbook |
Deliverables:
package_model.py, which adds golden cases and a hash manifest to the model folder that Capstone 4’strain_churn.pywrites.- A package
churn_service/with the settings, the safe model loader, the request and response models, the logging setup and the app. - A pytest suite in
tests/that runs in under a second. - A
requirements.txt, aDockerfileand the command that starts the service. release_check.pyand a one-page runbook: deploy, monitor and roll back.
Skills practiced:
| Skill | Where you learned it |
|---|---|
Custom exceptions, logging |
Module 06 — Errors and debugging |
Packages, relative imports, pyproject.toml |
Module 08 — Modules, packages and environments |
asynccontextmanager, ExitStack |
Module 11 — Decorators and context managers |
Literal, Annotated, Protocol, Self |
Module 12 — Type hints |
Fixtures, tmp_path, parametrize, monkeypatch, caplog |
Module 14 — Testing with pytest |
| HTTP methods, status codes, environment variables | Module 16 — APIs and web data |
| Frozen dataclasses | Module 21 — Dataclasses, enums and slots |
| Pipelines that hold their preprocessing | Module 34 — The scikit-learn workflow |
Model files, FastAPI, pydantic, TestClient, drift |
Module 44 — ML in production basics |
Dataset
Section titled “Dataset”The service itself reads no data file. Only the training and packaging scripts read data/customers.csv: 5,000 customers, one row each (data dictionary).
Columns used:
- 12 features:
region,plan,contract,payment_method,age,has_autopay,tenure_months,monthly_charges,total_charges,support_tickets,logins_last_30dandavg_session_minutes. churned, the target, only for training.customer_id, which the service echoes back but never gives to the model.
Known quirks that matter for serving:
total_chargesis blank for exactly 10 brand-new customers. pandas reads a blank as NaN, but JSON has no NaN. The CRM must sendnull, and the service must turnnullback into the NaN that the model learned from.has_autopayis 0/1 in the file. The API takes a JSON boolean. Pydantic’s default lax mode also converts some other values: 1,"yes","true"and"on"becomeTrue, and"34"or34.0becomes the integer 34. This capstone keeps lax mode, documents it and tests it. The model needs 0/1 again.- The categories are exact, lowercase strings (
month-to-month,electronic_check). The Capstone 4 pipeline raisesValueErrorfor any category it did not see in training, a blank one included. So the API must refusePremiumor""with a 422 before the model sees it; otherwise the client gets a 500. tenure_monthsstops at 72 in the data (a cap). The API accepts up to 120, because a real customer can stay longer than the training data shows. The metadata stores the training ranges, so a monitoring job can count values outside them.- The classes are imbalanced: 19.26% of customers churned. The share of flagged customers in production is a useful health signal.
Milestones
Section titled “Milestones”Milestone 1 — Package the model artifact
Section titled “Milestone 1 — Package the model artifact”- Goal: two commands train the Capstone 4 model and turn its output into a folder that the service can check.
- Acceptance criteria:
python train_churn.py(from Capstone 4, unchanged) writesmodels/churn_model.joblibandmodels/metadata.json.python package_model.pyaddsgolden_cases.json(customers across the score range, one at the threshold and one withouttotal_charges) andMANIFEST.sha256, and prints the release hash. Two training runs give the same files. The shipped pipeline gives the same probabilities as Capstone 4’s recipe. - Review: Capstone 4, module 34, module 44.
Milestone 2 — Read the settings from the environment
Section titled “Milestone 2 — Read the settings from the environment”- Goal: every value that changes between machines comes from an environment variable with a safe default.
- Acceptance criteria:
CHURN_MODEL_DIR,CHURN_MODEL_SHA256,CHURN_MAX_BATCH_SIZEandCHURN_LOG_LEVELexist. An invalid value stops the service at start-up with a clear message. An unknownCHURN_name gives a warning, not a crash. - Review: module 16, module 44.
Milestone 3 — Load the model safely
Section titled “Milestone 3 — Load the model safely”- Goal: the service unpickles only a folder whose files have not changed since packaging, and it says why it refuses one.
- Acceptance criteria: before
joblib.load(), the loader checks the manifest (against the release hash when one is set), the hash of every listed file, the metadata types, and that the features, categories and library versions match the service. Every problem, a half-copied or unreadable file included, raisesModelLoadErrorwith a precise message. - Review: module 06, module 07, module 44.
Milestone 4 — Define the request and response contract
Section titled “Milestone 4 — Define the request and response contract”- Goal: pydantic models that accept every valid customer and reject every invalid one, with the reason.
- Acceptance criteria: unknown fields, NaN, infinity, unknown or blank categories and out-of-range values give a 422.
customer_idandtotal_chargesare optional. The batch model takes 1 tomax_batch_sizecustomers. The allowed categories are exactly the model’s categories. - Review: module 12, module 44.
Milestone 5 — Build the API, its errors and its logs
Section titled “Milestone 5 — Build the API, its errors and its logs”- Goal: five endpoints, one documented error shape and one JSON log line per event.
- Acceptance criteria:
GET /live,GET /health,GET /model-info,POST /predictandPOST /predict/batchwork. Every error answer haserror,messageandrequest_id, and the OpenAPI schema documents it. A bad model folder gives 503 with aRetry-Afterheader. A model failure gives 500 without internal details. Every request gets anX-Request-IDheader and a log line with its status and duration. Error lines carry the stack. Logs never contain customer values. - Review: module 06, module 11, module 16, module 44.
Milestone 6 — Test the service
Section titled “Milestone 6 — Test the service”- Goal: a suite that proves each rule of milestones 2–5 and catches a training–serving skew.
- Acceptance criteria: tests cover the happy paths, validation errors, lax-mode conversions, the batch limits, a missing model, every kind of broken model folder, a model failure, the settings, the OpenAPI error schema and the log content. A golden test sends the golden cases through the API and gets the training scores and decisions back. The suite runs in under one second, and
ruff checkpasses. - Review: module 14, module 44.
Milestone 7 — Ship it: container, run command and runbook
Section titled “Milestone 7 — Ship it: container, run command and runbook”- Goal: anyone on the operations team can deploy, watch and roll back the service without you.
- Acceptance criteria: a pinned
requirements.txt, a.dockerignore, aDockerfilethat runs as a non-root user with a health check, theuvicorncommand, a release check script, and a runbook with the steps and checks for deploy, monitor and roll back. - Review: module 08, module 44.
Grading rubric
Section titled “Grading rubric”| Criterion | Needs work (0 points) | Meets | Excellent | Points |
|---|---|---|---|---|
| Model artifact | the pipeline file only | model, metadata and a hash, reproducible (2) | a manifest over every file, golden cases, a release hash; parity with the training recipe shown (3) | 3 |
| Settings | paths in the code | environment variables with defaults (1) | validated at start-up; unknown names reported; one settings object (2) | 2 |
| Safe loading | joblib.load() on any file |
hash checked before unpickling (2) | also metadata types, versions, features and categories; every bad folder gives ModelLoadError (3) |
3 |
| Request contract | a dict body |
pydantic models with ranges and categories (2) | also no NaN, blank or extra values; documented lax mode; a configured batch limit in the schema (3) | 3 |
| Endpoints and errors | 500 for bad input, tracebacks to the client | four endpoints; 422, 503 and 500 (2) | one documented error shape with a request id; liveness and readiness; no internal details (4) | 4 |
| Logging | print() or no logs |
logging on errors (1) |
JSON lines with the request id, duration and error stack; no customer values (2) | 2 |
| Tests | fewer than 10 tests, or tests need a running server | TestClient tests of the happy paths and 422 (3) |
also limits, 503, 500, broken folders, golden predictions, log privacy; under one second (5) | 5 |
| Shipping | no container or run command | pinned requirements, a Dockerfile, a run command (2) |
non-root, health check, cached layers, no data in the image; a release check and a runbook (3) | 3 |
| Total | 25 |
You meet the brief at 17 points or more.
Reference solution
Section titled “Reference solution”The solution is a real project. Each file is shown in full, in the order of the milestones. Python blocks then import the package and call the app in memory with TestClient, and terminal blocks run the scripts and the tests from the project folder. No server or Docker runs on this page.
Reference solution — Milestone 1: Package the model artifact
The project uses the flat layout of module 08: the package sits next to data/, so the tests and uvicorn find it without an install step.
my-course/├── data/customers.csv├── .dockerignore├── Dockerfile├── pyproject.toml # project name, pytest and ruff settings├── requirements.txt # pinned runtime dependencies├── train_churn.py # from Capstone 4, unchanged├── package_model.py # milestone 1├── release_check.py # milestone 7├── churn_service/│ ├── __init__.py # service version│ ├── config.py # Settings from CHURN_* variables (milestone 2)│ ├── model.py # safe loading and scoring (milestone 3)│ ├── schemas.py # request and response models (milestone 4)│ ├── logging_setup.py # JSON log lines (milestone 5)│ ├── app.py # create_app(): endpoints and errors (milestone 5)│ └── main.py # the object that uvicorn serves (milestone 5)├── models/ # written by the two scripts└── tests/ # milestone 6Train with Capstone 4’s script. Copy train_churn.py from Capstone 4 into the project folder and do not change it. One training recipe in one file is the surest way to serve exactly the model that was evaluated: the same splits, the same ordinal-code + LightGBM pipeline refit on all 3,750 training rows, the break-even threshold and one test evaluation.
python train_churn.pytrain 3,750 (fit 2,812 + validation 938)CV ROC-AUC 0.844, PR-AUC 0.623threshold 0.335 (break-even); validation best 0.39test: 249 calls, USD 5,395 expected profit per 1,000 customerssaved models/churn_model.joblib and models/metadata.jsonTwo checks before you serve it. First, a second run must give the same files: otherwise the hashes below would change with every training and could not name a release. Second, the shipped pipeline must give the probabilities of Capstone 4’s recipe. The second check refits build_pipeline() from train_churn.py on the same training rows and compares the test probabilities bit by bit.
python train_churn.py --out output/rerun > /dev/nullimport jsonfrom pathlib import Path
import joblibimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_split
import train_churnfrom churn_service.model import FEATURES, file_sha256
models = Path("models")for name in ["churn_model.joblib", "metadata.json"]: same = file_sha256(models / name) == file_sha256(Path("output/rerun") / name) print(f"{name:<19} identical in both runs: {same}")
customers = pd.read_csv("data/customers.csv")X, y = customers[train_churn.FEATURES], customers[train_churn.TARGET]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=train_churn.SEED)recipe = train_churn.build_pipeline().fit(X_train, y_train)shipped = joblib.load(models / "churn_model.joblib") # our own, fresh filep_recipe = recipe.predict_proba(X_test)[:, 1]p_shipped = shipped.predict_proba(X_test)[:, 1]print("identical test probabilities:", np.array_equal(p_recipe, p_shipped))print("service uses the same columns:", FEATURES == train_churn.FEATURES)
metadata = json.loads((models / "metadata.json").read_text())for key in ["model_version", "n_train", "threshold", "threshold_rule"]: print(f"{key:>14}: {metadata[key]}")assert np.array_equal(p_recipe, p_shipped)assert metadata["threshold"] == 0.335churn_model.joblib identical in both runs: Truemetadata.json identical in both runs: Trueidentical test probabilities: Trueservice uses the same columns: True model_version: 1.0.0 n_train: 3750 threshold: 0.335threshold_rule: break-even: call_cost_usd / (save_rate * value_saved_usd)Add what serving needs. package_model.py adds two files to the folder.
"""Package a model that Capstone 4's train_churn.py trained, for the service.
Run from the project folder, after `python train_churn.py`: python package_model.py [--models DIR] [--data PATH]
Adds two files to DIR: golden_cases.json 7 customers and the scores the trained pipeline gives them MANIFEST.sha256 the SHA-256 of the model, the metadata and the golden casesThen prints the SHA-256 of the manifest itself: the release hash. Store itoutside the folder (the release record) and give it to the service asCHURN_MODEL_SHA256."""
import argparseimport jsonfrom pathlib import Path
import joblibimport numpy as npimport pandas as pd
from churn_service.model import ( FEATURES, GOLDEN_FILE, METADATA_FILE, MODEL_FILE, file_sha256, write_manifest,)
QUANTILES = [0.05, 0.25, 0.50, 0.75, 0.95]
def golden_cases(customers: pd.DataFrame, pipeline, threshold: float) -> list[dict]: """Score 7 customers: 5 across the score range, the one closest to the threshold and the first one without total_charges.""" scores = pipeline.predict_proba(customers[FEATURES])[:, 1] order = np.argsort(scores, kind="stable") ranks = (np.array(QUANTILES) * (len(order) - 1)).astype(int) picked = [int(i) for i in order[ranks]] picked.append(int(np.argmin(np.abs(scores - threshold)))) picked.append(int(np.flatnonzero(customers["total_charges"].isna())[0])) records = customers.iloc[picked][["customer_id", *FEATURES]].to_dict("records") cases = [] for record, p in zip(records, scores[picked], strict=True): # JSON has no NaN: a missing total_charges travels as null. clean = {k: None if pd.isna(v) else v for k, v in record.items()} cases.append( { "customer": clean, "churn_probability": float(p), "will_churn": bool(p >= threshold), } ) return cases
def main() -> None: parser = argparse.ArgumentParser(description="Package a trained churn model.") parser.add_argument("--models", type=Path, default=Path("models")) parser.add_argument("--data", type=Path, default=Path("data/customers.csv")) args = parser.parse_args()
# This script trusts the folder: train_churn.py wrote it a moment ago. pipeline = joblib.load(args.models / MODEL_FILE) metadata = json.loads((args.models / METADATA_FILE).read_text()) cases = golden_cases(pd.read_csv(args.data), pipeline, metadata["threshold"]) (args.models / GOLDEN_FILE).write_text(json.dumps(cases, indent=2)) manifest = write_manifest(args.models, [MODEL_FILE, METADATA_FILE, GOLDEN_FILE])
print(f"model {metadata['model_version']}, threshold {metadata['threshold']}") for case in cases: customer = case["customer"] print( f" golden {customer['customer_id']} total={customer['total_charges']}" f" p={case['churn_probability']:.4f} call={case['will_churn']}" ) print(manifest.read_text().rstrip()) print(f"release hash (CHURN_MODEL_SHA256): {file_sha256(manifest)}")
if __name__ == "__main__": main()- The golden cases are 7 customers: 5 across the score range (5th to 95th percentile), the one whose score is closest to the threshold and the first one with a blank
total_charges. The script scores them straight from the DataFrame, as training does, and stores the request bodies that the CRM would send. In milestone 6, a test sends them through the API. The threshold case tests the>=comparison at its edge; thenullcase tests the NaN conversion. - The manifest lists the SHA-256 of each file in the format of the
sha256sumtool, so an operator can also check a copied folder withsha256sum -c MANIFEST.sha256. It coversmetadata.jsontoo, because that file holds the threshold that decides who gets a call. - The release hash is the SHA-256 of the manifest itself. One value names the whole folder.
python package_model.pymodel 1.0.0, threshold 0.335 golden C02820 total=800.7 p=0.0255 call=False golden C00860 total=2686.06 p=0.0498 call=False golden C02823 total=548.74 p=0.1055 call=False golden C01616 total=1758.44 p=0.2756 call=False golden C04776 total=68.49 p=0.6503 call=True golden C03934 total=242.09 p=0.3350 call=True golden C04991 total=None p=0.3120 call=False3cff5e8ae230f12de4c8d7d36eda4c57fa78511a4fbe65e906c3f4256f531762 churn_model.joblibb5f1f94b0dab1a7dda91abffd222c9fbd52218f05422bc059c0e877d40304f6e metadata.json065a9364de1611e611cea6b976fdf7d6aeb261e5a0bce0e1a64ec9fb0ebd518c golden_cases.jsonrelease hash (CHURN_MODEL_SHA256): 6e30f4a4021e80ae189b3babbc29aa5081ff1e223ded3767ceb53e179140183bThe golden cases cover both sides of the threshold. C03934 scores 0.3350 and is flagged: it sits right at the threshold.
Reference solution — Milestone 2: Read the settings from the environment
A pydantic model validates the settings like any other input.
"""Service settings, read once at start-up from CHURN_* environment variables."""
import osfrom collections.abc import Mappingfrom pathlib import Pathfrom typing import Literal, Self
from pydantic import BaseModel, ConfigDict, Field
PREFIX = "CHURN_"
class Settings(BaseModel): """Every setting has a safe default; an invalid value stops the service."""
model_config = ConfigDict(frozen=True, extra="forbid")
model_dir: Path = Path("models") # The SHA-256 of MANIFEST.sha256, from the release record. None: not pinned. model_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") max_batch_size: int = Field(default=100, ge=1, le=10_000) log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
@classmethod def from_env(cls, environ: Mapping[str, str] | None = None) -> Self: """Build the settings from CHURN_<NAME> variables (default: os.environ).
CHURN_MAX_BATCH_SIZE=250 sets max_batch_size. Other CHURN_ names are skipped here; unknown_settings() lists them for a start-up warning. """ environ = os.environ if environ is None else environ values = { name: environ[key] for key in environ if key.startswith(PREFIX) and (name := key.removeprefix(PREFIX).lower()) in cls.model_fields } return cls.model_validate(values)
def unknown_settings(environ: Mapping[str, str] | None = None) -> list[str]: """Return the CHURN_ names that are no setting: typos, or platform variables.
Kubernetes adds CHURN_PORT and CHURN_SERVICE_HOST for a Service named "churn", so these names must not stop the service. """ environ = os.environ if environ is None else environ return sorted( key for key in environ if key.startswith(PREFIX) and key.removeprefix(PREFIX).lower() not in Settings.model_fields )frozen=Truemakes the settings read-only after start-up: no request can change them.- A bad value stops the service: a deployment bug never fixes itself.
CHURN_MODEL_SHA256must look like a full SHA-256, so a truncated copy-paste fails at once. - An unknown
CHURN_name does not stop it. Kubernetes adds variables such asCHURN_PORTandCHURN_SERVICE_HOSTto every pod when a Service namedchurnexists in the namespace (unless the pod setsenableServiceLinks: false). A strict check would crash every pod.main.pylogs the unknown names as a warning instead, so a typo such asCHURN_MAX_BATCHis still visible. The packagepydantic-settingsmakes the same choice: it ignores unknown prefixed variables. It also reads.envfiles and secrets folders, which this service does not need. from_env()takes an optional mapping. Tests pass a plaindictand never touch the real environment.
from pydantic import ValidationError
from churn_service.config import Settings, unknown_settings
env = { "CHURN_MODEL_DIR": "models/1.0.0", "CHURN_MAX_BATCH_SIZE": "250", "CHURN_MAX_BATCH": "50", # a typo "CHURN_PORT": "tcp://10.0.0.7:80", # added by Kubernetes}print(Settings.from_env({}))print(Settings.from_env(env))print("unknown:", unknown_settings(env))for bad in [{"CHURN_MAX_BATCH_SIZE": "0"}, {"CHURN_MODEL_SHA256": "6e30f4"}]: try: Settings.from_env(bad) except ValidationError as exc: error = exc.errors()[0] print(f"{bad} -> {error['loc'][0]}: {error['msg']}")model_dir=PosixPath('models') model_sha256=None max_batch_size=100 log_level='INFO'model_dir=PosixPath('models/1.0.0') model_sha256=None max_batch_size=250 log_level='INFO'unknown: ['CHURN_MAX_BATCH', 'CHURN_PORT']{'CHURN_MAX_BATCH_SIZE': '0'} -> max_batch_size: Input should be greater than or equal to 1{'CHURN_MODEL_SHA256': '6e30f4'} -> model_sha256: String should match pattern '^[0-9a-f]{64}$'Environment variables are always strings. Pydantic converts "250" to an integer and checks its range.
Reference solution — Milestone 3: Load the model safely
"""Load the churn model safely and score customers with it.
A model folder holds the two files of Capstone 4's train_churn.py, plus twofiles that package_model.py adds: churn_model.joblib the fitted scikit-learn pipeline metadata.json version, threshold, scores and input schema golden_cases.json customers and the scores the pipeline gave them MANIFEST.sha256 the SHA-256 of each file above, in `sha256sum` format"""
import hashlibimport refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
import joblibimport lightgbmimport numpy as npimport pandas as pdimport sklearnfrom pydantic import BaseModel, ConfigDict, Field, ValidationError
CATEGORICAL = ["region", "plan", "contract", "payment_method"]NUMERIC = [ "age", "has_autopay", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes",]FEATURES = CATEGORICAL + NUMERICMODEL_FILE = "churn_model.joblib"METADATA_FILE = "metadata.json"GOLDEN_FILE = "golden_cases.json"MANIFEST_FILE = "MANIFEST.sha256"SHA256_RE = re.compile(r"[0-9a-f]{64}")
class ModelLoadError(RuntimeError): """The model folder cannot be used safely."""
class ModelMetadata(BaseModel): """The metadata keys that the service uses, with their types."""
model_config = ConfigDict(extra="allow", frozen=True)
model_name: str model_version: str trained_at: str n_train: int features: list[str] categories: dict[str, list[str]] threshold: float = Field(gt=0, lt=1) threshold_rule: str metrics: dict[str, float] sklearn_version: str lightgbm_version: str
def file_sha256(path: Path, chunk_size: int = 1 << 16) -> str: """Return the SHA-256 hex digest of a file, read in chunks.""" digest = hashlib.sha256() with path.open("rb") as f: while chunk := f.read(chunk_size): digest.update(chunk) return digest.hexdigest()
def write_manifest(model_dir: Path, names: list[str]) -> Path: """Write '<sha256> <name>' lines, the format that `sha256sum -c` reads.""" lines = [f"{file_sha256(model_dir / name)} {name}\n" for name in names] manifest = model_dir / MANIFEST_FILE manifest.write_text("".join(lines)) return manifest
def read_manifest(path: Path) -> dict[str, str]: """Return {file name: expected SHA-256}; refuse a malformed manifest.""" hashes = {} for number, line in enumerate(path.read_text().splitlines(), start=1): parts = line.split() if len(parts) != 2 or not SHA256_RE.fullmatch(parts[0]): raise ModelLoadError(f"{path.name} line {number} is not '<sha256> <file>'") hashes[parts[1]] = parts[0] if not hashes: raise ModelLoadError(f"{path.name} is empty") return hashes
@dataclass(frozen=True)class ChurnModel: """A loaded pipeline with its checked metadata and hashes."""
pipeline: Any metadata: ModelMetadata sha256: str manifest_sha256: str
@property def version(self) -> str: return self.metadata.model_version
@property def threshold(self) -> float: return self.metadata.threshold
def predict_proba(self, rows: list[dict[str, Any]]) -> np.ndarray: """Return P(churn) for feature dicts, in the input order.""" frame = pd.DataFrame(rows, columns=FEATURES) # The model learned 0/1 and NaN: True -> 1.0, None -> NaN. frame[NUMERIC] = frame[NUMERIC].astype(float) return self.pipeline.predict_proba(frame)[:, 1]
def load_model( model_dir: Path, categories: dict[str, list[str]], manifest_sha256: str | None = None,) -> ChurnModel: """Check the model folder, then unpickle the pipeline.
Every problem, even an unreadable or half-copied file, raises ModelLoadError, so the service can refuse the folder instead of crashing. """ try: return _check_and_load(model_dir, categories, manifest_sha256) except ModelLoadError: raise except Exception as exc: # OSError, UnicodeDecodeError, ...: still refuse raise ModelLoadError(f"cannot read {model_dir}: {type(exc).__name__}") from exc
def _check_and_load( model_dir: Path, categories: dict[str, list[str]], manifest_sha256: str | None) -> ChurnModel: manifest = model_dir / MANIFEST_FILE if not manifest.is_file(): raise ModelLoadError(f"not found in {model_dir}: {MANIFEST_FILE}") actual_manifest_hash = file_sha256(manifest) if manifest_sha256 is not None and actual_manifest_hash != manifest_sha256: raise ModelLoadError(f"{MANIFEST_FILE} differs from the release hash")
hashes = read_manifest(manifest) for name in (MODEL_FILE, METADATA_FILE): if name not in hashes: raise ModelLoadError(f"{MANIFEST_FILE} does not list {name}") missing = [name for name in hashes if not (model_dir / name).is_file()] if missing: raise ModelLoadError(f"not found in {model_dir}: {', '.join(missing)}") for name, expected in hashes.items(): if file_sha256(model_dir / name) != expected: raise ModelLoadError(f"{name} hash mismatch: the file changed")
try: metadata = ModelMetadata.model_validate_json( (model_dir / METADATA_FILE).read_bytes() ) except ValidationError as exc: error = exc.errors()[0] if error["type"] == "json_invalid": # for example a half-copied file message = f"{METADATA_FILE} is not valid JSON: {error['ctx']['error']}" else: where = ".".join(str(part) for part in error["loc"]) message = f"{METADATA_FILE} is invalid at {where}: {error['msg']}" raise ModelLoadError(message) from exc if metadata.features != FEATURES: raise ModelLoadError("the model's feature list differs from FEATURES") trained = {name: sorted(values) for name, values in metadata.categories.items()} if trained != {name: sorted(values) for name, values in categories.items()}: raise ModelLoadError("the model's categories differ from the request schema") for library, saved, running in [ ("sklearn", metadata.sklearn_version, sklearn.__version__), ("lightgbm", metadata.lightgbm_version, lightgbm.__version__), ]: if saved != running: raise ModelLoadError( f"model saved with {library} {saved}, running {running}" )
try: # only now: unpickling runs code from the file pipeline = joblib.load(model_dir / MODEL_FILE) except Exception as exc: raise ModelLoadError(f"cannot unpickle {MODEL_FILE}") from exc return ChurnModel( pipeline=pipeline, metadata=metadata, sha256=hashes[MODEL_FILE], manifest_sha256=actual_manifest_hash, )- Why the order matters is in module 44: unpickling can run code, so every check runs before
joblib.load(). The checks run from cheap to expensive: the manifest, the hash of each file, then the content of the metadata. ModelMetadatavalidates the types of the metadata, not only its keys. A half-writtenmetadata.jsonor acategorieslist where a dict belongs gives a precise message instead of aKeyErrororAttributeErrorat start-up.load_model()turns every other exception intoModelLoadErrortoo, for example anOSErrorfrom an unreadable file. The service can then always answer 503 instead of crashing.- The version check is strict: a pickle from another scikit-learn or LightGBM version may load and still predict differently. Retrain, or pin the versions (milestone 7).
predict_proba()builds the DataFrame withcolumns=FEATURES, so the column order never depends on the request.astype(float)turnsTrueinto 1.0 andNoneinto NaN, exactly what the model saw in training.
Break a copy of the folder in three ways:
import shutil
from churn_service.model import ModelLoadError, load_model, write_manifestfrom churn_service.schemas import CATEGORIES
release_hash = file_sha256(models / "MANIFEST.sha256")model = load_model(models, CATEGORIES, release_hash)print(model.version, model.threshold, model.manifest_sha256 == release_hash)
def broken_copy(name: str) -> Path: folder = Path("output") / name shutil.rmtree(folder, ignore_errors=True) return Path(shutil.copytree(models, folder))
edited = broken_copy("edited") # someone lowers the threshold by handmeta = json.loads((edited / "metadata.json").read_text())(edited / "metadata.json").write_text(json.dumps(meta | {"threshold": 0.01}))
FILES = ["churn_model.joblib", "metadata.json", "golden_cases.json"]rewritten = broken_copy("rewritten") # ... and also rewrites the manifest(rewritten / "metadata.json").write_text(json.dumps(meta | {"threshold": 0.01}))write_manifest(rewritten, FILES)
half = broken_copy("half") # an interrupted copy, then a fresh manifest(half / "metadata.json").write_text('{"model_name": "churn')write_manifest(half, FILES)
attempts = [ (edited, None), (rewritten, None), (rewritten, release_hash), (half, None), (Path("output/none"), None),]for folder, pinned in attempts: label = folder.name + (" +pin" if pinned else "") try: loaded = load_model(folder, CATEGORIES, pinned) print(f"{label:<14} LOADED, threshold {loaded.threshold}") except ModelLoadError as exc: print(f"{label:<14} {exc}")1.0.0 0.335 Trueedited metadata.json hash mismatch: the file changedrewritten LOADED, threshold 0.01rewritten +pin MANIFEST.sha256 differs from the release hashhalf metadata.json is not valid JSON: EOF while parsing a string at line 1 column 21none not found in output/none: MANIFEST.sha256The hashes catch the edited threshold. The rewritten folder shows the limit of a manifest in the same folder: it loads with a threshold of 0.01 that would flag almost every customer. Only the release hash, kept outside the folder, catches it. The half-written metadata gives a clear message, not a crash.
Reference solution — Milestone 4: Define the request and response contract
"""Request and response models: the public contract of the service."""
from typing import Any, Literal, get_args
from pydantic import BaseModel, ConfigDict, Field
Region = Literal["East", "North", "South", "West"]Plan = Literal["basic", "premium", "standard"]Contract = Literal["month-to-month", "one-year", "two-year"]PaymentMethod = Literal["bank_transfer", "credit_card", "electronic_check", "paypal"]
# The model must have been trained on exactly these values (checked at load).CATEGORIES = { "region": list(get_args(Region)), "plan": list(get_args(Plan)), "contract": list(get_args(Contract)), "payment_method": list(get_args(PaymentMethod)),}
class Customer(BaseModel): """One customer as the CRM sends it. customer_id is echoed, not scored.
Lax mode: pydantic also converts "34" or 34.0 to 34 and "yes", "true", 1 to True. Strict types (StrictInt, StrictBool) would refuse them. """
# Reject unknown fields, and reject inf and NaN in every float field. model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
customer_id: str | None = Field(default=None, pattern=r"^C\d{5}$") age: int = Field(ge=18, le=100) region: Region plan: Plan contract: Contract payment_method: PaymentMethod has_autopay: bool tenure_months: int = Field(ge=0, le=120) monthly_charges: float = Field(gt=0, le=1000) total_charges: float | None = Field(default=None, ge=0, le=120_000) support_tickets: int = Field(ge=0, le=100) logins_last_30d: int = Field(ge=0, le=1000) avg_session_minutes: float = Field(ge=0, le=1440)
def features(self) -> dict[str, Any]: return self.model_dump(exclude={"customer_id"})
def batch_request_model(max_size: int) -> type[BaseModel]: """Return the batch request model with the configured size limit."""
class BatchRequest(BaseModel): model_config = ConfigDict(extra="forbid")
customers: list[Customer] = Field(min_length=1, max_length=max_size)
return BatchRequest
class Prediction(BaseModel): customer_id: str | None churn_probability: float will_churn: bool
class PredictionResponse(Prediction): threshold: float model_version: str
class BatchResponse(BaseModel): model_version: str threshold: float n_customers: int n_flagged: int predictions: list[Prediction]
class Health(BaseModel): status: Literal["ok"] model_version: str
class Live(BaseModel): status: Literal["alive"]
class ModelInfo(BaseModel): model_name: str model_version: str trained_at: str n_train: int sha256: str manifest_sha256: str threshold: float threshold_rule: str features: list[str] metrics: dict[str, float] sklearn_version: str lightgbm_version: str max_batch_size: int
class ErrorDetail(BaseModel): loc: list[str | int] msg: str type: str
class ErrorBody(BaseModel): """Every error answer has this shape, whatever its status code."""
error: str message: str request_id: str details: list[ErrorDetail] | None = NoneCustomerhas the bounds and thecustomer_idpattern of module 44’s request model. New here: theLiteralaliases buildCATEGORIES, and the loader compares it withmetadata["categories"]. So every category that the API accepts is one that the pipeline knows, and a blank or unknown one gets a 422 instead of the pipeline’sValueError.batch_request_model()builds the batch model at start-up with the configured limit. The limit then appears in the published OpenAPI schema (maxItems), so client developers can read it.Predictionis one result in a batch.PredictionResponseadds the threshold and the model version for a single call. The batch answer puts them once at the top.ErrorBodyis the one shape of every error answer. A client needs one error parser, not four.
Send a raw CSV row, as a careless client would:
from churn_service.schemas import Customer, batch_request_model
record = customers.tail(1).to_dict("records")[0] # C05000, a brand-new customertry: Customer.model_validate(record)except ValidationError as exc: for error in exc.errors(): print(error["loc"][0], "->", error["type"])
def to_request(row: dict) -> dict: """Turn a CSV row into a request body: known fields only, null for NaN.""" return { key: None if pd.isna(value) else value for key, value in row.items() if key in Customer.model_fields }
customer = Customer.model_validate(to_request(record))print(customer.customer_id, customer.has_autopay, customer.total_charges)schema = batch_request_model(100).model_json_schema()["properties"]["customers"]print({key: schema[key] for key in ["type", "minItems", "maxItems"]})total_charges -> finite_numbersignup_date -> extra_forbiddenchurned -> extra_forbiddenC05000 True None{'type': 'array', 'minItems': 1, 'maxItems': 100}The raw row fails three times: NaN is not a finite number, and signup_date and churned are not fields of the contract. to_request() is what the CRM team must do on its side. After it, has_autopay 1 becomes True and the NaN becomes None.
Reference solution — Milestone 5: Build the API, its errors and its logs
Middleware is code that runs around every request, before and after the endpoint, whatever the path. Here it gives each request an id, times it and logs it. The path of one request through the service:
sequenceDiagram
participant C as CRM
participant M as Middleware
participant V as Pydantic
participant E as Endpoint
participant P as Pipeline
C->>M: POST /predict/batch
M->>M: request id, start timer
M->>V: JSON body
V-->>M: 422 if invalid
V->>E: list of Customer
E->>P: DataFrame, columns=FEATURES
P-->>E: probabilities
E-->>M: 200, or 503 / 500
M->>M: log status and duration
M-->>C: answer + X-Request-IDStructured logging writes each log line as data (here one JSON object) instead of free text, so a log system can filter by field: event = "prediction_failed" AND model_version = "1.0.0". A request id is a short string that names one request. The service takes it from the X-Request-ID header (or makes one), puts it in every log line of that request and sends it back, so a CRM developer and an operator can talk about the same request.
"""Structured logging: one JSON object per line, with the request id."""
import jsonimport loggingimport sysimport tracebackfrom contextvars import ContextVarfrom datetime import UTC, datetimefrom typing import Any, TextIO
LOGGER_NAME = "churn_service"# Set by the request middleware; every log line of that request carries it.request_id_var: ContextVar[str | None] = ContextVar("request_id", default=None)
class JsonFormatter(logging.Formatter): def format(self, record: logging.LogRecord) -> str: created = datetime.fromtimestamp(record.created, UTC) entry: dict[str, Any] = { "ts": created.isoformat(timespec="milliseconds"), "level": record.levelname, "event": record.getMessage(), } if (request_id := request_id_var.get()) is not None: entry["request_id"] = request_id entry |= getattr(record, "fields", {}) if record.exc_info and record.exc_info[0] is not None: exc_type, _, tb = record.exc_info # The stack (files, lines, code) but not the message, which can # hold input values. entry["exc_type"] = exc_type.__name__ entry["stack"] = "".join(traceback.format_tb(tb)) return json.dumps(entry, default=str)
def log_event( logger: logging.Logger, level: int, event: str, exc_info: BaseException | None = None, **fields: Any,) -> None: """Log an event name plus key-value fields, for example n=3.""" logger.log(level, event, exc_info=exc_info, extra={"fields": fields})
def configure_logging(level: str = "INFO", stream: TextIO | None = None) -> None: """Send the service's log records as JSON lines to stream (default stderr).""" handler = logging.StreamHandler(stream or sys.stderr) handler.setFormatter(JsonFormatter()) logger = logging.getLogger(LOGGER_NAME) logger.handlers[:] = [handler] # calling it twice must not double the lines logger.setLevel(level)request_id_varis aContextVar: a variable with one value per request, even when many requests run at once in threads or tasks. The formatter reads it, so no function needs arequest_idparameter.- An error line carries
exc_typeandstack: the file, line number and code line of each frame, enough to find a bug. It leaves out the exception message on purpose, because a message such asFound unknown categories ['Premium']can hold input values. A traceback never shows local variables.
"""The FastAPI application: endpoints, error answers and request logging.
GET /live 200 while the process runs (liveness)GET /health 200 when a model is loaded, else 503 (readiness)GET /model-info the loaded model's version, hashes, threshold and scoresPOST /predict one customerPOST /predict/batch 1 to max_batch_size customersErrors: 422 invalid input, 503 no model, 500 the model or the code failed."""
import loggingimport reimport timeimport uuidfrom collections.abc import AsyncIterator, Awaitable, Callablefrom contextlib import asynccontextmanagerfrom typing import Annotated, Any
from fastapi import Depends, FastAPI, Request, Responsefrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponsefrom starlette.exceptions import HTTPException as StarletteHTTPException
from . import __version__from .config import Settingsfrom .logging_setup import LOGGER_NAME, log_event, request_id_varfrom .model import ChurnModel, ModelLoadError, load_modelfrom .schemas import ( CATEGORIES, BatchResponse, Customer, ErrorBody, ErrorDetail, Health, Live, ModelInfo, Prediction, PredictionResponse, batch_request_model,)
logger = logging.getLogger(LOGGER_NAME)SAFE_REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{1,64}$")ERROR_DOCS = { 422: "Invalid request: see details", 500: "The model or the service failed", 503: "No model loaded: try another copy, or later",}
def documented(*codes: int) -> dict[int | str, dict[str, Any]]: """The error answers of a route, for the OpenAPI schema.""" return { code: {"model": ErrorBody, "description": ERROR_DOCS[code]} for code in codes }
class ModelUnavailable(Exception): """No model is loaded: answer 503."""
class PredictionFailed(Exception): """The model raised while scoring: answer 500."""
def error_response( request: Request, status_code: int, error: str, message: str, details: list[ErrorDetail] | None = None, headers: dict[str, str] | None = None,) -> JSONResponse: body = ErrorBody( error=error, message=message, request_id=request.state.request_id, details=details, ) return JSONResponse( body.model_dump(exclude_none=True), status_code=status_code, headers=headers )
def score(model: ChurnModel, customers: list[Customer]) -> list[Prediction]: """Score customers with one model call; any model error becomes a 500.""" try: probabilities = model.predict_proba([c.features() for c in customers]) except Exception as exc: raise PredictionFailed(model.version) from exc predictions = [ Prediction( customer_id=customer.customer_id, churn_probability=round(float(p), 4), will_churn=bool(p >= model.threshold), ) for customer, p in zip(customers, probabilities, strict=True) ] log_event( logger, logging.INFO, "predictions", model_version=model.version, n=len(predictions), n_flagged=sum(p.will_churn for p in predictions), ) return predictions
def create_app(settings: Settings | None = None) -> FastAPI: """Build the app. Tests pass their own settings; production reads the env.""" settings = settings or Settings.from_env() BatchRequest = batch_request_model(settings.max_batch_size)
@asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: # A bad model folder does not stop the process: /health answers 503, # so the platform keeps routing to the old version. app.state.model = None try: model = load_model(settings.model_dir, CATEGORIES, settings.model_sha256) except ModelLoadError as exc: log_event(logger, logging.ERROR, "model_load_failed", reason=str(exc)) else: app.state.model = model log_event( logger, logging.INFO, "model_loaded", model_version=model.version, manifest_sha256=model.manifest_sha256[:12], ) yield app.state.model = None
app = FastAPI(title="Churn service", version=__version__, lifespan=lifespan)
@app.middleware("http") async def request_context( request: Request, call_next: Callable[[Request], Awaitable[Response]] ) -> Response: header = request.headers.get("x-request-id", "") request_id = header if SAFE_REQUEST_ID.match(header) else uuid.uuid4().hex request.state.request_id = request_id token = request_id_var.set(request_id) start = time.perf_counter() try: response = await call_next(request) except Exception as exc: # a bug: log it, answer a generic 500 log_event( logger, logging.ERROR, "unhandled_error", exc_info=exc, path=request.url.path, ) response = error_response(request, 500, "internal_error", "internal error") response.headers["X-Request-ID"] = request_id quiet = request.url.path in ("/live", "/health") log_event( logger, logging.DEBUG if quiet else logging.INFO, "request", method=request.method, path=request.url.path, status=response.status_code, duration_ms=round(1000 * (time.perf_counter() - start), 2), ) request_id_var.reset(token) return response
@app.exception_handler(RequestValidationError) async def on_invalid_request( request: Request, exc: RequestValidationError ) -> JSONResponse: details = [ ErrorDetail(loc=list(e["loc"]), msg=e["msg"], type=e["type"]) for e in exc.errors() ] # Log the error types only, never the values (personal data). log_event( logger, logging.WARNING, "validation_failed", n_errors=len(details), types=sorted({d.type for d in details}), ) message = f"{len(details)} invalid field(s)" return error_response(request, 422, "validation_error", message, details)
@app.exception_handler(ModelUnavailable) async def on_no_model(request: Request, exc: ModelUnavailable) -> JSONResponse: return error_response( request, 503, "model_unavailable", str(exc), headers={"Retry-After": "30"} )
@app.exception_handler(PredictionFailed) async def on_model_error(request: Request, exc: PredictionFailed) -> JSONResponse: log_event( logger, logging.ERROR, "prediction_failed", exc_info=exc.__cause__, model_version=str(exc), ) return error_response(request, 500, "prediction_failed", "prediction failed")
@app.exception_handler(StarletteHTTPException) async def on_http_error( request: Request, exc: StarletteHTTPException ) -> JSONResponse: code = exc.status_code return error_response(request, code, f"http_{code}", str(exc.detail))
def get_model(request: Request) -> ChurnModel: model = request.app.state.model if model is None: raise ModelUnavailable("model not loaded") return model
LoadedModel = Annotated[ChurnModel, Depends(get_model)]
@app.get("/live") def live() -> Live: return Live(status="alive")
@app.get("/health", responses=documented(503)) def health(model: LoadedModel) -> Health: return Health(status="ok", model_version=model.version)
@app.get("/model-info", responses=documented(503)) def model_info(model: LoadedModel) -> ModelInfo: meta = model.metadata return ModelInfo( model_name=meta.model_name, model_version=meta.model_version, trained_at=meta.trained_at, n_train=meta.n_train, sha256=model.sha256, manifest_sha256=model.manifest_sha256, threshold=meta.threshold, threshold_rule=meta.threshold_rule, features=meta.features, metrics=meta.metrics, sklearn_version=meta.sklearn_version, lightgbm_version=meta.lightgbm_version, max_batch_size=settings.max_batch_size, )
@app.post("/predict", responses=documented(422, 500, 503)) def predict(customer: Customer, model: LoadedModel) -> PredictionResponse: prediction = score(model, [customer])[0] return PredictionResponse( **prediction.model_dump(), threshold=model.threshold, model_version=model.version, )
@app.post("/predict/batch", responses=documented(422, 500, 503)) def predict_batch(body: BatchRequest, model: LoadedModel) -> BatchResponse: predictions = score(model, body.customers) return BatchResponse( model_version=model.version, threshold=model.threshold, n_customers=len(predictions), n_flagged=sum(p.will_churn for p in predictions), predictions=predictions, )
return appWhere each acceptance criterion of the milestone lives:
| Criterion | Code |
|---|---|
| one app per settings object | create_app(); the batch model comes from batch_request_model(settings.max_batch_size) |
| a bad folder gives 503, the process stays up | lifespan() catches ModelLoadError; get_model() raises ModelUnavailable |
| liveness and readiness | /live always answers 200; /health answers 200 only with a model |
| a request id and one log line per request | the request_context middleware and request_id_var |
| one error shape, documented | error_response(), the four exception handlers and documented() in each route’s responses= |
| 500 without internal details, with the stack in the log | score() raises PredictionFailed; on_model_error() and the middleware log with exc_info= |
| no customer values in the logs | on_invalid_request() logs the error types only; score() logs counts |
Design decisions:
- Start without a model. Module 44 stops the service when the model fails its checks, so a bad model never takes traffic. Here the process stays up and answers 503, for the same reason: the platform sends no traffic to a copy that is not ready, and it keeps the old copies running. What changes is the diagnosis: the reason is in a
model_load_failedlog line, and/livestill works, so the platform does not restart the copy in a loop. - Liveness and readiness. A liveness check asks “is the process alive?”; a failure makes the platform restart it. A readiness check asks “can it serve now?”; a failure only stops traffic to it.
/liveis the liveness check and/healthis the readiness check. Never use/healthas a liveness check: a missing model would then restart the copy forever. - 503 says little. The client learns only “model not loaded”, not where the files live.
Retry-After: 30tells it to try again later, or another copy. This copy does not load the model again by itself: an operator must fix the folder and restart it. - Untrusted headers. A request id that is not 1–64 safe characters is replaced, so a client cannot inject line breaks into the logs.
/liveand/healthlog at DEBUG: the platform calls them every few seconds, and those lines would drown the useful ones.
"""The process entry point: uvicorn churn_service.main:app
Reads the settings from the environment, sets up JSON logging and builds theapp. Tests import create_app() instead, with their own settings."""
import logging
from .app import create_app, loggerfrom .config import Settings, unknown_settingsfrom .logging_setup import configure_logging, log_event
settings = Settings.from_env()configure_logging(settings.log_level)if names := unknown_settings(): log_event(logger, logging.WARNING, "unknown_settings", names=names)app = create_app(settings)Only main.py reads the real environment and sets up logging. Importing churn_service.app has no side effects.
Now call the app in memory with TestClient, as in module 44. An ExitStack keeps the client open across the next blocks.
import iofrom contextlib import ExitStack
from fastapi.testclient import TestClient
from churn_service.app import create_appfrom churn_service.logging_setup import configure_logging
log_stream = io.StringIO()configure_logging("INFO", stream=log_stream) # JSON lines go here, not to stderrsettings = Settings(model_dir=models, model_sha256=release_hash, max_batch_size=100)app = create_app(settings)stack = ExitStack()client = stack.enter_context(TestClient(app)) # runs the lifespan: loads the model
print(client.get("/live").json(), client.get("/health").json())info = client.get("/model-info").json()print({k: info[k] for k in ["model_name", "n_train", "threshold", "max_batch_size"]})print({k: info["metrics"][k] for k in ["test_roc_auc", "test_pr_auc", "test_brier"]})error_schema = client.get("/openapi.json").json()["paths"]["/predict"]["post"]print(sorted(error_schema["responses"]))assert info["manifest_sha256"] == release_hash{'status': 'alive'} {'status': 'ok', 'model_version': '1.0.0'}{'model_name': 'churn-lgbm', 'n_train': 3750, 'threshold': 0.335, 'max_batch_size': 100}{'test_roc_auc': 0.8368, 'test_pr_auc': 0.583, 'test_brier': 0.1129}['200', '422', '500', '503']/model-info answers the first question of every incident: which model is live? Its manifest_sha256 must equal the release hash of the folder that you meant to deploy. The OpenAPI schema lists the error answers of /predict with the ErrorBody shape.
The agent screen: one customer.
risky = { "customer_id": "C09999", "age": 34, "region": "East", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": False, "tenure_months": 3, "monthly_charges": 99.5, "total_charges": 298.5, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5,}response = client.post("/predict", json=risky, headers={"X-Request-ID": "crm-7f3a"})print(response.status_code, response.headers["X-Request-ID"])for key, value in response.json().items(): print(f"{key:>17}: {value}")assert response.json()["will_churn"]200 crm-7f3a customer_id: C09999churn_probability: 0.882 will_churn: True threshold: 0.335 model_version: 1.0.0The nightly job: every customer, in batches. The client reads the limit from /model-info and splits the 5,000 customers into batches.
requests = [to_request(row) for row in customers.to_dict("records")]limit = info["max_batch_size"]predictions = []for start in range(0, len(requests), limit): response = client.post( "/predict/batch", json={"customers": requests[start : start + limit]} ) assert response.status_code == 200 predictions += response.json()["predictions"]
scores = pd.DataFrame(predictions)budget = 1_000 # calls per month, from Capstone 4call_list = ( scores[scores["will_churn"]] .sort_values(["churn_probability", "customer_id"], ascending=[False, True]) .head(budget))print(f"{len(requests) // limit} requests, {len(scores):,} customers scored")print(f"flagged {scores['will_churn'].sum():,} ({scores['will_churn'].mean():.1%})")print(f"call list: {len(call_list):,} customers (budget {budget:,})")print(call_list.head(3).to_string(index=False))assert len(scores) == len(customers)assert call_list["churn_probability"].min() >= info["threshold"]50 requests, 5,000 customers scoredflagged 1,012 (20.2%)call list: 1,000 customers (budget 1,000)customer_id churn_probability will_churn C04816 0.9003 True C04381 0.8808 True C04795 0.8752 True50 requests score every customer. These are the same customers that the model was built and tested on, so this run is a demo of the job, not a measure of quality. More customers are above the threshold than the budget allows, so the team calls the 1,000 with the highest scores, as Capstone 4 planned. The table is sorted with a tie-breaker, so the order is stable.
Invalid requests.
too_big = client.post("/predict/batch", json={"customers": requests[: limit + 1]})bad_body = risky | {"age": 12, "plan": "Premium", "region": "", "coupon": "SAVE10"}bad = client.post("/predict", json=bad_body)for response in [too_big, bad]: body = response.json() print(response.status_code, body["error"], "|", body["message"]) for detail in body["details"]: print(" ", detail["loc"], detail["type"])422 validation_error | 1 invalid field(s) ['body', 'customers'] too_long422 validation_error | 4 invalid field(s) ['body', 'age'] greater_than_equal ['body', 'region'] literal_error ['body', 'plan'] literal_error ['body', 'coupon'] extra_forbiddenThe batch of 101 is refused as a whole, with one clear reason. The second request has four problems, and the client gets all four at once, each with its location. The blank region never reaches the pipeline.
A deploy without the model file.
no_model_dir = broken_copy("no-model")(no_model_dir / "churn_model.joblib").unlink() # the deploy forgot one file
with TestClient(create_app(Settings(model_dir=no_model_dir))) as other: live = other.get("/live") health = other.get("/health") predict = other.post("/predict", json=risky)print("/live", live.status_code, "| /health", health.status_code)print("Retry-After:", health.headers["Retry-After"], "|", health.json()["message"])print(predict.status_code, predict.json()["error"], "|", predict.json()["message"])stack.close() # stop the first client: runs the shutdown part of the lifespanassert health.status_code == predict.status_code == 503/live 200 | /health 503Retry-After: 30 | model not loaded503 model_unavailable | model not loadedThe process is alive, but it is not ready. The answers say only “model not loaded”. The reason is in the log, below.
The logs. Every block above wrote JSON lines into log_stream. Count them by event, then show the lines of the agent-screen request and every warning and error. The timestamps and durations change on every run, so this printout drops them.
from collections import Counter
events = [json.loads(line) for line in log_stream.getvalue().splitlines()]for name, count in sorted(Counter(e["event"] for e in events).items()): print(f"{name:<18} {count:>3}")print()hidden = {"ts", "duration_ms", "request_id", "level", "event"}for event in events: if event.get("request_id") == "crm-7f3a" or event["level"] != "INFO": fields = " ".join( f"{k}={','.join(v) if isinstance(v, list) else v}" for k, v in event.items() if k not in hidden ) print(f"{event['level']:<7} {event['event']:<17} {fields}")model_load_failed 1model_loaded 1predictions 51request 56validation_failed 2
INFO predictions model_version=1.0.0 n=1 n_flagged=1INFO request method=POST path=/predict status=200WARNING validation_failed n_errors=1 types=too_longWARNING validation_failed n_errors=4 types=extra_forbidden,greater_than_equal,literal_errorERROR model_load_failed reason=not found in output/no-model: churn_model.joblib56 requests were logged; the /live and /health calls are at DEBUG and do not appear. Each warning holds only the error types. The model_load_failed line names the missing file for the operator. In production, the same lines go to stderr, and a log system such as Loki, Elasticsearch or CloudWatch indexes their fields.
Reference solution — Milestone 6: Test the service
pyproject.toml names the project and tells pytest where the tests are. pythonpath = ["."] lets the tests import churn_service without an install. The [tool.ruff] tables pin the lint rules in the project, so ruff check gives the same result on every machine and with every ruff version.
[project]name = "churn-service"version = "1.0.0"description = "Serve the churn model over HTTP."requires-python = ">=3.12"
[tool.pytest]testpaths = ["tests"]pythonpath = ["."]strict = true
[tool.ruff]line-length = 88target-version = "py312"
[tool.ruff.lint]select = ["E", "F", "W", "I", "B", "UP"]The fixtures use the real model folder. A test that breaks a model works on a copy in tmp_path.
"""Shared fixtures. They use the real model folder: run python train_churn.pyand python package_model.py first."""
import jsonimport shutilfrom collections.abc import Iteratorfrom pathlib import Pathfrom typing import Any
import pytestfrom fastapi.testclient import TestClient
from churn_service.app import create_appfrom churn_service.config import Settingsfrom churn_service.model import MANIFEST_FILE
MODEL_DIR = Path(__file__).resolve().parents[1] / "models"MAX_BATCH = 8
@pytest.fixture(scope="session")def model_dir() -> Path: if not (MODEL_DIR / MANIFEST_FILE).is_file(): pytest.fail("no packaged model in models/: see the conftest docstring") return MODEL_DIR
@pytest.fixture(scope="session")def golden(model_dir: Path) -> list[dict[str, Any]]: return json.loads((model_dir / "golden_cases.json").read_text())
@pytest.fixture(scope="module")def client(model_dir: Path) -> Iterator[TestClient]: """One app for a whole test file; "with" runs the lifespan (model load).""" app = create_app(Settings(model_dir=model_dir, max_batch_size=MAX_BATCH)) with TestClient(app) as test_client: yield test_client
@pytest.fixturedef model_copy(model_dir: Path, tmp_path: Path) -> Path: """A private copy of the model folder that a test may break.""" return Path(shutil.copytree(model_dir, tmp_path / "models"))
@pytest.fixturedef customer() -> dict[str, Any]: """A valid request body: a new, risky customer.""" return { "customer_id": "C09999", "age": 34, "region": "East", "plan": "premium", "contract": "month-to-month", "payment_method": "electronic_check", "has_autopay": False, "tenure_months": 3, "monthly_charges": 99.5, "total_charges": 298.5, "support_tickets": 4, "logins_last_30d": 2, "avg_session_minutes": 6.5, }tests/__init__.py is an empty file. It makes tests a package, so the test files can import MAX_BATCH and the breakages with relative imports.
tests/breakages.py collects the ways a model folder breaks in real life. The loader tests and the API tests share it.
"""Ways a model folder breaks in real life, for the loader and API tests.
Each entry: (function that breaks a copied folder, expected message regex)."Rehashed" cases also rewrite the manifest, like a buggy release job would,so the hash check passes and the later checks must catch the problem."""
import jsonfrom collections.abc import Callablefrom pathlib import Path
from churn_service.model import write_manifestfrom churn_service.schemas import CATEGORIES
FILES = ["churn_model.joblib", "metadata.json", "golden_cases.json"]
def append_byte(path: Path) -> None: """Change a file the way an interrupted copy or a bad upload can.""" path.write_bytes(path.read_bytes() + b"\0")
def rehashed(change: Callable[[Path], object]) -> Callable[[Path], None]: def apply(folder: Path) -> None: change(folder) write_manifest(folder, FILES)
return apply
def edit_metadata(**changes: object) -> Callable[[Path], None]: def apply(folder: Path) -> None: path = folder / "metadata.json" path.write_text(json.dumps(json.loads(path.read_text()) | changes))
return apply
def write(name: str, text: str) -> Callable[[Path], None]: return lambda folder: (folder / name).write_text(text)
BREAKAGES: dict[str, tuple[Callable[[Path], object], str]] = { "manifest missing": ( lambda d: (d / "MANIFEST.sha256").unlink(), r"not found in .*: MANIFEST\.sha256$", ), "manifest empty": (write("MANIFEST.sha256", ""), "is empty"), "manifest truncated": (write("MANIFEST.sha256", "8dede2"), "line 1 is not"), "model file missing": ( lambda d: (d / "churn_model.joblib").unlink(), r"not found in .*: churn_model\.joblib$", ), "model file changed": ( lambda d: append_byte(d / "churn_model.joblib"), "churn_model.joblib hash mismatch", ), "threshold edited": ( edit_metadata(threshold=0.01), "metadata.json hash mismatch", ), "metadata not JSON": ( rehashed(write("metadata.json", '{"model_name": "churn')), "metadata.json is not valid JSON: EOF while parsing", ), "metadata wrong type": ( rehashed(edit_metadata(categories=["East", "West"])), "invalid at categories: Input should be an object", ), "threshold out of range": ( rehashed(edit_metadata(threshold=1.5)), "invalid at threshold: Input should be less than 1", ), "other scikit-learn": ( rehashed(edit_metadata(sklearn_version="1.0.0")), "sklearn 1.0.0", ), "other features": (rehashed(edit_metadata(features=["age"])), "feature list"), "other categories": ( rehashed(edit_metadata(categories=CATEGORIES | {"plan": ["gold"]})), "categories differ", ), "model not a pickle": ( rehashed(write("churn_model.joblib", "not a pickle")), "cannot unpickle churn_model.joblib", ),}from pathlib import Path
import pytestfrom pydantic import ValidationError
from churn_service.config import Settings, unknown_settings
def test_defaults_without_variables() -> None: settings = Settings.from_env({}) assert settings.model_dir == Path("models") assert settings.model_sha256 is None assert settings.max_batch_size == 100 assert settings.log_level == "INFO"
def test_variables_override_defaults() -> None: env = { "CHURN_MODEL_DIR": "/srv/models/1.0.0", "CHURN_MODEL_SHA256": "ab" * 32, "CHURN_MAX_BATCH_SIZE": "250", "HOME": "/home/app", # not ours: ignored } settings = Settings.from_env(env) assert settings.model_dir == Path("/srv/models/1.0.0") assert settings.model_sha256 == "ab" * 32 assert settings.max_batch_size == 250
@pytest.mark.parametrize( "env", [ {"CHURN_MAX_BATCH_SIZE": "0"}, {"CHURN_MAX_BATCH_SIZE": "many"}, {"CHURN_LOG_LEVEL": "LOUD"}, {"CHURN_MODEL_SHA256": "8deded"}, # a truncated hash ],)def test_invalid_settings_stop_the_service(env: dict[str, str]) -> None: with pytest.raises(ValidationError): Settings.from_env(env)
def test_unknown_names_are_listed_not_fatal() -> None: env = { "CHURN_MAX_BATCH": "50", # a typo "CHURN_PORT": "tcp://10.0.0.7:80", # added by Kubernetes "CHURN_SERVICE_HOST": "10.0.0.7", "CHURN_LOG_LEVEL": "DEBUG", } assert Settings.from_env(env).max_batch_size == 100 unknown = unknown_settings(env) assert unknown == ["CHURN_MAX_BATCH", "CHURN_PORT", "CHURN_SERVICE_HOST"]from pathlib import Path
import pytest
from churn_service import model as model_modulefrom churn_service.model import ( CATEGORICAL, FEATURES, NUMERIC, ModelLoadError, file_sha256, load_model, write_manifest,)from churn_service.schemas import CATEGORIES
from .breakages import BREAKAGES, FILES, append_byte, edit_metadata
def test_load_checks_and_returns_the_model(model_dir: Path) -> None: model = load_model(model_dir, CATEGORIES) assert model.version == "1.0.0" assert model.threshold == 0.335 assert model.metadata.threshold_rule.startswith("break-even")
def test_service_and_training_share_the_columns() -> None: import train_churn # Capstone 4's script, in the same project folder
assert (FEATURES, CATEGORICAL, NUMERIC) == ( train_churn.FEATURES, train_churn.CATEGORICAL, train_churn.NUMERIC, )
@pytest.mark.parametrize("breakage", BREAKAGES, ids=list(BREAKAGES))def test_bad_model_folder_is_refused(model_copy: Path, breakage: str) -> None: break_it, message = BREAKAGES[breakage] break_it(model_copy) with pytest.raises(ModelLoadError, match=message): load_model(model_copy, CATEGORIES)
def test_release_hash_catches_a_rewritten_manifest( model_dir: Path, model_copy: Path) -> None: release_hash = file_sha256(model_dir / "MANIFEST.sha256") assert load_model(model_copy, CATEGORIES, release_hash).version == "1.0.0" edit_metadata(threshold=0.01)(model_copy) write_manifest(model_copy, FILES) # whoever edited the file fixed the manifest assert load_model(model_copy, CATEGORIES).threshold == 0.01 # not pinned: loads with pytest.raises(ModelLoadError, match="differs from the release hash"): load_model(model_copy, CATEGORIES, release_hash)
def test_hash_is_checked_before_unpickling( model_copy: Path, monkeypatch: pytest.MonkeyPatch) -> None: def never(path: Path) -> None: raise AssertionError("joblib.load ran on an unverified file")
monkeypatch.setattr(model_module.joblib, "load", never) append_byte(model_copy / "churn_model.joblib") with pytest.raises(ModelLoadError, match="hash mismatch"): load_model(model_copy, CATEGORIES)test_hash_is_checked_before_unpickling replaces joblib.load with a function that fails the test. It proves the order of the checks, not only the result.
import ioimport jsonimport loggingfrom collections.abc import Callable, Iteratorfrom dataclasses import replacefrom pathlib import Pathfrom typing import Any
import pytestfrom fastapi.testclient import TestClient
from churn_service.app import create_appfrom churn_service.config import Settingsfrom churn_service.logging_setup import LOGGER_NAME, configure_logging
from .breakages import BREAKAGESfrom .conftest import MAX_BATCH
def test_health_reports_the_model(client: TestClient) -> None: assert client.get("/live").json() == {"status": "alive"} response = client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "ok", "model_version": "1.0.0"}
def test_model_info_identifies_the_artifact( client: TestClient, model_dir: Path) -> None: info = client.get("/model-info").json() manifest = (model_dir / "MANIFEST.sha256").read_text() assert info["sha256"] == manifest.split()[0] # first line: the model assert info["threshold"] == 0.335 assert info["max_batch_size"] == MAX_BATCH assert len(info["features"]) == 12
def test_predict_one_customer(client: TestClient, customer: dict[str, Any]) -> None: response = client.post("/predict", json=customer) assert response.status_code == 200 body = response.json() assert body["customer_id"] == "C09999" assert 0.0 <= body["churn_probability"] <= 1.0 assert body["will_churn"] == (body["churn_probability"] >= body["threshold"])
def test_request_id_is_echoed_or_created( client: TestClient, customer: dict[str, Any]) -> None: echoed = client.post("/predict", json=customer, headers={"X-Request-ID": "abc-1"}) assert echoed.headers["X-Request-ID"] == "abc-1" unsafe = client.post("/predict", json=customer, headers={"X-Request-ID": "a b\n"}) assert len(unsafe.headers["X-Request-ID"]) == 32 # replaced by a new uuid4 hex
def test_customer_id_and_total_charges_are_optional( client: TestClient, customer: dict[str, Any]) -> None: del customer["customer_id"], customer["total_charges"] response = client.post("/predict", json=customer | {"tenure_months": 0}) assert response.status_code == 200 assert response.json()["customer_id"] is None
@pytest.mark.parametrize( ("field", "value", "error_type"), [ ("age", 12, "greater_than_equal"), ("plan", "gold", "literal_error"), ("monthly_charges", -5, "greater_than"), ("tenure_months", "ten", "int_parsing"), ("total_charges", "Infinity", "finite_number"), ("customer_id", "12345", "string_pattern_mismatch"), ("region", "", "literal_error"), # blank: the pipeline would raise ("region", None, "literal_error"), ("coupon", "SAVE10", "extra_forbidden"), ],)def test_invalid_field_gives_422( client: TestClient, customer: dict[str, Any], field: str, value: object, error_type: str,) -> None: response = client.post("/predict", json=customer | {field: value}) assert response.status_code == 422 body = response.json() assert body["error"] == "validation_error" assert body["details"] == [ {"loc": ["body", field], "msg": body["details"][0]["msg"], "type": error_type} ]
@pytest.mark.parametrize( ("field", "value"), [("has_autopay", "yes"), ("has_autopay", 1), ("age", "34")])def test_lax_mode_converts_simple_types( client: TestClient, customer: dict[str, Any], field: str, value: object) -> None: """Characterization: the contract accepts these conversions on purpose.""" assert client.post("/predict", json=customer | {field: value}).status_code == 200
def test_openapi_documents_the_error_shape(client: TestClient) -> None: responses = client.get("/openapi.json").json()["paths"]["/predict"]["post"] for code in ["422", "500", "503"]: schema = responses["responses"][code]["content"]["application/json"] assert schema["schema"]["$ref"].endswith("/ErrorBody")
def test_malformed_json_gives_422(client: TestClient) -> None: response = client.post( "/predict", content=b"{not json", headers={"Content-Type": "application/json"} ) assert response.status_code == 422 assert response.json()["details"][0]["type"] == "json_invalid"
def test_batch_keeps_the_input_order( client: TestClient, customer: dict[str, Any]) -> None: ids = ["C00003", "C00001", "C00002"] batch = {"customers": [customer | {"customer_id": i} for i in ids]} body = client.post("/predict/batch", json=batch).json() assert [p["customer_id"] for p in body["predictions"]] == ids assert body["n_customers"] == 3 assert body["n_flagged"] == sum(p["will_churn"] for p in body["predictions"])
@pytest.mark.parametrize( ("size", "status"), [(1, 200), (MAX_BATCH, 200), (MAX_BATCH + 1, 422), (0, 422)])def test_batch_size_limits( client: TestClient, customer: dict[str, Any], size: int, status: int) -> None: response = client.post("/predict/batch", json={"customers": [customer] * size}) assert response.status_code == status
def test_one_bad_customer_rejects_the_batch_and_names_it( client: TestClient, customer: dict[str, Any]) -> None: batch = {"customers": [customer, customer | {"age": 150}]} response = client.post("/predict/batch", json=batch) assert response.status_code == 422 assert response.json()["details"][0]["loc"] == ["body", "customers", 1, "age"]
def test_missing_model_gives_503_everywhere( tmp_path: Path, customer: dict[str, Any]) -> None: app = create_app(Settings(model_dir=tmp_path)) # an empty folder with TestClient(app) as client: # the service still starts assert client.get("/live").status_code == 200 health = client.get("/health") assert health.status_code == 503 assert health.headers["Retry-After"] == "30" assert health.json()["message"] == "model not loaded" # no paths assert client.get("/model-info").status_code == 503 assert client.post("/predict", json=customer).status_code == 503 batch = {"customers": [customer]} assert client.post("/predict/batch", json=batch).status_code == 503
@pytest.mark.parametrize( "breakage", ["manifest empty", "metadata not JSON", "model not a pickle"])def test_broken_model_folder_gives_503(model_copy: Path, breakage: str) -> None: BREAKAGES[breakage][0](model_copy) with TestClient(create_app(Settings(model_dir=model_copy))) as client: assert client.get("/health").status_code == 503
@pytest.fixturedef log_lines() -> Iterator[Callable[[], list[dict[str, Any]]]]: """Capture the service's JSON lines; restore the logger afterwards.""" logger = logging.getLogger(LOGGER_NAME) saved = logger.handlers[:], logger.level stream = io.StringIO() configure_logging("INFO", stream=stream) yield lambda: [json.loads(line) for line in stream.getvalue().splitlines()] logger.handlers[:] = saved[0] logger.setLevel(saved[1])
def test_logs_carry_the_request_id_and_no_values( client: TestClient, customer: dict[str, Any], log_lines: Callable[[], list[dict[str, Any]]],) -> None: secret = customer | {"customer_id": "C31337", "monthly_charges": 987.65} client.post("/predict", json=secret, headers={"X-Request-ID": "ok-1"}) bad = secret | {"plan": "SECRET-PLAN", "age": 777} client.post("/predict", json=bad, headers={"X-Request-ID": "bad-1"}) lines = log_lines() assert {line["event"] for line in lines} == { "predictions", "request", "validation_failed", } assert all(line["request_id"] in ("ok-1", "bad-1") for line in lines) text = json.dumps(lines) for value in ["C31337", "987.65", "SECRET-PLAN", "777"]: assert value not in text
class BrokenPipeline: def predict_proba(self, X: object) -> None: raise ValueError("corrupted model")
def test_model_failure_gives_500_and_an_error_log( model_dir: Path, customer: dict[str, Any], caplog: pytest.LogCaptureFixture) -> None: app = create_app(Settings(model_dir=model_dir)) with TestClient(app) as client: app.state.model = replace(app.state.model, pipeline=BrokenPipeline()) response = client.post("/predict", json=customer) assert response.status_code == 500 assert response.json()["error"] == "prediction_failed" assert "corrupted" not in response.text # no internal details for the client [record] = [r for r in caplog.records if r.getMessage() == "prediction_failed"] assert record.levelno == logging.ERROR assert record.exc_info is not None and record.exc_info[0] is ValueError
def test_unexpected_bug_gives_generic_500( model_dir: Path, caplog: pytest.LogCaptureFixture) -> None: app = create_app(Settings(model_dir=model_dir))
@app.get("/boom") def boom() -> None: raise RuntimeError("bug")
with TestClient(app) as client: response = client.get("/boom") assert response.status_code == 500 assert response.json()["error"] == "internal_error" [record] = [r for r in caplog.records if r.getMessage() == "unhandled_error"] assert record.exc_info is not None and record.exc_info[0] is RuntimeError
def test_unknown_path_uses_the_error_shape(client: TestClient) -> None: response = client.get("/predictions") assert response.status_code == 404 assert set(response.json()) == {"error", "message", "request_id"}A golden test compares a result with a stored, known-good result. Here, the stored results are the scores that package_model.py computed from the CSV rows.
"""Golden predictions: the service must give the scores that training gave.
package_model.py scored these customers straight from the CSV rows. The service getsthem as JSON (0/1 for has_autopay, null for a missing total), so any skewbetween training and serving input handling shows up here."""
from typing import Any
import pytestfrom fastapi.testclient import TestClient
def test_golden_cases_through_the_batch_endpoint( client: TestClient, golden: list[dict[str, Any]]) -> None: batch = {"customers": [case["customer"] for case in golden]} body = client.post("/predict/batch", json=batch).json() for case, prediction in zip(golden, body["predictions"], strict=True): assert prediction["customer_id"] == case["customer"]["customer_id"] # The service rounds to 4 decimals: allow half a unit of rounding. assert prediction["churn_probability"] == pytest.approx( case["churn_probability"], abs=5e-5 ) assert prediction["will_churn"] == case["will_churn"]
def test_single_and_batch_endpoints_agree( client: TestClient, golden: list[dict[str, Any]]) -> None: single = [ client.post("/predict", json=case["customer"]).json()["churn_probability"] for case in golden ] batch = {"customers": [case["customer"] for case in golden]} predictions = client.post("/predict/batch", json=batch).json()["predictions"] assert single == [p["churn_probability"] for p in predictions]import jsonimport loggingimport sys
from churn_service.logging_setup import JsonFormatter, request_id_var
def make_record(exc_info: object = None) -> logging.LogRecord: record = logging.getLogger("churn_service").makeRecord( "churn_service", logging.ERROR, __file__, 1, "predictions", (), exc_info ) record.fields = {"n": 3} return record
def test_log_lines_are_json_with_the_request_id() -> None: token = request_id_var.set("req-7") try: line = JsonFormatter().format(make_record()) finally: request_id_var.reset(token) entry = json.loads(line) assert entry["event"] == "predictions" assert entry["request_id"] == "req-7" assert entry["n"] == 3
def test_errors_log_the_stack_but_not_the_message() -> None: age = 700 + 77 # computed, so the value is not in the source line either try: raise ValueError(f"customer C00042 has age {age}") except ValueError: entry = json.loads(JsonFormatter().format(make_record(sys.exc_info()))) assert entry["exc_type"] == "ValueError" assert "test_errors_log_the_stack_but_not_the_message" in entry["stack"] assert "777" not in json.dumps(entry)pytest -q............................................................. [100%]61 passed in 0.33sruff check .All checks passed!| The test proves that… | How |
|---|---|
| settings have defaults and overrides; bad values stop the service; unknown names are listed | Settings.from_env() and unknown_settings() with plain dicts |
each kind of broken model folder is refused with ModelLoadError, before unpickling |
13 breakages on a copy in tmp_path; monkeypatch on joblib.load |
| a rewritten manifest loads, unless the release hash is pinned | test_release_hash_catches_a_rewritten_manifest |
the service and train_churn.py use the same columns |
test_service_and_training_share_the_columns |
| invalid and blank fields give 422 with their location and type; lax mode converts on purpose | 9 parametrized invalid cases, 3 lax-mode cases, malformed JSON |
| the batch limit holds at 1, the maximum, the maximum + 1 and 0 | a parametrized test on an app with MAX_BATCH = 8 |
a missing or broken model gives 503 on every endpoint, and /live still answers |
an app on an empty folder and on 3 broken folders |
| a failure gives a generic 500 and an ERROR log line with the stack | a stand-in pipeline, a route that raises, caplog |
| log lines carry the request id and no customer values | test_logs_carry_the_request_id_and_no_values |
| the API gives the training scores and decisions | the golden cases through /predict/batch and /predict |
The golden test catches a training–serving skew. For example, if predict_proba() in model.py filled the missing total_charges with 0 instead of NaN, every other test would still pass, but the golden case C04991 would fail. Try it.
Reference solution — Milestone 7: Ship it: container, run command and runbook
The runtime needs fewer packages than the course. The test tools stay out of the image; install them where the tests run: pip install pytest==9.2.0 httpx2==2.16.0.
# Runtime dependencies of the churn service. These pins cover the direct# dependencies; the model loads only with the scikit-learn and LightGBM# versions that trained it. For a fully repeatable image, also pin the# indirect ones (starlette, scipy, pydantic-core, ...) in a lock file made# with `uv pip compile` or `pip freeze`.fastapi==0.162.2uvicorn==0.54.0pydantic==2.14.3numpy==2.5.4pandas==3.1.1scikit-learn==1.9.1lightgbm==4.7.0joblib==1.6.0A Dockerfile is the recipe for a container image: a file system with Python, the dependencies, the code and the model, which runs the same way on a laptop and on a server. The build context is the folder that docker build sends to Docker; .dockerignore keeps the customer data and the virtual environment out of it.
# Keep the build context small and free of personal data: the image needs# only requirements.txt, churn_service/ and models/.data/output/tests/.venv/.git/**/__pycache__/.pytest_cache/.ruff_cache/*.ipynb# Image of the churn service with the packaged model inside.# Build: docker build -t churn-service:1.0.0 .# For repeatable builds, pin the base image by digest: python:3.13-slim@sha256:...FROM python:3.13-slim
# LightGBM needs the OpenMP runtime, which the slim image does not include.RUN apt-get update \ && apt-get install -y --no-install-recommends libgomp1 \ && rm -rf /var/lib/apt/lists/*
# OMP_NUM_THREADS=1: one thread per prediction; uvicorn workers use the cores.ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ OMP_NUM_THREADS=1 \ CHURN_MODEL_DIR=/app/models \ CHURN_MAX_BATCH_SIZE=100 \ CHURN_LOG_LEVEL=INFO
WORKDIR /app# Dependencies first: Docker reuses this layer while requirements.txt is unchanged.COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY churn_service/ churn_service/COPY models/ models/
# Never run a network service as root.RUN useradd --create-home --uid 10001 appUSER app
EXPOSE 8000HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \ CMD ["python", "-c", "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/live')"]CMD ["uvicorn", "churn_service.main:app", "--host", "0.0.0.0", "--port", "8000", \ "--workers", "2", "--no-access-log"]- The model is inside the image, so the image tag names one code version and one model version together. Rolling back means running the previous tag.
requirements.txtis copied and installed before the code. A code change then rebuilds only the last layers, in seconds.- The
HEALTHCHECKcalls/live, Docker’s liveness check. The platform’s readiness check calls/health. OMP_NUM_THREADS=1: LightGBM uses every CPU core for each prediction call by default. With two workers and FastAPI’s thread pool, the threads would fight for the cores. One thread per call and one worker per core keep the latency steady.--no-access-logturns off uvicorn’s own access lines: the service already logs every request as JSON, with more fields.
Run it locally, from the project folder, after the two scripts of milestone 1:
uvicorn churn_service.main:app --reload # development: restarts on code changesOMP_NUM_THREADS=1 CHURN_MODEL_SHA256=<release hash> \ uvicorn churn_service.main:app --host 0.0.0.0 --port 8000 \ --workers 2 --no-access-log # like productionEach of the two workers is a separate process with its own copy of the model. FastAPI also publishes the contract as interactive documentation at http://127.0.0.1:8000/docs. uvicorn does not limit the size of a request body, and FastAPI reads the whole body before it checks the batch limit. So the proxy or the platform in front of the service must cap the body size, for example at 1 MB.
Build and run the image:
docker build -t churn-service:1.0.0 .docker run -d --name churn -p 8000:8000 -e CHURN_MODEL_SHA256=<release hash> churn-service:1.0.0docker inspect --format '{{.State.Health.Status}}' churn # starting, then healthycurl -s http://127.0.0.1:8000/model-infodocker logs churn | tail -n 5 # the JSON linesThe release check. Before a new copy (the canary, below) takes traffic, release_check.py checks it: ready, the expected folder, the golden scores, and a quality gate against the live copy.
"""Check a running churn service before it takes traffic.
Usage: python release_check.py URL [--models DIR] [--live URL] [--max-auc-drop X] URL the new copy (the canary), for example http://10.0.0.8:8000 --live the copy that serves traffic now: its ROC-AUC is the bar to clearExit code 0 when every check passes, 1 otherwise. Needs httpx."""
import argparseimport jsonimport sysfrom pathlib import Pathfrom typing import Any, Protocol
from churn_service.model import GOLDEN_FILE, MANIFEST_FILE, file_sha256
class Client(Protocol): """httpx.Client and fastapi.testclient.TestClient both fit."""
def get(self, url: str) -> Any: ... def post(self, url: str, *, json: Any) -> Any: ...
def run_checks( client: Client, models: Path, live_info: dict[str, Any] | None = None, max_auc_drop: float = 0.01,) -> list[tuple[str, bool, str]]: """Return (check, passed, detail) for each release check.""" checks = [] health = client.get("/health") checks.append(("health", health.status_code == 200, f"{health.status_code}")) if health.status_code != 200: return checks
info = client.get("/model-info").json() expected = file_sha256(models / MANIFEST_FILE) checks.append( ("artifact", info["manifest_sha256"] == expected, info["model_version"]) )
cases = json.loads((models / GOLDEN_FILE).read_text()) body = {"customers": [case["customer"] for case in cases]} got = client.post("/predict/batch", json=body).json()["predictions"] worst = max( abs(g["churn_probability"] - c["churn_probability"]) for g, c in zip(got, cases, strict=True) ) same = all( g["will_churn"] == c["will_churn"] for g, c in zip(got, cases, strict=True) ) detail = f"{len(cases)} cases, max diff {worst:.6f}" checks.append(("golden", worst <= 5e-5 and same, detail))
if live_info is not None: new = info["metrics"]["test_roc_auc"] old = live_info["metrics"]["test_roc_auc"] detail = f"ROC-AUC {new:.4f} vs live {old:.4f}" checks.append(("quality", new >= old - max_auc_drop, detail)) return checks
def main() -> int: import httpx # only this command-line part needs a real HTTP client
parser = argparse.ArgumentParser(description="Check a new service copy.") parser.add_argument("url") parser.add_argument("--models", type=Path, default=Path("models")) parser.add_argument("--live") parser.add_argument("--max-auc-drop", type=float, default=0.01) args = parser.parse_args()
live_info = None if args.live: live_info = httpx.get(f"{args.live}/model-info", timeout=10).json() with httpx.Client(base_url=args.url, timeout=10) as client: checks = run_checks(client, args.models, live_info, args.max_auc_drop) for name, passed, detail in checks: print(f"{'PASS' if passed else 'FAIL'} {name:<9} {detail}") return 0 if all(passed for _, passed, _ in checks) else 1
if __name__ == "__main__": sys.exit(main())run_checks() takes any client with get() and post(), so the same code checks a real server through httpx and the app in memory through TestClient. Here it checks a fresh copy, first alone, then against a live copy whose test ROC-AUC is higher:
from release_check import run_checks
with TestClient(create_app(Settings(model_dir=models))) as canary: live = canary.get("/model-info").json() stronger_live = live | {"metrics": live["metrics"] | {"test_roc_auc": 0.86}} for live_info in [live, stronger_live]: for name, passed, detail in run_checks(canary, models, live_info): print(f"{'PASS' if passed else 'FAIL'} {name:<9} {detail}") print()PASS health 200PASS artifact 1.0.0PASS golden 7 cases, max diff 0.000035PASS quality ROC-AUC 0.8368 vs live 0.8368
PASS health 200PASS artifact 1.0.0PASS golden 7 cases, max diff 0.000035FAIL quality ROC-AUC 0.8368 vs live 0.8600All 7 golden cases come back within rounding, with the same decisions. The quality gate fails when the new model’s test ROC-AUC is more than 0.01 below the live one. The size of the allowed drop is a team decision; write it down before you compare.
The runbook. A runbook is a short document with the steps that an operator follows for a routine task or an incident, with a check after each step. Keep it next to the code, so it changes with the code.
Deploy a new model version (for example 1.1.0):
- Set
MODEL_VERSION = "1.1.0"andTRAINED_ATintrain_churn.pybefore training, so the metadata names the new version. - Train, package and test:
python train_churn.py && python package_model.py && pytest -q. Stop if a test fails. Write the printed release hash into the release record. - Build a new tag:
docker build -t churn-service:1.1.0 .. Keep the old tag1.0.0. - Start one copy of the new tag with
-e CHURN_MODEL_SHA256=<new release hash>, next to the old copies. This is a canary release: the load balancer or the platform (for example a weighted route) sends it a small share of the traffic first.docker runalone does not split traffic. - Check the canary:
python release_check.py http://<canary>:8000 --live http://<live>:8000. Stop if any line says FAIL. - Watch the canary for one nightly batch (see the monitoring table), then replace the old copies.
Monitor (from the JSON logs and the nightly job):
| Signal | Where | Act when |
|---|---|---|
| 5xx answers | request lines with status ≥ 500 |
any prediction_failed or unhandled_error line |
| 422 answers | validation_failed lines and their types |
a sudden rise: a client changed its payload |
| Latency | duration_ms of request lines |
the p95 (the 95th percentile: 95% of requests are faster) is above an agreed limit, for example 200 ms for one customer |
| Flag rate | n_flagged / n of predictions lines |
far from its usual level, for example a change of more than 25% (relative) from one month to the next |
| Feature drift | the monthly drift report of the module 44 project | any PSI above 0.1: investigate; live ROC-AUC 0.03 below the test score: retrain |
| Readiness | the platform’s readiness check on /health |
a copy is not ready for more than one minute |
| Settings | unknown_settings warnings at start-up |
a name that looks like a typo of a real setting |
Roll back (when the new version misbehaves):
- Remove the new copy:
docker rm -f churn(or set its traffic share to 0 on the platform). - Start the previous tag with its own release hash:
docker run -d --name churn -p 8000:8000 -e CHURN_MODEL_SHA256=<old release hash> churn-service:1.0.0. - Check:
/healthis 200 and/model-infoshows the oldmodel_versionandmanifest_sha256. - Check the logs: the 5xx lines stop and the flag rate returns to its usual level.
- Keep the bad image and its logs for the incident review. Do not delete a tag that has served traffic.
When the model folder is mounted from outside the image instead, roll back by pointing CHURN_MODEL_DIR at the previous folder (for example /srv/models/1.0.0), setting its release hash and restarting. The manifest then refuses a half-copied folder with a 503 instead of serving it.
Stretch goals
Section titled “Stretch goals”- Sign the manifest in the release job and verify the signature at start-up, so that trust no longer depends on who can write the model folder.
- Send uvicorn’s own start-up lines as JSON too, with
uvicorn --log-config logging.json. - Add a
/metricsendpoint in the Prometheus text format, with request counts by status and a histogram ofduration_ms. - Reject bodies above 1 MB inside the service too: a middleware that reads the
Content-Lengthheader and answers 413. - Switch
Customerto strict types (StrictInt,StrictBool) and update the lax-mode tests. Discuss what the CRM team must change. - Add the training ranges of
metadata.jsonto the answer: a list of the features that are outside the range that the model saw. - Protect the service with an API key: a dependency that reads the
X-API-Keyheader and compares it with a value from the environment, withsecrets.compare_digest(). - Write a GitHub Actions workflow that runs the two scripts,
pytestandruff, then builds the image, on every pull request.
Next steps
Section titled “Next steps”- This is the last capstone. Go back to the learning paths and pick the modules that you want to deepen.
- Review module 44 for drift and experiment tracking, the two parts of production work that this service does not do itself.
- Review module 14 if a test was hard to write.