SENIORCHAPTER 27

Prompt management, versioning and experimentation

Treat the prompt, the model id and the parameters as one versioned, immutable bundle; gate every change on a paired eval; roll it out by stable buckets; and make rollback a config flip, not a deploy

55 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

A candidate prompt and the production prompt run on the same 50 labelled tickets. The candidate gets 6 tickets right that production got wrong, and 1 wrong that production got right; the other 43 agree. How strong is the evidence that the candidate is better?

A prompt change is a code change with three unusual properties. Its effect cannot be read from the diff: a reordered paragraph can move accuracy by ten points. It does not fail loudly: a worse prompt returns HTTP 200 with fluent text. And it is easy to ship without the machinery code has, because prompts often live in a database row, a vendor console or a string pasted into a config file.

This chapter puts that machinery back. The prompt, the model and the parameters become one immutable, versioned bundle; a gate compares any candidate with production on the eval set, item by item; a stable bucketing function rolls the candidate out to a percentage of users; every call logs the version that produced it; and rollback is one line of configuration. The lab builds all of it around the ticket classifier, on the local model, so it costs nothing to run. The same pieces wrap the support agent’s prompts.py in the project at the end of this module.

The unit of versioning is the bundle

The text of the prompt is not the only thing that decides the output. The same text on claude-haiku-5-5 and on claude-sonnet-5-5 is two different systems; so is the same text at effort: "low" and effort: "high", or with and without a JSON schema, or with five retrieved chunks instead of ten. A version must cover all of it:

Part of the bundle Example Why it belongs
Template system text, user template with named variables The obvious part
Few-shot examples and definitions six tagged examples Order and choice move scores, as prompting-fundamentals measured
Model id claude-haiku-5-5, never an alias that moves A model change is the largest prompt change there is
Generation parameters effort, max_tokens, output schema Effort changes thinking and cost; the schema changes what is possible
Tools and their descriptions the support agent’s four tool definitions Tool descriptions are prompt text the model reads on every call
Retrieval parameters pipeline, k, reranker What the model sees is part of the prompt

Identify a version by a content hash of the bundle as well as by a human name. Names drift: someone edits v3 in place “to fix a typo”, and now two different prompts are logged as v3. A hash cannot drift. Released versions are immutable: to change anything, copy to a new version. Storage is cheap and the old version must stay loadable for rollback and for re-running old evaluations.

Prompts in files, in git

The default home for prompts is the repository, next to the code that renders them:

  • One file per version, in a format that diffs well and holds multi-line text without escaping. TOML and YAML both work; Python has a TOML reader in the standard library (tomllib).
  • Named variables in the template ($ticket, $definitions) rendered by one function, not f-strings scattered through the code. One renderer means one place to escape untrusted input and one place to test.
  • A lock file of released hashes, checked at load time, so an in-place edit to a released version fails loudly.
  • A deploy pointer, separate from the versions, that says which version is production and which is the candidate at what percentage. Moving the pointer is the release; editing a version never is.
  • Review rules: a CODEOWNERS entry for the prompts directory, so prompt changes get the same review as the code that calls them.

Git gives you review, history, blame, atomic changes to prompt and code together, and CI on every pull request. What it does not give you is a change without a deploy. If the deploy pointer is a file baked into the build, rolling back a prompt takes as long as a deploy, which on a bad day is the wrong speed.

Registries, and what they are for

A prompt registry (Langfuse, Braintrust, PromptLayer, a table in your own database, or a vendor console) stores versions outside the code and lets the application fetch them at run time. Langfuse’s model is typical: every save creates a new, immutable, numbered version; labels such as production and latest point at versions; the application asks for a prompt by name and gets whatever production points at; and rollback is moving the label back. The SDKs cache the fetched prompt, so the lookup adds no latency on the hot path.

Files in git Registry
Who can change a prompt Anyone who can merge Anyone with registry access, often including non-engineers
Review and eval gate Pull request and CI, by default Only if you build it into promotion
Change reaches production On deploy When a label moves, without a deploy
Rollback Revert and deploy, unless the pointer is runtime config Move the label: seconds
Prompt and code changed together Atomic, one commit Two systems; a template variable added in the registry before the code passes it breaks every call
Runtime dependency None The registry, unless you bundle a fallback

The Grok incident is the left column’s protections missing from the right column. The pattern that works for most teams combines them: versions are authored and reviewed as files, CI runs the eval gate, and only a passing version can be promoted, by moving a label in a registry or a pointer in runtime configuration. The application fetches by label, caches, and falls back to a version bundled in the build if the registry is unreachable. People who are not engineers (support leads tuning tone, for instance) edit drafts in the registry’s interface, which opens the same gate before anything reaches the production label.

