Sub topic 10
Pinning model versions and detecting drift
This chapter covers how to control which model your tests run against, and how to notice when a model changes behavior even though your code did not. It assumes you have the earlier pieces in place: a golden dataset, deterministic and judge-based checks, a stored baseline, and a CI workflow that runs the suite. You should also be comfortable reading Python, YAML, and GitHub Actions configuration.
Why pinning matters
Your prompt is only half of what produces an output. The other half is the model, and a model name can mean different things on different days.
Most providers offer two kinds of model identifier:
| Identifier type | Example form | Behavior |
|---|---|---|
| Alias | `example-model-latest` | The provider moves it to a newer snapshot when one is released. |
| Snapshot (dated version) | `example-model-2025-06-01` | Intended to point at one fixed set of weights until it is retired. |
The names above are placeholders. Check your provider's documentation for the real identifiers and for what it promises about each kind.
If your application and your eval suite both call an alias, a model upgrade can change results with no commit in your repository. A test that passed on Monday fails on Tuesday, and git blame finds nothing. Worse, the failure may show up first in production, because production traffic reaches the new snapshot before your next scheduled test run.
Pinning means you choose the model snapshot explicitly and change it only in a reviewed pull request. That gives you two properties:
- A change in eval results can be traced to a change in the repository.
- A model upgrade becomes a deliberate event with its own test run, not a surprise.
What pinning does not give you
Pinning reduces uncontrolled change. It does not remove it. Keep these limits in mind.
- Snapshots are retired. Providers publish deprecation schedules. A pinned model eventually stops working, and you must migrate on their timeline. Pinning postpones the upgrade. It does not cancel it.
- Pinned does not mean deterministic. Even with a fixed snapshot and
temperatureset to 0, many APIs can return slightly different text across calls. The earlier chapter on nondeterministic output still applies. - Serving changes can occur. Providers may change infrastructure, safety filters, tokenizer handling, or system-level wrappers around a snapshot. Not all providers promise that a snapshot behaves identically forever. Read the terms for your provider.
- Some products have no snapshots. A hosted assistant feature or a fine-tuned model behind a gateway may only offer a moving target. In that case, drift detection is your only protection.
The practical conclusion: pin to reduce noise, and also run drift detection to catch what pinning misses.
Pinning in your code
Keep the model identifier and all other generation settings in one place, and make the eval suite read from the same place as the application. If the suite uses a different configuration from production, it tests the wrong thing.
import os
import re
from dataclasses import dataclass
# Matches identifiers that end in a date such as 2025-06-01 or 20250601.
DATED_SUFFIX = re.compile(r"\d{4}-?\d{2}-?\d{2}$")
@dataclass(frozen=True)
class ModelConfig:
model: str
temperature: float
max_tokens: int
prompt_version: str
def __post_init__(self):
if not DATED_SUFFIX.search(self.model):
raise ValueError(
f"Model '{self.model}' has no date suffix. "
"Pin a dated snapshot, not an alias."
)
PINNED = ModelConfig(
model=os.environ.get("EVAL_MODEL", "example-model-2025-06-01"),
temperature=0.0,
max_tokens=512,
prompt_version="summarize-v7",
)
if __name__ == "__main__":
print(PINNED)Three details are worth noting:
frozen=Truestops code from mutating the configuration after it loads.- The
__post_init__check fails fast if someone sets an alias. It is a guard, not proof of pinning. Some providers use identifiers that do not end in a date, so adapt the pattern to your provider's naming. - The
EVAL_MODELenvironment variable lets a CI job try a candidate model without editing the file. The default stays pinned, so normal runs are unaffected.
Record what actually ran
Many APIs return the model identifier in the response. If yours does, store it with each result. Then compare it with what you requested. If you asked for a snapshot and the response names something else, the provider may have redirected your request, and you want to know about it.
Save these fields with every eval run:
- Requested model identifier
- Model identifier reported in the response, if available
- Prompt version or commit hash
- Generation parameters
- Date and time of the run
- The dataset version
Without these, a result file from three months ago cannot be interpreted.
Two kinds of drift
Drift means your system's behavior changed without a change you made. It comes in two forms, and they need different responses.
- Model drift. The model behind your identifier behaves differently. Typical signs: a format that used to be respected now breaks, answers become longer or shorter, refusals appear or disappear, or a judge's scores shift.
- Input drift. Your real users' inputs change over time, so your golden dataset no longer represents production. The model did not change. Your test set went stale. This is covered in the chapter on maintaining datasets, but you will meet it here because the symptoms overlap.
To tell them apart, run the fixed golden dataset on a schedule. If results move while the dataset, prompt, and pinned identifier are unchanged, the cause is model or serving drift. If results stay stable but users complain, suspect input drift.
Detecting model drift with a canary suite
A canary suite is a small, fixed set of cases you run repeatedly on a schedule, with the sole purpose of noticing change. It differs from your pull request suite in purpose: the PR suite asks "did my change break something?", and the canary suite asks "did something change without me?"
A good canary suite has these properties:
- It runs against the exact configuration production uses.
- It repeats each case several times, so you measure a pass rate per case instead of one pass or fail.
- It includes cases that are sensitive to model behavior: strict output formats, instruction-following edge cases, and a few adversarial inputs.
- It is stable. You do not edit it casually, because edits would look like drift.
Storing a per-case pass rate is what makes drift visible. A suite-level average can hide a real shift. Suppose ten cases each go from 100% to 90%, or one case goes from 100% to 0%: the average moves the same amount in both, but only the second is easy to explain and fix.
import json
import sys
from pathlib import Path
def load(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def mean(values):
values = list(values)
return sum(values) / len(values)
def detect_drift(current, baseline, tolerance=0.03, flip_drop=0.5):
"""Compare per-case pass rates between two runs.
Each argument is a dict like:
{"model": "example-model-2025-06-01",
"cases": {"case-001": 1.0, "case-002": 0.8}}
"""
cur, base = current["cases"], baseline["cases"]
shared = sorted(set(cur) & set(base))
if not shared:
raise ValueError("No overlapping case ids between runs")
overall_drop = mean(base[c] for c in shared) - mean(cur[c] for c in shared)
flipped = [c for c in shared if base[c] - cur[c] >= flip_drop]
return {
"model_changed": current["model"] != baseline["model"],
"overall_drop": overall_drop,
"flipped_cases": flipped,
"drifted": overall_drop > tolerance or bool(flipped),
}
if __name__ == "__main__":
report = detect_drift(load(sys.argv[1]), load(sys.argv[2]))
print(json.dumps(report, indent=2))
sys.exit(1 if report["drifted"] else 0)Run it as python drift.py results/current.json evals/canary_baseline.json. The script exits with status 1 when drift is detected, which makes a CI job fail.
The script checks two signals on purpose:
overall_dropcatches a broad, gradual slide.flipped_casescatches a sharp change in a single case, even when the average barely moves.
It also reports model_changed. If that is True, you are comparing across two different identifiers, and the result should be read as an upgrade comparison, not as drift.
The drift detection flow
The rerun step matters. A single failed scheduled run is often noise, and alerting on every blip trains people to ignore alerts.
Scheduling the canary run
A scheduled GitHub Actions workflow runs without any pull request. Note that scheduled workflows run only on the default branch, and the cron time is in UTC.
name: model-drift-canary
on:
schedule:
- cron: "17 5 * * *"
workflow_dispatch:
jobs:
canary:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- name: Run canary suite
run: python -m evals.run_canary --repeats 5 --out results/current.json
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
- name: Compare with baseline
run: python drift.py results/current.json evals/canary_baseline.json
- uses: actions/upload-artifact@v4
if: always()
with:
name: canary-results
path: results/Here evals.run_canary stands for your own runner module that executes the cases several times and writes the per-case pass rates in the format detect_drift expects. The workflow_dispatch trigger lets you start a run by hand, which is useful when you suspect drift right now. The if: always() on the upload step keeps the results even when the comparison fails, and you need those results to investigate.
The cron minute is 17 instead of 0 because many schedules fire at the top of the hour, and busy times can delay or skip runs.
Upgrading a model deliberately
Eventually you will move to a new snapshot, because the old one is retired or the new one is better or cheaper. Treat this as a normal change with its own test run.
- Open a branch and set
EVAL_MODELto the candidate snapshot in a CI job, leaving the pinned default unchanged. - Run the full suite, not only the fast tier, with repeated runs.
- Compare per-case pass rates between the old and new snapshots. Read the flipped cases, since the average alone will not explain them.
- Fix what you can with prompt edits, and re-run the old snapshot too if you changed the prompt, so you know the edits do not hurt there.
- If results are acceptable, change the pinned identifier and update the baseline in the same pull request, with a note explaining why.
- Watch the first scheduled canary runs after merge.
Never update the baseline just to make a failing run pass without understanding the failure. A baseline that follows every drop hides the drift you built the canary to find.
Common mistakes
- Pinning in the app but not in the tests, or the other way around. The suite then measures a model that production does not use.
- Using one global threshold for drift. A tolerance suited to a 200-case suite can be too loose for a 20-case canary. With 20 cases, one case flipping moves the average by 5 percentage points.
- Alerting on a single run. Rerun once before you page anyone.
- Editing canary cases to match new behavior. This resets the signal. If a case is wrong, fix it in a separate, reviewed change and record a new canary baseline.
- Forgetting retirement dates. Put the provider's deprecation date for your pinned snapshot in the repository, for example in a comment next to the configuration, and set a reminder well before it.
Exercise
Your canary suite has 25 cases, each run 5 times. Last week the stored baseline had an average pass rate of 0.96. Today the average is 0.95, which is within your 0.03 tolerance. But case-014 went from 1.0 to 0.2. The prompt, dataset, and pinned model identifier have not changed. What does the drift script report, what does that most likely indicate, and what should you do next?
Show answer
The script reports drifted as true, because case-014 dropped by 0.8, which is at or above the flipdrop value of 0.5, even though overalldrop is only about 0.01. Since nothing in the repository changed, the most likely cause is model or serving drift, though noise is possible with only 5 repeats. Rerun the canary once to rule out noise. If the drop persists, compare stored outputs for case-014 from both runs to see what changed (for example a broken format or a new refusal), then decide whether to adjust the prompt, migrate to another snapshot, or, after review, accept a new baseline.
Exercise
A teammate sets the application to use an alias that always points to the newest model, but the eval suite uses a dated snapshot. CI is green. Why is that a problem, and how would you fix it?
Show answer
The suite tests a model that production does not use, so a green build says nothing about production behavior, and an alias upgrade could break the feature without any test noticing. Fix it by having both the application and the suite read the same pinned configuration with a dated snapshot, and add a guard that rejects aliases. Also run a scheduled canary against the production configuration.