Sub topic 4
Logging predictions so versions can be compared
This chapter assumes you can serve a model behind an HTTP or RPC endpoint, read short Python snippets, and read JSON. It also assumes you know the basic model metrics (accuracy, precision, recall, latency). The previous chapters covered why offline evaluation is not enough and how to split traffic. Here you will build the record-keeping that makes shadow, canary, and A/B rollouts measurable.
Why logging comes first
A rollout answers a question such as "does the candidate agree with the stable model?" or "does the candidate convert better?". You can only answer it if you can line up the two versions' outputs for the same request and, later, attach the real outcome. If you did not record the request, the model version, and the output at serving time, you cannot recover them afterward. Features change, models get redeployed, and the live state is gone.
Prediction logging is therefore a prerequisite for every strategy in this tutorial:
- Shadow needs paired predictions for the same request from both versions.
- Canary needs per-version error, latency, and score distributions.
- A/B needs the assignment, the exposure, and the outcome joined per unit.
What a prediction record contains
One record is written per model call. The fields below are the working minimum.
| Field | Purpose |
|---|---|
| `request_id` | Join key shared by the stable and candidate records for one request, and later by the label. |
| `unit_id` | The user, session, or account used for assignment. Needed to analyze experiments by randomization unit. |
| `model_name`, `model_version` | Exact artifact that produced the output. A tag like `latest` is not enough. |
| `role` | `stable`, `candidate`, or `shadow`. Keeps the rollout role separate from the version number. |
| `experiment`, `variant` | Which experiment and arm the request was assigned to, if any. |
| `features_hash` and `feature_schema` | Detects whether the two versions saw the same inputs. |
| `score`, `prediction` | The raw model output and the decision derived from it. |
| `latency_ms`, `error` | Operational data for guardrails. Record failures too. |
| `ts` | Event time, in UTC. |
Two design choices matter here.
First, log the raw score and the thresholded decision. Comparing only decisions hides drift in the score distribution. Comparing only scores hides the threshold you actually serve with.
Second, log the model-version identifier from the artifact itself, such as a registry version or image digest. A version string typed into a config file can drift from what is actually loaded.
Writing records
The code below defines a record and writes it as one JSON object per line. This format is simple to append to, ship to a log pipeline, and read back.
import hashlib
import json
import sys
import time
from dataclasses import asdict, dataclass, field
from typing import Optional
@dataclass
class PredictionRecord:
request_id: str
unit_id: str
model_version: str
role: str # "stable", "candidate" or "shadow"
features_hash: str
score: float
prediction: int
latency_ms: float
experiment: Optional[str] = None
variant: Optional[str] = None
error: Optional[str] = None
ts: float = field(default_factory=time.time)
def hash_features(features: dict) -> str:
canonical = json.dumps(features, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()[:16]
def log_prediction(record: PredictionRecord, sink=sys.stdout) -> None:
sink.write(json.dumps(asdict(record)) + "\n")
features = {"amount": 120.5, "country": "DE"}
log_prediction(PredictionRecord(
request_id="req-001",
unit_id="user-123",
model_version="fraud-2.4.0",
role="stable",
features_hash=hash_features(features),
score=0.91,
prediction=1,
latency_ms=42.0,
experiment="fraud-v3-exp1",
variant="stable",
))The sort_keys=True argument makes the hash independent of dictionary order. Without it, two identical feature sets can produce different hashes and look like an input mismatch.
Where to log in the request path
For shadow traffic, the stable model's record is written on the normal path. The candidate's record is written from the background task, after it finishes or times out. The shadow task from the earlier chapter already logs a shadow_pair. In practice, write two separate records with the same request_id rather than one combined record. Separate records let a failed candidate leave a clear error record without blocking or changing the stable record.
Log asynchronously and never let a logging failure fail the user request. Use a bounded queue and drop records under pressure, and count the drops. A silent drop rate that differs between versions will bias every comparison you make later.
Pairing records and comparing versions
The diagram shows the full flow from request to comparison.
Once records exist, the first useful comparison needs no labels at all. It measures how often the two versions disagree and how far apart their scores are. The code below pairs records by request_id and reports both numbers. It also reports pair coverage, the share of requests that have both records.
import json
from collections import defaultdict
def load_pairs(lines):
by_request = defaultdict(dict)
for line in lines:
rec = json.loads(line)
by_request[rec["request_id"]][rec["role"]] = rec
total = len(by_request)
pairs = [v for v in by_request.values() if "stable" in v and "candidate" in v]
return pairs, total
def compare(pairs, total, threshold=0.5):
flips = sum(
(p["stable"]["score"] >= threshold) != (p["candidate"]["score"] >= threshold)
for p in pairs
)
abs_diff = sum(abs(p["stable"]["score"] - p["candidate"]["score"]) for p in pairs)
return {
"pairs": len(pairs),
"coverage": round(len(pairs) / total, 3),
"disagreement_rate": round(flips / len(pairs), 3),
"mean_abs_score_diff": round(abs_diff / len(pairs), 3),
}
def line(request_id, role, score):
return json.dumps({"request_id": request_id, "role": role, "score": score})
lines = [
line("r1", "stable", 0.9), line("r1", "candidate", 0.8),
line("r2", "stable", 0.4), line("r2", "candidate", 0.6),
line("r3", "stable", 0.6), line("r3", "candidate", 0.55),
line("r4", "stable", 0.7), # candidate timed out, no candidate record
]
pairs, total = load_pairs(lines)
print(compare(pairs, total))Running it prints:
{'pairs': 3, 'coverage': 0.75, 'disagreement_rate': 0.333, 'mean_abs_score_diff': 0.117}Read coverage before anything else. Here the candidate timed out on one request in four. If the timeouts happen on the slowest or hardest inputs, the three surviving pairs are an optimistic sample, and the agreement numbers overstate how well the candidate behaves.
Disagreement is not the same as being wrong. A flip can be the candidate fixing a mistake or making one. Labels settle that.
Joining labels
Ground truth usually arrives after serving: a chargeback weeks later, a click seconds later, or never. Store labels in a separate table keyed by request_id, with their own event time, and join them to the prediction log at analysis time. Never update the original prediction record.
Keep these rules in mind:
- Join on
request_id, not onunit_idand a time window. A user making two requests would otherwise match the wrong prediction. - Record the label's arrival time. This lets you recompute a metric "as of" a given day and see how it matured.
- Treat missing labels as unknown, not as negative. Counting "no chargeback yet" as "not fraud" makes every model look better early on.
Handling delayed labels in depth comes in a later chapter. For now, make sure the join key exists.
Request replay
Logged requests can also be replayed. Replay means sending stored requests to a new model offline or in a staging environment. It lets you test a candidate against real traffic shapes before any live exposure.
Replay works only if you stored the inputs the model actually received, or can rebuild them. Features computed live from a feature store can differ from what you can reconstruct later. If you want replay, log the feature values, or log the feature-store keys and a snapshot timestamp. Hashes alone detect mismatches but cannot be replayed.
Common errors
- Version not logged. Records say
model_version: "latest". After the next deploy, old logs cannot be attributed. - No shared
request_id. Each service generates its own ID, so the stable and candidate records cannot be paired. Generate the ID once at the edge and pass it down. - Logging only the winner. Only the served prediction is logged, so the candidate's output is lost whenever it is not served.
- Different clocks or time zones. Mixed local and UTC timestamps break time-window comparisons. Use UTC.
- Logging after sampling without recording the rate. If you log 10% of traffic, store the sampling rate so counts can be scaled. Better, sample by hashing
request_idso both versions are sampled together. - Unbounded cardinality in metric labels. Put
request_idin the log, not in metric labels, or your monitoring system will fail.
Summary of decisions
- Write one record per model call, with a shared
request_id. - Identify the exact model artifact and the rollout role separately.
- Store raw scores, decisions, latency, and errors.
- Log asynchronously, and count dropped records.
- Keep labels in a separate table and join on
request_id. - Check pair coverage before trusting any comparison.
Exercise
During a shadow rollout you compute a 0.4% disagreement rate between stable and candidate from the paired log. Pair coverage is 60%, because the candidate times out on the slowest requests. Why is the 0.4% number unreliable, and what two things would you do?
Show answer
The 40% of requests without a candidate record are not a random sample. Timeouts concentrate on slow, probably complex inputs, so the surviving pairs are easier cases and the disagreement rate is likely understated. First, report and investigate coverage and the timeout cause, for example by comparing feature distributions of paired and unpaired requests and by raising the timeout or fixing the candidate's latency. Second, log the timeout as an error record with the same request_id so the missing cases are visible and can be counted as candidate failures in the guardrail metrics rather than silently excluded.