The eval gate

A gate answers one question before a candidate goes anywhere near users: is it worse than production on the cases you know about? It runs the candidate and production on the same eval set and compares them item by item.

Paired comparison is the important idea. The prompting-fundamentals chapter computed that an accuracy measured on 50 items has a 95% interval of about ±11 points, which makes two separate scores nearly useless for comparing prompts. But the two prompts saw the same items. The 43 items both got right or both got wrong say nothing about which prompt is better; all the information is in the items that flipped. If the candidate fixed f items and broke b, and the prompts were equally good, each flip would be a fair coin, so the one-sided chance of f or more wins out of n = f + b is the binomial tail Σ C(n, k) / 2ⁿ for k from f to n. For 6 fixed and 1 broken that is 8/128, about 0.06. For 10 fixed and 1 broken, 12/2048, about 0.006. This is the exact sign test (McNemar’s test in its exact form), and it is the right default for a prompt gate. It is one-sided on purpose: it answers ‘is the candidate better?’, which is the question that decides between Pass and Neutral below. The CI gate in evals in CI prints the same test two-sided, because a reviewer there asks whether anything changed in either direction; for 6 fixed and 1 broken that is 16/128, about 0.13. Neither gate blocks on a p-value. Blocking comes from the must-pass list and the net-loss threshold in both, so a change that is merely not better passes CI and comes out Neutral here.

A useful gate has three outcomes, not two:

  • Block when the candidate breaks any must-pass item that production gets right (the compliance ticket, the refund that must be declined, the injection case), or when it loses more items than it wins by a margin you choose, or when it costs more tokens without winning anything.
  • Pass when the candidate wins with a sign-test p-value below your threshold.
  • Neutral otherwise: no evidence either way. Ship a neutral change if it is simpler or cheaper, behind a gradual rollout, and add eval items of the kind that flipped.

Two things keep a gate honest. Cache results by content hash: production’s per-item results do not change until its hash does, so the gate runs only the candidate, which halves the cost of every check in CI. And keep a held-out set that day-to-day iteration does not use: a team that iterates prompt after prompt against the same fifty items is fitting the prompt to those items. The next section splits the support agent’s set. Shankar et al. found a related effect in people: graders’ criteria shift as they read outputs (‘criteria drift’), so the rubric and the must-pass list need revisiting as well as the prompt.

The CI wiring itself, running a gate on every pull request that touches the agent or its eval set and showing the flips on the run’s summary page, is the subject of evals in CI, which builds the same rules (must-pass first, a net-loss threshold measured from an A/A run, a cost budget) for the support agent. This chapter’s lab builds the gate as a command you can run before you push.

Development and held-out cases

Every prompt you try against the eval set teaches you something about its cases, and after twenty iterations the prompt fits them. The defence is the one machine learning has always used: split the set, iterate on one part, and look at the other only when you decide to ship. For the support agent’s support-100.jsonl from building-an-eval-set, a 70/30 split, stratified by category so that every slice is in both halves and stable by case id so that everyone’s split is the same, is a few lines in labs/ai/evals/split.py. Rounding each category’s 30% separately would give 29 or 31, so the shares are rounded to add up to exactly 30:

"""Split support-100.jsonl into 70 development and 30 held-out ids: per category, stable by id."""
import hashlib, json
from collections import defaultdict

HOLDOUT = 30
cases = [json.loads(l) for l in open("support-100.jsonl") if l.strip()]
by_cat = defaultdict(list)
for c in cases:
    by_cat[c["category"]].append(c["id"])
# each category's share of the 30, rounded so the shares add up to exactly 30 (largest remainder)
share = {cat: len(ids) * HOLDOUT / len(cases) for cat, ids in by_cat.items()}
take = {cat: int(s) for cat, s in share.items()}
for cat in sorted(share, key=lambda c: (take[c] - share[c], c))[: HOLDOUT - sum(take.values())]:
    take[cat] += 1
held = []
for cat, ids in sorted(by_cat.items()):
    ids.sort(key=lambda i: hashlib.sha256(f"holdout-v1:{i}".encode()).hexdigest())
    held += ids[: take[cat]]
split = {"dev": sorted(set(c["id"] for c in cases) - set(held)), "holdout": sorted(held)}
json.dump(split, open("split.json", "w"), indent=1)
print(f"dev {len(split['dev'])}  holdout {len(split['holdout'])}")

