Measure the local prediction path and keep service health separate from prediction quality.
Problem
When you need this. After a release, successful model loading is only the start. The analyst may receive no predictions because inputs are malformed or a dependency fails. A service can also respond quickly while making poor predictions.
This workshop runs one bounded batch of local prediction calls: the 48 valid observations and one deliberately invalid request. It counts statuses, summarizes elapsed call times and keeps the predictions for the later label join.
Concepts
Service health describes whether the application completes requests and how long they take. Data quality describes whether requests satisfy the declared feature and time contract. Prediction quality requires outcomes; a successful response does not supply them.
The collector loads one Predictor before timing requests. Each elapsed value spans validation and prediction for that call. It excludes model loading, network transport and user-facing report generation. The optional HTTP smoke check from the serving workshop is a different measurement.
The report uses nearest-rank percentiles: sort the measured durations and take the element at the ceiling of the desired fraction times the number of requests. With 49 measured durations, the p95 summarizes this small local sample. It is not a service-level objective.
The reporting function accepts at most 1000 events. Each event has a status from a fixed set, an elapsed time and the bundle ID. Successful events also keep the observation ID and its time fields. The exercise writes the events to one file, service-events.json; it does not run a collector that grows without limit.
Architecture
Working code
Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. Install the pinned platform dependencies for this workshop.
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txtOn PowerShell, activate with .venv\Scripts\Activate.ps1.
Continue from Roll back to a compatible model bundle; keep the same lab directory and outputs.
Record requests without calling them successful outcomes
The collector separates valid predictions from rejected inputs. It keeps valid predictions in their own list, so a failed request does not become an artificial negative label.
def measure(bundle,rows):
predictor=serving.Predictor(bundle);events=[];predictions=[]
for row in rows:
start=time.perf_counter()
try:
result=predictor.predict(row);predictions.append(result)
event={'status':'ok','bundle_id':predictor.bundle_id,'id':result['id'],'feature_at':result['feature_at'],'predict_at':result['predict_at']}
except ValueError:event={'status':'invalid','bundle_id':predictor.bundle_id}
event['elapsed_ms']=(time.perf_counter()-start)*1000;events.append(event)
return events,predictionsThe deliberately invalid null request produces an invalid event. The 48 valid requests produce estimates using the selected bundle.
Summarize the actual bounded window
The report validates status and elapsed values, computes counts and nearest-rank percentiles, and states that prediction quality has not been measured.
def service_report(events):
if not isinstance(events,list) or not 1<=len(events)<=1000:raise ValueError('report requires 1 to 1000 events')
for event in events:
if event.get('status') not in ['ok','invalid','error']:raise ValueError('unknown event status')
value=event.get('elapsed_ms')
if type(value) not in (int,float) or not math.isfinite(value) or value<0:raise ValueError('invalid elapsed time')
values=sorted(e['elapsed_ms'] for e in events)
return {'requests':len(events),'status_counts':dict(Counter(e['status'] for e in events)),
'p50_ms':values[math.ceil(len(values)*.5)-1],'p95_ms':values[math.ceil(len(values)*.95)-1],
'quantile':'nearest rank; whole local prediction call, excluding model load',
'window':'this supplied bounded batch','prediction_quality_measured':False}python course.py monitoring --workspace work/course{
"requests": 49,
"status_counts": {
"ok": 48,
"invalid": 1
},
"p50_ms": 0.001750071533024311,
"p95_ms": 0.0025830231606960297,
"quantile": "nearest rank; whole local prediction call, excluding model load",
"window": "this supplied bounded batch",
"prediction_quality_measured": false
}This output is from a saved local run; your timings will differ. Compare the raw service-events.json with the aggregate. Do not read the percentile as a capacity benchmark.
The recorded commands wrote their outputs to recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh workspace for another attempt: course.py refuses to overwrite a topic output that already exists.
Failure cases
test_metrics_separate_invalid_inputs_from_quality checks 48 successful calls, one invalid input and a report that sets prediction_quality_measured to false. It also checks that the report rejects a negative elapsed time and a window larger than 1000 events.
The collector records a ValueError from the predictor as an invalid input. Any other exception, such as a programming or dependency error, stops the exercise and stays visible in the command log. The collector does not relabel every exception as bad input.
python -m unittest -v test_platform.pyRunning and scaling the workshop
The raw event and prediction files stay in the course workspace. A deployed collector needs retention, privacy rules, bounded label cardinality and failure-safe export. This exercise sends no telemetry to a remote service.
Track model-load, feature-fetch and network timings separately when those costs enter the operating path. Add load testing before setting worker counts or response-time targets. These measurements cover one small model, already loaded, in one process.
Key takeaways
- Healthy responses and useful predictions are different questions.
- State which operations a timer includes.
- Bound telemetry volume and retain the release identity.
Best practices
Count invalid inputs separately from server failures.
Create the predictor before you start the timer, as measure does, so each elapsed value covers one call and not model loading.
Read status_counts beside the percentiles. service_report computes p50 and p95 over every event, valid and invalid alike.
Use finalized outcomes for model-quality monitoring, introduced next.
Check your understanding
Can a low p95 latency show that the return predictions are accurate?
Show the explanation
No. It only describes elapsed time for these calls. Accuracy needs a prediction-to-finalized-label join.
Read the explanation
These counts describe request execution and input validation. Prediction quality requires joining predictions to finalized outcomes.