Sub topic 12
Handle drift and re-record deliberately
Recorded responses make tests fast and repeatable. They also freeze a moment in time. This chapter covers what happens when the real world moves on and your recordings do not. It also covers how to refresh recordings without hiding real bugs.
This chapter assumes you have read the earlier chapters on the client seam, the RecordingClient class, and cassette hygiene. You should be comfortable with pytest fixtures and command-line options.
What drift means for recorded tests
Drift is a gap between what your recordings say the model or API does and what it does now. A replayed test passes because it never contacts the real service, so it cannot notice this gap on its own.
Drift comes from four places:
| Kind of drift | What changes | How it shows up |
|---|---|---|
| Prompt drift | Your own prompt template | Replay raises `LookupError` because the prompt hash has no entry |
| Model drift | The provider updates a model, or an alias points to a new version | Replies get longer, change format, or follow your instructions differently. Replayed tests stay green. |
| API or SDK drift | Response shape, field names, error types, or deprecations | Your parsing code breaks in production. Tests that replay old shapes stay green. |
| Data drift | The real inputs your users send | Recordings cover cases that no longer match real traffic |
Only prompt drift fails loudly by itself. The other three are silent. A suite that is green for a year may be testing a model that no longer exists.
Prompt drift: let the failure happen
The RecordingClient from the previous chapter hashes the prompt. If you edit the prompt, the hash changes and replay raises LookupError. Treat this as the design working. The error means your recording no longer describes your code.
The wrong response is to loosen matching until the old reply is returned anyway. The test would then check a reply to a question your code no longer asks. The right response is to decide whether the new prompt is correct, then re-record.
Make re-recording an explicit action
Re-recording should be hard to do by accident. Four rules help:
- Re-recording requires a flag, such as
--rerecord. The default run never touches the network. - The flag refuses to run in CI. Credentials and cost stay on a developer's machine.
- Each test owns its own recording file. You can then re-record one test without changing others.
- The model name comes from configuration. You choose it on purpose and it appears in the commit message.
This conftest.py implements those rules. It assumes RecordingClient lives in recording.py and that you use the OpenAI SDK. Replace the OpenAIChat adapter with your own provider's.
import os
import pytest
from recording import RecordingClient
def pytest_addoption(parser):
parser.addoption(
"--rerecord",
action="store_true",
default=False,
help="Call the real model and overwrite recordings.",
)
class OpenAIChat:
"""Adapts the OpenAI SDK to the one-method ChatClient protocol."""
def __init__(self):
from openai import OpenAI
self._client = OpenAI()
self._model = os.environ["LLM_MODEL"]
def complete(self, prompt: str) -> str:
response = self._client.chat.completions.create(
model=self._model,
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
@pytest.fixture
def recorded_client(request):
path = os.path.join("tests", "recordings", f"{request.node.name}.json")
if request.config.getoption("--rerecord"):
if os.environ.get("CI"):
pytest.fail("--rerecord is not allowed in CI")
os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
os.remove(path)
return RecordingClient(path, real_client=OpenAIChat())
return RecordingClient(path)The fixture deletes the old file before recording. Without that step, RecordingClient would keep every old entry whose prompt still matched. A "re-record" would then replay stale replies instead of fetching new ones. Deleting the file forces a fresh call for each prompt the test sends.
A re-record run looks like this:
LLM_MODEL=your-model-id pytest tests/test_invoice.py --rerecordRun the same tests again without the flag. They should pass offline against the new files.
Review the diff before committing
A re-recorded file is a new set of replies, so it deserves the same review as code. Git can show the line-level diff, but replies are often long strings and the diff is noisy. This script compares two recording files by prompt hash and prints what changed.
import json
import sys
def load(path):
with open(path, encoding="utf-8") as f:
return json.load(f)
def diff(old, new):
added = sorted(set(new) - set(old))
removed = sorted(set(old) - set(new))
changed = sorted(k for k in set(old) & set(new) if old[k] != new[k])
return added, removed, changed
def main(old_path, new_path):
old, new = load(old_path), load(new_path)
added, removed, changed = diff(old, new)
for key in added:
print(f"ADDED {key[:12]} {new[key]!r}")
for key in removed:
print(f"REMOVED {key[:12]} {old[key]!r}")
for key in changed:
print(f"CHANGED {key[:12]}")
print(f" old: {old[key]!r}")
print(f" new: {new[key]!r}")
if not (added or removed or changed):
print("No differences.")
return 1 if (added or removed or changed) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2]))To compare a re-recorded file with the committed one, extract the committed version from git:
git show HEAD:tests/recordings/test_extract_total.json > /tmp/old.json
python diff_recordings.py /tmp/old.json tests/recordings/test_extract_total.jsonBecause keys are prompt hashes, the output has a clear meaning:
- A
CHANGEDentry means the same prompt got a different reply. This is model drift (or ordinary sampling variation). Read the old and new replies. - An
ADDEDandREMOVEDpair usually means you edited the prompt. Check that the edit was intended. - An
ADDEDentry with no matching removal means the code now makes an extra model call.
Sampling variation is the main source of noise here. Unless you set temperature to 0, a re-record can change replies even when the model has not changed. Do not treat every CHANGED line as a regression. Ask whether your parser and assertions still pass and whether the reply's structure is the same.
Read the result of a re-record
After re-recording, run the suite offline and sort what you see into three cases:
- Everything passes and replies differ only in wording. Commit the new files.
- A test fails because the reply format changed, for example the model now wraps JSON in a Markdown fence. This is the useful case. Your code has a real weakness. Fix the parser, and keep the new recording as the regression test.
- A test fails because the assertion was too exact, for example it compared a full sentence. Loosen the assertion to check what matters, such as the parsed fields.
When to re-record
Re-record on events, not on a calendar alone. These are good triggers:
- You edited a prompt, system message, or tool schema.
- You changed the model name, or the provider announced a retirement or new version of the model you use.
- You upgraded the SDK, and its response objects or errors changed.
- A production incident showed a reply shape that no recording covers. Add that reply as a new recording or a scripted fake case.
- A live smoke test (covered in the next chapter) failed.
Pin an exact model version where the provider offers one. A moving alias such as "latest" changes the model under you, and you get drift with no commit to point at. A pinned version makes drift a decision you make when you bump it.
Keep a record of what was recorded
A recording file holds only prompt hashes and replies. It does not say which model produced them or when. Add that information somewhere reviewers will see it. Two cheap options:
- Put the model name and date in the commit message of every re-record.
- Keep a small
tests/recordings/README.mdstating the model, SDK version, and the command that regenerates the files.
Also avoid relying on file modification times to judge age. A fresh git clone sets every file's mtime to checkout time, so the mtime tells you nothing.
The overall loop
The diagram shows how the routine fits together. Replay runs on every commit. Re-recording happens only on a trigger and always passes through review.
Limits of this approach
Re-recording catches drift only when you do it. Between re-records, the real API can change and your suite stays green. Recordings tell you your code handles the replies you saved. They do not tell you the provider still sends those replies.
Closing that gap takes a small number of live checks that run outside the normal test loop. The next chapter covers those smoke tests and explains why they are not the same as evaluating output quality.
Exercise
A teammate edits the prompt template in extract_total to add one more instruction. The suite then fails with LookupError: No recorded reply for this prompt. on three tests. They propose changing RecordingClient to fall back to the most similar saved prompt. What do you advise instead, and what steps do you follow?
Show answer
Reject the fallback. It would replay replies to a prompt the code no longer sends, so the tests would pass without testing the new prompt. The LookupError is correct. First confirm the prompt edit is intended. Then run the three tests with --rerecord on a developer machine with a pinned LLM_MODEL. Diff each old and new file with the diff script: expect ADDED/REMOVED pairs for the edited prompt, and read each new reply. Run the suite offline without the flag. If a parser test fails because the reply format changed, fix the parser. Commit the new recordings with the model name in the commit message.