Three rules make the split worth having. Iterate, read failures and write prompt changes against dev only. Run holdout once per release candidate, and record the result with the version hash, not after every edit. And when the two disagree by more than the A/A noise from the evals-in-CI chapter, believe the held-out number: the gap is the amount you fitted the development cases. New cases from production go through the same rule, so about 30% of them land in the held-out half without anyone choosing. Adding cases can shift a category’s share by one, so diff split.json after re-running it: a development case you have already read must not move into the held-out half. This split is separate from llm-as-judge’s even and odd halves: those exist to tune and then test the judge, these to tune and then test the agent.

Gradual rollout

A gate can only test the cases you have. Production has the others. So a version that passes the gate goes to a small fraction of real traffic first, and widens in stages while you watch.

Bucket by a stable unit. Hash the unit id with a per-rollout salt and take it modulo 100: bucket = sha256(salt + ":" + user_id) mod 100. A user whose bucket is below the candidate percentage gets the candidate. Three properties follow, and all three matter:

  • Sticky. The same user gets the same version on every request, so a conversation never changes prompt half-way and users do not see the assistant’s personality flicker.
  • Monotonic. Raising the percentage from 10 to 50 keeps the first 10% in the candidate and adds 40% more; nobody flips back.
  • Independent between rollouts. A new salt per rollout means the same unlucky 10% of users are not the guinea pigs every time.

Randomising per request breaks all three. Bucketing by conversation rather than user is fine for a support agent where conversations are independent; bucket by user when users return and would notice.

Stages. A typical sequence is 1% for an hour, 10% for a day, 50% for a day, then 100%, with a person or an automated check deciding at each step. Shadow mode comes before any of it when the change is risky: the candidate runs on a copy of live traffic and its outputs are logged but not shown. It costs a second model call per request and shows you real inputs without real consequences.

What to watch. Online metrics are the only measure of the cases the eval set lacks: escalation to a human, thumbs-down rate, refund or action rate for an agent, guardrail and output-check trips, refusals, cost per conversation, latency. Compare candidate buckets with production buckets over the same hours, not the candidate this week with production last week. The SRE workbook’s advice on canaries applies unchanged: few metrics, user-visible ones, attributable to the change.

Know what an A/B test can detect. To detect a change from 20% to 18% in escalation rate with 80% power at the usual 5% significance level you need about 16·p(1−p)/δ² = 16 × 0.16 / 0.02² ≈ 6,400 conversations per arm. A product with a few hundred conversations a day cannot A/B test small prompt changes in any reasonable time. It relies on the offline gate and on staged rollout as a safety check for large regressions, which a few hundred conversations do show.

Mind the cache. Each prompt version is a different prefix, so each has its own prompt cache, and caches are per model too. During a 50/50 rollout each version’s prefix is read half as often; with a five-minute cache lifetime and modest traffic, more requests miss and pay full input price. Expect cost per call to rise during a rollout and to fall back after it, and do not read that rise as the candidate being more expensive.

Rollback

Rollback must be faster than the harm. That rules out anything that needs a build: the pointer that says which version is production lives in runtime configuration (a registry label, a feature-flag service, a config file the service re-reads), and setting the candidate percentage to zero is the whole rollback. The old version is still loadable because released versions are immutable and never deleted.

Three practices make rollback dependable:

  • Log the version on every call. Name, version and hash, next to the model id and the usage. When complaints arrive, you can say which version produced the bad output and how many calls it served. Without this, a rollback is a guess.
  • Automate the obvious triggers. If the candidate’s guardrail-trip rate or refusal rate is several times production’s over the last thousand calls, set its percentage to zero and page someone. A rollback that waits for a human to read a dashboard at 03:15 is the Grok timeline.
  • Pin model ids, and treat a model change as a version. A bundle that says claude-haiku-5-5 behaves the same until you change it. When a model is deprecated, the replacement goes through the same gate and rollout as any other change. The applied-LLMs practitioners’ write-up puts pinning model versions on its list of hard-won lessons for this reason.

Where it goes wrong

  • The registry path skips the gate. Promotion to production must require a passing gate result for that hash. Otherwise the registry is a way around your review process.
  • Template and code drift. The registry version expects a $customer_tier variable that this build does not pass. Render every version against a test fixture in CI and fail on a missing variable; the lab’s renderer raises on one.
  • Silent edits. A released version changed in place, now logged under the old name. The hash and the lock file catch it.
  • Overfitting the eval. Fifty prompt iterations against fifty items find the prompt that fits those items. Keep a held-out set and grow both sets from production failures.
  • Mixed versions in one conversation. Per-request bucketing, or a rollout percentage changed mid-conversation with no stickiness. Bucket by conversation or user, and decide the version once per conversation.
  • Version not in the trace. An incident review that cannot say which prompt produced the output. Put the version and hash on every log line and span; the observability chapter in module A4 makes them span attributes.
LAB Versioned prompts, a paired gate, a rollout and a rollback ~60 MIN
YOU NEEDThe prompting-fundamentals harness: labs/ai/evals/classify.py and labs/ai/evals/tickets.jsonlOllama with llama3.2:3b (the default backend; everything runs locally for free)Python 3.12 with uv (tomllib is in the standard library)Optional: ANTHROPIC_API_KEY to point a version at claude-haiku-5-5; one gate run of 50 tickets costs under one cent

You will move the classifier’s few-shot prompt into immutable, hashed version files, write a gate that compares any two versions item by item with the exact sign test and a must-pass list, block a ‘harmless’ token-saving change, roll a candidate out to 10% of customers with stable buckets, and roll it back with one line. Work in labs/ai/prompts/, next to labs/ai/evals/.

1. Version 1, as a file. From the root of your checkout:

mkdir -p labs/ai/prompts/prompts/triage labs/ai/prompts/results labs/ai/prompts/logs && cd labs/ai/prompts
cat > prompts/triage/v1.toml <<'EOF'
# Released versions are immutable. To change anything, copy this file to a new version.
description = "Few-shot triage: definitions, tie-break rule, six examples, JSON schema (classify.py's structured variant)"
backend = "ollama"
model = "llama3.2:3b"
effort = "low"            # used only by the claude backend
structured = true
system = "You sort customer support tickets for an online shop so they reach the right team."
template = """<categories>
$definitions
</categories>

<examples>
$examples
</examples>

<ticket>$ticket</ticket>

Return JSON: {"category": "<one of the categories>"}."""
definitions = """billing: charges, refunds already issued, invoices, payment methods, promo codes
shipping: where an order is, delivery dates, couriers, wrong address, damaged in transit
returns: sending an item back, return labels, exchanges, the return window
account: login, password, email change, deleting the account, marketing emails
product: questions about an item: size, compatibility, materials, stock
technical: the website or app is broken: errors, pages not loading, buttons failing
If a ticket fits two categories, choose the team that must act first."""
examples = [
  ["I was charged twice for order 5521.", "billing"],
  ["My parcel has been stuck in Leipzig for six days.", "shipping"],
  ["How do I send back the coat? It is too big.", "returns"],
  ["I can't remember which email I signed up with.", "account"],
  ["Does the X200 kettle work on 110 V?", "product"],
  ["The app freezes whenever I open my basket.", "technical"],
]
EOF
cat > prompts/triage/deploy.toml <<'EOF'
# Runtime pointer: read on every call, so changing it needs no deploy.
production = "v1"
candidate = ""
candidate_percent = 0
salt = "triage-2026-11"
EOF
cat > prompts/triage/gate.toml <<'EOF'
must_pass = [28, 30, 43]     # delete my data; account takeover; checkout broken
max_net_loss = 1             # block if the candidate loses more than this many items net
max_token_growth = 0.20      # block if input tokens grow more than this without a win
EOF
Three files. v1.toml is the bundle: model, effort, schema switch, system text, template, definitions and examples, everything that decides the output. deploy.toml is the pointer that releases happen through. gate.toml names three tickets that must never regress, chosen because a misroute there has a cost beyond a slow reply: a data-deletion request, an account takeover and a broken checkout.

2. The registry: load, verify, render, release, resolve. Create registry.py:

"""Versioned prompts from files: immutable versions, a lock of released hashes, stable buckets."""
import hashlib, json, string, tomllib
from dataclasses import dataclass
from pathlib import Path

ROOT = Path(__file__).parent / "prompts"

@dataclass(frozen=True)
class Prompt:
    name: str
    version: str
    sha: str
    cfg: dict

    def render(self, ticket: str) -> str:
        ex = "\n".join(f"<example>\n<ticket>{t}</ticket>\n<category>{c}</category>\n</example>"
                       for t, c in self.cfg.get("examples", []))
        # substitute() raises KeyError on a variable the template names and we do not pass
        return string.Template(self.cfg["template"]).substitute(
            definitions=self.cfg.get("definitions", ""), examples=ex, ticket=ticket)

def _lock(name):
    p = ROOT / name / "lock.json"
    return json.loads(p.read_text()) if p.exists() else {}

def load(name: str, version: str) -> Prompt:
    raw = (ROOT / name / f"{version}.toml").read_bytes()
    sha = hashlib.sha256(raw).hexdigest()[:12]
    released = _lock(name).get(version)
    if released and released != sha:
        raise RuntimeError(f"{name}/{version} was released as {released} but the file is now {sha}: "
                           "released versions are immutable, copy it to a new version")
    return Prompt(name, version, sha, tomllib.loads(raw.decode()))

def release(name: str, version: str) -> str:
    p = load(name, version)
    lock = _lock(name) | {version: p.sha}
    (ROOT / name / "lock.json").write_text(json.dumps(lock, indent=1, sort_keys=True) + "\n")
    return p.sha

def bucket(unit_id: str, salt: str) -> int:
    return int(hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest(), 16) % 100

def resolve(name: str, unit_id: str) -> Prompt:
    d = tomllib.loads((ROOT / name / "deploy.toml").read_text())
    if d.get("candidate") and bucket(unit_id, d["salt"]) < d.get("candidate_percent", 0):
        return load(name, d["candidate"])
    return load(name, d["production"])

And runner.py, which sends a rendered prompt to whichever backend the bundle names:

"""Call the model a prompt bundle names. Returns (text, input_tokens, output_tokens)."""
import json, sys, urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / "evals"))
from classify import SCHEMA

def complete(p, user):
    c = p.cfg
    if c["backend"] == "ollama":
        body = {"model": c["model"], "stream": False, "options": {"temperature": 0, "seed": 1, "num_predict": 200},
                "messages": [{"role": "system", "content": c["system"]}, {"role": "user", "content": user}]}
        if c.get("structured"):
            body["format"] = SCHEMA
        req = urllib.request.Request("http://localhost:11434/api/chat", data=json.dumps(body).encode(),
                                     headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=300) as r:
            d = json.load(r)
        return d["message"]["content"], d.get("prompt_eval_count", 0), d.get("eval_count", 0)
    import anthropic
    client = anthropic.Anthropic(max_retries=5)
    oc = {"effort": c.get("effort", "low")}
    if c.get("structured"):
        oc["format"] = {"type": "json_schema", "schema": SCHEMA}
    # Opus and Sonnet retry a classifier decline on a fallback model (the API chapter's rule);
    # Haiku 5.5 has no server-side fallback, so it gets none
    fb = {} if c["model"].startswith("claude-haiku") else {
        "betas": ["server-side-fallback-2026-07-01"], "fallbacks": "default"}
    r = client.beta.messages.create(model=c["model"], max_tokens=1024, system=c["system"],
                                    output_config=oc, messages=[{"role": "user", "content": user}], **fb)
    text = "" if r.stop_reason == "refusal" else "".join(b.text for b in r.content if b.type == "text")
    return text, r.usage.input_tokens, r.usage.output_tokens
uv run python -c "
import registry
p = registry.load('triage', 'v1'); print(p.version, p.sha)
print(p.render('Where is my parcel?')[-160:])
print('released', registry.release('triage', 'v1'))"
cat prompts/triage/lock.json
v1 and a 12-character hash, the tail of the rendered prompt ending in the ticket and the JSON instruction, then released with the same hash, and a lock.json containing {"v1": "<hash>"}. From now on load refuses a v1.toml whose bytes differ from that hash. The hash covers the whole file, comments included, which is deliberate: a strict rule is easier to keep than a clever one.

3. The gate. Create gate.py. It caches each version’s per-item results by hash, so production is evaluated once per hash, not on every check:

"""Pre-merge gate: candidate vs production on the eval set, item by item."""
import argparse, json, math, sys, tomllib
from pathlib import Path
HERE = Path(__file__).parent
sys.path.insert(0, str(HERE.parent / "evals"))
from classify import ITEMS, parse_label
from registry import load
from runner import complete

def results(p):
    path = HERE / "results" / f"{p.name}-{p.version}-{p.sha}.json"
    if path.exists():
        return json.loads(path.read_text())
    rows = {}
    for it in ITEMS:
        text, tin, tout = complete(p, p.render(it["text"]))
        pred = parse_label(text)
        rows[str(it["id"])] = {"ok": pred == it["label"], "pred": pred, "tin": tin, "tout": tout}
    path.write_text(json.dumps(rows))
    return rows

def sign_p(wins, losses):
    """One-sided exact sign test: P(at least `wins` of n flips go one way | no real difference)."""
    n = wins + losses
    return sum(math.comb(n, k) for k in range(wins, n + 1)) / 2 ** n if n else 1.0

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("name"); ap.add_argument("base"); ap.add_argument("cand")
    a = ap.parse_args()
    rules = tomllib.loads((HERE / "prompts" / a.name / "gate.toml").read_text())
    b, c = load(a.name, a.base), load(a.name, a.cand)
    rb, rc = results(b), results(c)
    fixed = [i for i in rb if not rb[i]["ok"] and rc[i]["ok"]]
    broken = [i for i in rb if rb[i]["ok"] and not rc[i]["ok"]]
    must = [i for i in broken if int(i) in rules["must_pass"]]
    acc = lambda r: sum(x["ok"] for x in r.values())
    tok = lambda r: sum(x["tin"] for x in r.values()) / len(r)
    growth = tok(rc) / tok(rb) - 1
    p_better, p_worse = sign_p(len(fixed), len(broken)), sign_p(len(broken), len(fixed))
    print(f"{a.base} {b.sha}: {acc(rb)}/{len(rb)}  {tok(rb):.0f} tok/item")
    print(f"{a.cand} {c.sha}: {acc(rc)}/{len(rc)}  {tok(rc):.0f} tok/item ({growth:+.0%})")
    print(f"fixed {len(fixed)} {fixed}  broken {len(broken)} {broken}  "
          f"p(better) {p_better:.3f}  p(worse) {p_worse:.3f}")
    text = {str(it["id"]): it["text"] for it in ITEMS}
    for i in fixed + broken:
        print(f"  {'+' if i in fixed else '-'} #{i:<3} {rb[i]['pred']} -> {rc[i]['pred']}: {text[i][:70]}")
    if must:
        verdict = f"BLOCK: must-pass items broken {must}"
    elif len(broken) - len(fixed) > rules["max_net_loss"]:
        verdict = f"BLOCK: net loss of {len(broken) - len(fixed)} items (p(worse) {p_worse:.3f})"
    elif growth > rules["max_token_growth"] and len(fixed) <= len(broken):
        verdict = f"BLOCK: {growth:+.0%} input tokens with no gain"
    elif p_better < 0.05:
        verdict = "PASS: evidence of improvement"
    else:
        verdict = "NEUTRAL: no evidence either way; ship only if simpler or cheaper, behind a rollout"
    print(verdict)
    sys.exit(1 if verdict.startswith("BLOCK") else 0)

if __name__ == "__main__":
    main()
uv run gate.py triage v1 v1
A minute or two on llama3.2:3b, then both lines show the same score (in the range the structured variant gave you in prompting-fundamentals), fixed 0 [] broken 0 [], and NEUTRAL. A second run returns instantly: both sides come from results/triage-v1-<hash>.json. Comparing a version with itself is the first test of any gate; if it reported flips, the model call would be non-deterministic and every later verdict would be noise. Ollama with temperature: 0 and a fixed seed is deterministic on one machine.

4. A ‘harmless’ change, and a real one. v3 is the change someone makes to save tokens: drop the examples and the tie-break line. v2 is a change made from reading the errors in prompting-fundamentals: sharpen the two definitions behind most confusions.

sed -e '/^examples = \[/,/^\]/d' -e '/^<examples>$/,/^<\/examples>$/d' \
    -e 's/^If a ticket fits two categories.*"""$/"""/' \
    -e 's/^description = .*/description = "v1 without examples or tie-break rule, to save tokens"/' \
    prompts/triage/v1.toml > prompts/triage/v3.toml
sed -e 's/^returns: .*/returns: sending an item back, return labels, exchanges, the return window; an item that arrived intact but is unwanted or not as described/' \
    -e 's/^shipping: .*/shipping: where an order is, delivery dates, couriers, wrong address, items damaged or missing on arrival/' \
    -e 's/^description = .*/description = "v1 with sharper returns and shipping definitions"/' \
    prompts/triage/v1.toml > prompts/triage/v2.toml
diff prompts/triage/v1.toml prompts/triage/v3.toml; diff prompts/triage/v1.toml prompts/triage/v2.toml
uv run gate.py triage v1 v3; echo "exit $?"
uv run gate.py triage v1 v2; echo "exit $?"
The diffs show exactly what changed, which is the point of files. For v3 the token line drops sharply, often by half, and the flips are lopsided against it: several broken items, usually including ambiguous ones such as 13 or 24 and often one of the must-pass items. The verdict is BLOCK and the exit code is 1. A change that reads as a tidy-up cost accuracy on exactly the tickets the examples and the tie-break rule were there for. For v2 expect a handful of flips, mostly on shipping and returns tickets, with NEUTRAL or, if the wins are lopsided enough, PASS. If v2 also comes out BLOCK on your machine, read its broken items: a definition you sharpened for one ticket moved another, which is a finding, not a failure of the method.

5. Release the candidate and roll it out to 10%. Create triage.py, the production entry point. It resolves the version per customer, calls the model and logs one JSON line with the version and hash:

"""Classify one ticket for one customer, with the version chosen by deploy.toml, and log it."""
import json, sys, time
from pathlib import Path
from registry import resolve
from runner import complete
sys.path.insert(0, str(Path(__file__).parent.parent / "evals"))
from classify import parse_label

def classify(unit_id, text):
    p = resolve("triage", unit_id)
    t0 = time.time()
    raw, tin, tout = complete(p, p.render(text))
    label = parse_label(raw)
    with open(Path(__file__).parent / "logs" / "triage.jsonl", "a") as f:
        f.write(json.dumps({"ts": round(time.time(), 3), "unit": unit_id, "prompt": p.name,
                            "version": p.version, "sha": p.sha, "model": p.cfg["model"], "label": label,
                            "in": tin, "out": tout, "ms": round(1000 * (time.time() - t0))}) + "\n")
    return label

if __name__ == "__main__":
    print(classify(sys.argv[1], sys.argv[2]))
uv run python -c "import registry; print(registry.release('triage', 'v2'))"
sed -i.bak -e 's/^candidate = .*/candidate = "v2"/' -e 's/^candidate_percent = .*/candidate_percent = 10/' prompts/triage/deploy.toml
uv run python -c "
import registry
units = [f'cust-{i}' for i in range(10000)]
at = lambda pct: {u for u in units if registry.bucket(u, 'triage-2026-11') < pct}
print('10%:', len(at(10)), ' 50%:', len(at(50)), ' 10% inside 50%:', at(10) <= at(50))
print('cust-42 twice:', registry.resolve('triage', 'cust-42').version, registry.resolve('triage', 'cust-42').version)"
for i in $(seq 1 40); do uv run triage.py "cust-$i" "The courier left my parcel in the rain and the box is soaked." > /dev/null; done
uv run python -c "
import json, collections
rows = [json.loads(l) for l in open('logs/triage.jsonl')]
print(collections.Counter((r['version'], r['sha']) for r in rows))"
About 1,000 of 10,000 customers in the 10% bucket and about 5,000 in the 50% bucket, with 10% inside 50%: True: widening the rollout never moves a customer back. cust-42 gets the same version twice. The log counts show most of the 40 calls on v1 and a few on v2, each with its hash; with 40 customers, anywhere from one to eight on v2 is normal. Every log line can now be traced to the exact bytes of the prompt that produced it.

6. Roll back without a deploy.

sed -i.bak -e 's/^candidate_percent = .*/candidate_percent = 0/' prompts/triage/deploy.toml
for i in $(seq 1 40); do uv run triage.py "cust-$i" "Where do I print the return label?" > /dev/null; done
uv run python -c "
import json, collections
rows = [json.loads(l) for l in open('logs/triage.jsonl')][-40:]
print(collections.Counter(r['version'] for r in rows))"
Counter({'v1': 40}). One line changed and the next call used production, because deploy.toml is read per call. In a real service that file is a registry label or a feature flag the service re-reads every few seconds; the property that matters is the same: rollback is a configuration change measured in seconds, and v2 stays released and loadable for when you try again.
Edit a released version in place: sed -i.bak 's/billing: charges/billing: all charges/' prompts/triage/v2.toml, set candidate_percent = 10 again, and load it: uv run python -c "import registry; registry.load('triage', 'v2')". It fails with triage/v2 was released as ... but the file is now .... Now delete prompts/triage/lock.json and run the 40-customer loop from step 5 again: it works, and the log counter shows v2 under two different hashes. Two prompts are now logged as one version, every comparison of ‘v2’ mixes them, and an incident review cannot tell which one a customer saw. Restore it: mv prompts/triage/v2.toml.bak prompts/triage/v2.toml, then uv run python -c "import registry; registry.release('triage', 'v1'); registry.release('triage', 'v2')" to rebuild the lock, and put any change in v4.toml. Then try one thing the gate cannot catch: a candidate that passes because the fifty tickets never exercise the case it breaks. That is what the staged rollout and the online metrics are for.
ARTEFACT Write the prompt change request and experiment record ~45 MIN
YOU PRODUCEA prompt change request with its experiment record

Template

# Prompt change request: <prompt name>, <old version> to <new version>
Owner: <author>. Approver: <name and role>. Date: <date>.
Decision needed: <approve for rollout to <percent>% / approve for 100% / reject>, by <date>.

## 1. The change
What differs between the two bundles (text, model id, effort, tools, schema). Paste the diff.

## 2. Why it is needed
The failure or request behind it, with evidence: tickets, complaints, a missed case.

## 3. Versions
| | Old (production) | New (candidate) |
|---|---|---|
| Version id | | |
| Content hash | | |
| Model id and effort | | |

## 4. Offline eval, before and after
Eval set and size, fixed <n>, broken <n>, p(better) <value>, must-pass items broken <list or none>, token change <percent>. Gate verdict: <PASS / NEUTRAL / BLOCK>. Items read by hand: <ids and what you saw>.

## 5. Online experiment
Unit bucketed, salt, stages, how long, metrics watched, and what this traffic can detect. Result: <numbers, or not yet run>.

## 6. Rollout and rollback
Stages and who decides each step. Rollback: <the one config change>, trigger <metric and threshold>, time to roll back <seconds or minutes>.

## 7. How this could be wrong
<one way, and what would show it>

## 8. Out of scope and sign-off
Not covered: <what>. Approved <name, role, date>.
WORKED EXAMPLE

At a real company the engineer who owns the prompt writes this, and the head of support signs it, because the wording is hers and the customers are hers. This one is for the shop’s ticket classifier, going from v1 to v2 (sharper returns and shipping definitions).

Change. Two lines of definitions in v2.toml; model, effort and schema are unchanged. Why. The prompting-fundamentals errors showed returns and shipping tickets confused. Versions. v1 and v2, each logged with its 12-character hash from lock.json. Offline. The gate ran on the 50 tickets, with must-pass items 28, 30 and 43. Assumed for this example: v2 fixed 6 and broke 1, none of them must-pass. The one-sided sign test gives 8/128, about 0.06, which is above the 0.05 threshold, so the verdict is NEUTRAL: ship only behind a rollout. The one broken ticket was read by hand. Online. Bucketed by customer with salt triage-2026-11, 10% first. Assumed: 300 tickets a day. Detecting a 2-point change in a 20% rate needs about 6,400 per arm, so this stage is a safety canary, not a test. Rollback. Set candidate_percent = 0; the next call uses v1; time to roll back is seconds. Wrong if the 50 tickets miss a case v2 breaks; a rise in escalations in the 10% bucket would show it. Approved by the head of support.

Now you

You work at Owoleaf (60 people, live in four states, about 14 engineers). Its in-app support assistant answers customers in their own language from help-centre articles it retrieves. Its instruction says never ask for a PIN, password or OTP, give the session ID for a late transfer and escalate to a human agent. The support lead wants a change to that instruction: the assistant should quote the figures on the Fees and limits page exactly, including the daily send limits of ₦30,000 for tier 1 and ₦200,000 for tier 2, rather than paraphrase them. Write the change request and experiment record. Reuse the lab’s gate, flips, 10% rollout and rollback outputs as your pattern, and state as assumptions any figure the lab does not print, such as the size of the assistant’s eval set and its daily conversations. Your head of engineering reads it and decides whether the change goes to 10% of customers.

Self-check

DECIDE

The support agent's prompts live in prompts.py in the repository. The head of support wants her team leads to adjust the agent's tone and escalation wording several times a week without waiting for an engineer, and has found a hosted prompt registry with a web editor and a 'publish to production' button. You own the agent. What do you set up?

READING
  1. POST
    What We've Learned From A Year of Building with LLMs Eugene Yan, Bryan Bischof, Charles Frye, Hamel Husain, Jason Liu, Shreya Shankar, 2024

    Practitioners' lessons across tactics, operations and strategy. The operational section on pinning model versions, evals before and after migration, and shipping changes carefully is the background to this chapter; skim the rest.

  2. POST
    Your AI Product Needs Evals Hamel Husain, 2024

    Three levels of evaluation, unit tests on every change, human and model review on a cadence, A/B tests for big changes, and the advice to store results with prompt versions so you can track progress. The structure this chapter's gate and rollout follow.

  3. PAPER
    Who Validates the Validators? Aligning LLM-Assisted Evaluation of LLM Outputs with Human Preferences Shankar, Zamfirescu-Pereira, Hartmann, Parameswaran, Arawjo, 2024

    Criteria drift: what graders consider correct changes as they read outputs. The reason your must-pass list and rubric are versioned and revisited, not written once. Read: sections 1 and 5 (the criteria-drift findings); skip the tool description in section 4.

  4. DOC
    Prompt management: versions and labels Langfuse

    A clear statement of the registry model: immutable numbered versions, a production label fetched by default, latest, and rollback by moving a label. Read it as the reference design, whichever registry you use.

  5. BOOK
    Canarying Releases Google SRE, 2018

    Written for binaries and as true for prompts: how large a canary, how long, which metrics, and comparing canary with control over the same period rather than before and after. Read: the sections on canary population, duration and metric selection.

  6. DOC
    System prompt release notes Anthropic

    Dated, published versions of the system prompts behind Anthropic's own apps. A real example of prompts treated as versioned, reviewable artefacts; read two consecutive versions of one model's prompt as a diff.

  7. POST
    Patterns for Building LLM-based Systems & Products Eugene Yan, 2023

    The evals, guardrails, defensive UX and feedback-collection patterns that feed online metrics during a rollout. Read the evals and collecting-feedback sections; the rest overlaps earlier chapters.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: the support agent at 95% →