11C.2 CI/CD for Prompts, Models and Evals
A traditional service changes when code changes. An LLM service changes when code changes and when a prompt, model snapshot, tool schema, retrieval index, guardrail, dependency or data set changes — often without a line of application code changing at all. This lesson turns that observation into a release system: what belongs in a pull request, what belongs in a merge queue, what belongs behind an environment approval, what can run without provider keys, and how to make every gate fast enough that engineers actually trust it. It builds directly on 10A.8's eval machinery — the evalkit runner, the paired statistics and the gate verdicts — and 04.10's prompt versioning, and hands runtime monitoring to 11A.2 and 10A.9.
What you'll learn
- The release unit of an LLM system: code, prompts, models, parameters, tools, schemas, agent definitions, retrieval configuration, indexes, guardrails, dependencies and data, versioned and promoted as one auditable artefact
- The test pyramid for LLM applications: deterministic unit and contract tests at the base, schema and cassette checks in the middle, statistical eval gates above them, and live smoke/canary checks at the top
- How to classify a change by risk and choose the smallest gate set that can catch its likely failures
- A complete CI design for GitHub Actions and a GitLab CI pattern: secrets, environments, OIDC, fork safety, concurrency,
uvcaching, artifacts, PR comments and scheduled jobs - How prompts move through
dev → staging → productionaliases, when a prompt registry is worth it, and how to keep registry promotions behind eval gates and approvals - How to manage model upgrades: pin snapshots, detect deprecations, run shadow evaluations, canary traffic and roll back without code archaeology
- How off-the-shelf eval-in-CI tools (promptfoo, pytest-based libraries, hosted platforms) map onto the gate contract, and what to check before adopting one
- How index and embedding-model changes ship as blue/green releases, how dependency upgrades are scanned, and how release evidence is retained
- The post-deploy loop: smoke tests, synthetic probes, canary analysis, progressive rollout and automatic rollback triggers
What you don't need
- API keys. The lesson's scripts run on fixtures; the workflows are reference YAML and are not executed here. Provider-backed eval jobs are designed to use CI secrets you create later.
- A running Kubernetes cluster, cloud account or prompt platform. Deployment mechanics belong to 11C.1; this lesson owns the gates around them.
- Deep statistics. 10A.8 owns paired tests, confidence intervals, gate thresholds and flaky-gate handling; this lesson shows where those decisions plug into CI.
- Module 12's full security curriculum. This lesson covers pipeline secrets, untrusted PRs, dependency scanning and audit evidence, then links to Module 12.
Setup
The scripts in this lesson assume you have worked through Module 10A: the evalkit package (evalkit/runner.py, evalkit/compare.py and the thin evalkit.cli command layer), the eval_smoke/eval_pr/eval_nightly pytest markers and the --eval-live option from 10A.8, Parts 4–6, and the cassette/fake-client testing seam from 03.10. If you have not built evalkit yet, Parts 3–4 still teach the CI contract; do the Module 10A lessons first for the runnable pieces.
The scripts/*.py examples use the Python standard library plus evalkit.compare, so they need the Module 10A package on sys.path (in a real project it sits next to scripts/). First-time users can create a small project as in lesson 03.1:
uv init release-gates --bare --python 3.13
cd release-gates
mkdir -p scripts fixtures evalkitCopy each scripts/*.py example into that folder and run it with PYTHONPATH=. uv run python scripts/<name>.py .... The workflow files under .github/workflows/ and .gitlab-ci.yml are reference files: read them, adapt them to your repository, and do not expect them to run from this lesson alone.
What you must be able to do after this lesson#
- Define the release unit of an LLM system: code, prompts, models, parameters, tools and retrieval config
- Choose which checks run on every pull request without provider keys
- Design an eval gate with PASS, WARN and FAIL verdicts and tiered suites
- Configure CI so fork pull requests never receive provider secrets
- Promote a prompt through dev, staging and production aliases
- Pin model snapshots and run check_model_deprecations.py plus a shadow evaluation before an upgrade
- Write a release-evidence record that makes rollback possible
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The prompt changed but no code did." | 1.1 The release unit |
| "Why do we need an eval on every PR?" | 1.3 The test pyramid |
| "This gate is flaky and everyone ignores it." | 3.3 Statistical gates that do not cry wolf |
| "Can fork PRs run evals safely?" | 4.2 Eval workflow with safe PR behaviour |
| "Do we need a prompt registry?" | 5.1 Repo artefacts vs registries |
| "The provider deprecated a model next month." | 6.2 Lifecycle checks |
| "How do we roll back a bad prompt without a deploy?" | 5.2 Promotion rules |
| "The index looks better but answers got worse." | 7.1 Ingestion and index CI |
| "What exactly promoted this release?" | 9.3 Release evidence and audit trail |
Part 1: What changes in an LLM system#
1.1 The release unit#
In a CRUD service, the deployable artefact is usually the application version. In an LLM service, behaviour is a function of many independently versioned inputs. Call the whole set the release unit: the smallest collection of artefacts that must be evaluated, approved and rolled back together.
| Component | Examples | Version evidence | Typical rollback |
|---|---|---|---|
| Application code | FastAPI routes, routing logic, retry policy | Git SHA, image digest | Redeploy previous image |
| Prompts | Templates, system prompts, few-shot blocks | Prompt name, semver, content hash, alias | Move prompt alias back |
| Model choice | Provider, model ID, snapshot, reasoning effort, sampling/structured-output settings | Model inventory entry, config hash | Change model flag/alias |
| Tools and schemas | Tool definitions, JSON schemas, strict-mode flags | Tool registry version, schema hash | Deploy previous tool config |
| Agent definition | An agent's identity, system prompt reference, tool set, model, step and cost limits, and sub-agent or handoff wiring | Agent manifest version and digest | Repoint the agent pointer to the previous manifest |
| Retrieval config | Query rewrite, k, reranker, filters, context budget | Config version/hash | Change retrieval config flag |
| Index/data | Corpus manifest, chunker version, embedding model, vector index | Index alias, manifest hash, embedder version | Repoint index alias |
| Guardrails | Moderation, validators, refusal policy | Guardrail config version | Disable or roll back guardrail flag |
| Dependencies | SDKs, eval libraries, base images, actions | uv.lock, image SBOM |
Roll back lockfile/image |
| Eval assets | Dataset version, judge prompt/model, thresholds | Dataset hash, eval config hash | Re-run against prior baseline |
Agents are part of the release unit as one named thing. An agent is the combination of a prompt, a model, a tool set and its limits, and the combination behaves differently from any one part. Adding a tool, loosening the step cap or moving to a new model snapshot changes what the agent does even when the prompt file is untouched. So give each agent a manifest (a small versioned file listing those parts), hash it, and promote and roll back the manifest rather than its parts one by one. 8.4 shows a manifest, a canary and a rollback. The lesson 08A.1 on agent definitions and anatomy in Module 08A explains what an agent definition contains.
The practical rule is simple: if a change can alter user-visible behaviour, it belongs in the release unit even when no Python file changed. A prompt alias move can be as risky as a model swap; a corpus re-ingest can be as risky as a code deploy.
1.2 Why "just run the tests" is not enough#
Classic CI asks: does the code compile, do unit tests pass, does the build succeed? Those checks remain necessary, but they cannot prove that a prompt still extracts invoice fields correctly, that a model upgrade did not change refusal behaviour, or that a new index returns the same evidence for the same question. LLM quality is partly behavioural and partly statistical, so the pipeline needs three kinds of evidence:
- Deterministic evidence — code works, schemas parse, prompts render, requests have the expected shape.
- Statistical evidence — a versioned eval suite says the candidate is not worse than the accepted baseline by more than the agreed tolerance.
- Production evidence — smoke tests, probes, canary metrics and online evaluation say the rollout is healthy after merge.
Missing any one creates a predictable failure. Deterministic-only pipelines ship fluent nonsense. Eval-only pipelines are too slow for every commit. Production-only checks learn about regressions after users do.
1.3 The test pyramid for LLM applications#
The pyramid is wider at the bottom because deterministic checks are cheap and fast; it narrows at the top because live model calls are expensive, slower and non-deterministic.
| Layer | What runs | When it runs | Keys/services needed | Decision it supports |
|---|---|---|---|---|
| Unit tests | Pure functions: parsing, chunking, routing rules, budget arithmetic, template rendering | Every commit | None | Code correctness |
| Contract tests | Request/response schemas, tool-call formats, cassette replay, fake provider adapters | Every commit | None, or local stand-in | API/provider contract stability |
| Prompt render tests | Variables validate, conditionals render, forbidden braces absent, hashes stable | Every prompt PR | None | Prompt mechanics |
| Eval smoke suite | ~20-50 high-signal cases: schema validity, hard requirements, a few judged criteria | Every PR touching prompts/models/tools/retrieval | Usually none with cassettes; optional live | Obvious regression |
| Full eval suite | Hundreds/thousands of cases, slices, cost and latency report | Merge to main, nightly, pre-release | Provider keys or batch jobs | Release-quality decision |
| Integration/live smoke | Small real calls against staging dependencies | Post-merge, pre-deploy, scheduled | Staging keys | Environment and credentials work |
| Canary/online eval | Live traffic metrics, sampled judge scores, user feedback | After deploy | Production observability | Continue, hold or rollback |
The important design choice is not to make every layer call a live model. 03.10 already established the pattern: record provider interactions once, scrub them, commit them, and replay them with the network disabled. In CI, cassettes let a prompt edit prove that the request body changed and that the plumbing still handles the recorded response shape.
1.4 Change-risk classification#
Not every PR needs the same gate. A typo fix in a README needs lint; a prompt semantic change needs eval; a model swap needs shadow evaluation; a retrieval index promotion needs blue/green evidence. Classify the release unit first, then run the gates that can falsify the risky assumption.
| Change class | Examples | Minimum credible gates | Escalate when |
|---|---|---|---|
| Docs/comments only | README, docstrings, comments | Markdown/link checks if configured | Docs contain runnable examples or prompts |
| Pure code | Router rule, retry logic, metrics wrapper | Unit, contract, lint/type, cassette smoke | Touches provider calls, prompts or release config |
| Prompt mechanics | New variable, template syntax, alias move | Render tests, prompt diff, cassette replay, smoke eval | Changes instruction text or output contract |
| Prompt semantics | Reworded rules, new examples, changed tone | Full prompt eval on dev set, slice checks, cost/latency report | Touches safety, refusal, extraction or routing prompts |
| Model/parameters | New snapshot, effort level, temperature-like setting, structured-output mode | Lifecycle check, capability check, shadow eval, canary | Changes provider, data policy, context or price class |
| Tools/schemas | New tool, schema field, strict mode | Schema lint, trajectory tests, security review | Tool can mutate state or call external systems |
| Retrieval/index/data | New chunker, embedder, corpus, ACL filter | Pipeline tests, index build, shadow retrieval eval | Embedding model or permission model changes |
| Dependencies/base image | SDK bump, lockfile, Docker base | uv lock --check, audit/OSV scan, image scan, smoke eval |
SDK changes wire format or retry behaviour |
| Release plumbing | Workflow, deploy script, secrets config | Workflow lint/dry run, least-privilege review, rollback drill | Changes credentials, environments or promotion path |
The classification is a forcing function: if you cannot name the assumption a gate is testing, the gate is probably theatre. "Run evals" is not a gate; "candidate must not regress invoice_exact_match by more than 2 points at 95% confidence" is.
flowchart TD
C["What changed in the release unit?"] --> CODE["Application code"]
C --> PROMPT["Prompt file, template or alias"]
C --> MODEL["Model ID, snapshot or parameters"]
C --> TOOL["Tool definitions or schemas"]
C --> DATA["Retrieval config, corpus or index"]
C --> DEP["SDK, lockfile or base image"]
CODE --> R1["Unit, contract and cassette checks"]
PROMPT --> R2["Render tests plus prompt smoke eval"]
MODEL --> R3["Lifecycle check plus shadow eval"]
TOOL --> R4["Schema and trajectory contract tests"]
DATA --> R5["Pipeline tests plus blue-green shadow eval"]
DEP --> R6["Lock check, audit, image scan, smoke eval"]
R1 --> G["Risk-classified gates"]
R2 --> G
R3 --> G
R4 --> G
R5 --> G
R6 --> G1.5 The end-to-end pipeline#
The pipeline has one spine and several branches. The spine is always: fast checks → merge → full eval → build/scan → staging → canary → progressive production rollout → monitors → rollback path. Branches add the right evidence for the release unit.
flowchart LR
PR["Pull request"] --> CI["ci.yml: lint, types, unit, prompt render, cassette replay"]
CI --> SMOKE["eval.yml smoke: contracts and recorded eval suite"]
SMOKE --> MERGE{"Merge gate"}
MERGE -->|"pass"| FULL["eval.yml full suite, cost report, regression gate"]
FULL --> BUILD["release.yml: image, scan, SBOM, attestation"]
BUILD --> STAGE["Deploy to staging"]
STAGE --> VERIFY["Post-deploy smoke, probes, canary metrics"]
VERIFY --> GATE{"eval_gate and canary_gate pass?"}
GATE -->|"yes"| PROD["Production rollout 5% then 25% then 100%"]
GATE -->|"no"| BACK["Rollback prompt alias, model flag or index alias"]
PROD --> MON["11A.2 metrics and 10A.9 online evaluation"]
MON -->|"regression"| BACKNotice what is not in the diagram: a human reading every diff, a provider call on every keystroke, or a deploy that cannot be undone. The pipeline's job is to make the safe path cheap and the risky path visible.
Part 2: Fast deterministic checks#
2.1 What belongs in ci.yml#
The pull-request workflow should finish quickly and need no secrets. Its job is to reject broken plumbing before anyone spends eval budget.
| Check | Catches | Typical command |
|---|---|---|
| Format/lint | Style drift, syntax errors | ruff check ., ruff format --check . |
| Types | Interface mistakes before runtime | pyright or mypy |
| Unit tests | Pure logic regressions | pytest -m "not eval_smoke and not eval_pr and not eval_nightly and not live and not stand_in" |
| Prompt render tests | Missing variables, bad Jinja, unsafe templates | pytest tests/test_promptlib.py |
| Prompt diff | Instruction changes reviewers must see | scripts/diff_prompts.py (2.2) or promptlib.diffutil.diff_versions (04.10, 5.5) |
| Cassette replay | Request-shape drift against recorded provider responses | pytest --block-network tests/test_record_replay.py |
| Schema lint | Provider-incompatible JSON schemas | pytest tests/test_schema_lint.py |
| Lockfile check | Uncommitted dependency drift | uv lock --check |
| Dependency audit | Known vulnerabilities | pip-audit or osv-scanner scan source -r . |
| Workflow sanity | YAML mistakes, permissions drift | Actionlint or repository policy test |
The exact tools are less important than the separation: anything that can run without a key should run on every PR. If a check needs a provider key, it belongs in a protected environment or a scheduled job, not in the default PR path.
The marker expression deserves a note because it is a common copy-paste bug. The eval tiers are pytest markers registered by the Module 10A evalkit conftest — eval_smoke, eval_pr and eval_nightly (10A.8, 5.1) — while live and stand_in come from 03.10. A -m expression that forgets the eval_* markers does not merely fail to exclude them: it runs every eval tier inside the no-keys job, duplicating eval.yml's smoke job on fakes and slowing the fast lane. --eval-live is a pytest option, not a marker — it is what swaps the fake call_model fixture for the real provider client, so it never appears in -m.
2.2 Prompt render and request snapshot tests#
04.10 gives prompts immutable versions and aliases. CI should prove three things for every prompt change:
- The file parses and its declared variables match the template.
- Rendering with representative inputs produces the expected
system,text,version,modelandcontent_hash(the fields of 04.10'sRenderedPrompt). - The request snapshot sent to a fake client did not change except for the intended prompt fields.
The third check is where 03.10's rule matters: snapshot the request, not the answer. A model answer is non-deterministic; a request body is deterministic. If a PR changes instructions from Be brief. to Be very brief., the cassette or snapshot diff should show exactly that and nothing else.
A minimal CI assertion looks like this:
# tests/test_prompt_release_contract.py
"""Release-contract tests that need no provider key."""
from __future__ import annotations
import json
from pathlib import Path
def test_release_manifest_matches_prompt_files(tmp_path: Path) -> None:
manifest = json.loads(Path("release/manifest.json").read_text())
prompt_files = {p.stem for p in Path("prompts").rglob("*.md") if not p.name.startswith("_")}
assert set(manifest["prompts"]) <= prompt_files
def test_no_prompt_file_uses_unquoted_float_version() -> None:
for path in Path("prompts").rglob("*.md"):
text = path.read_text()
assert "version: 1.0\n" not in text, f"{path} has a YAML float version"This is intentionally small: the real prompt library tests live in 04.10. The CI lesson is that those tests must be required checks, not optional local habits.
The prompt diff that reviewers need is just as small. If you use 04.10's promptlib, its diff_versions helper does the job; the stdlib version below works on any two prompt files (save it as scripts/diff_prompts.py):
# scripts/diff_prompts.py
"""Unified diff of two prompt files, ready to paste into a PR description. Stdlib only.
Usage: python3 scripts/diff_prompts.py OLD.md NEW.md
Exit status: 0 on success (a diff is information, not a failure), 2 on bad usage.
"""
from __future__ import annotations
import difflib
import sys
from pathlib import Path
def diff_prompts(old: Path, new: Path) -> str:
"""Unified diff of the two files' full text (front matter and body)."""
before = old.read_text(encoding="utf-8").splitlines(keepends=True)
after = new.read_text(encoding="utf-8").splitlines(keepends=True)
return "".join(difflib.unified_diff(before, after, fromfile=str(old), tofile=str(new)))
def main(argv: list[str]) -> int:
if len(argv) != 3:
print("usage: python3 scripts/diff_prompts.py OLD.md NEW.md", file=sys.stderr)
return 2
print(diff_prompts(Path(argv[1]), Path(argv[2])) or "no differences")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))Given these two files (a prompt .md file starts with a YAML front-matter block, as in 04.10):
# prompts/support/ticket-triage.v1.md
---
name: support.ticket-triage
version: "1.0.0"
---
Classify the support ticket as billing, shipping or account.
Be brief.# prompts/support/ticket-triage.v2.md
---
name: support.ticket-triage
version: "1.1.0"
---
Classify the support ticket as billing, shipping or account.
Be very brief.Run python3 scripts/diff_prompts.py prompts/support/ticket-triage.v1.md prompts/support/ticket-triage.v2.md (the header comment line is not part of either file):
--- prompts/support/ticket-triage.v1.md
+++ prompts/support/ticket-triage.v2.md
@@ -1,6 +1,6 @@
---
name: support.ticket-triage
-version: "1.0.0"
+version: "1.1.0"
---
Classify the support ticket as billing, shipping or account.
-Be brief.
+Be very brief.2.3 Cassette and fake-provider checks#
Use three levels of provider isolation, in increasing realism:
| Level | Mechanism | Use in CI | What it proves |
|---|---|---|---|
| Fake client | Python fake implementing the app's client protocol | Unit/contract tests | Application logic and error mapping |
| Mock transport | SDK client with httpx mock transport |
Adapter tests | SDK request/response parsing per provider |
| Cassette replay | vcrpy/pytest-recording YAML files |
PR smoke suite | End-to-end request shape and response handling |
For eval suites, prefer a recorded eval cassette pack for the smoke tier and live calls for the full tier. The smoke tier can be deterministic if the cassette returns fixed model outputs; the full tier must be statistical because live outputs vary.
2.4 Dependency and supply-chain checks#
LLM services are especially exposed to supply-chain risk because SDKs sit on the hot path for every request. A lockfile is necessary but not sufficient: a compromised release can enter through a valid-looking version bump.
As of November 2026, useful checks include:
uv lock --check— provesuv.lockstill matchespyproject.toml(uv docs).uv export --format requirements-txtor the lockfile directly — gives scanners a resolved dependency list.pip-audit— scans Python environments or requirements files against vulnerability data (PyPI).osv-scanner scan source -r .— scans supported lockfiles includinguv.lock,requirements.txt,pylock.tomlandpoetry.lock(OSV-Scanner docs).- Renovate or Dependabot — opens update PRs so upgrades go through the same gates as code (Renovate docs, Dependabot docs).
- SBOM and provenance — generate an SBOM for release images and, where the platform supports it, artifact attestations (GitHub Docs, artifact attestations).
The policy should be explicit: dependency PRs are not exempt from eval smoke if the dependency can affect provider calls, JSON parsing, retries, HTTP behaviour or model client semantics. A openai, anthropic, google-genai or HTTP-client bump is a release-unit change. 03.11, 13.9 is the underlying discipline — pin, lock with hashes, review every upgrade like code — and its worked example (the LiteLLM supply-chain compromise) is exactly the failure mode these checks exist to catch; Module 12 owns the security-side response when a compromise is suspected.
Part 3: Eval gates and tiered suites#
3.1 What an eval gate is allowed to decide#
An eval gate is a policy applied to eval results, not the eval itself. 10A.8 owns everything upstream of the decision — datasets and versioning (10A.2), scorers and judges, the evalkit runner, the paired statistics in evalkit/compare.py, and the flaky-gate playbook (2.5 Taming flaky gates). This lesson owns the CI contract: which run the gate reads, which thresholds are hard, which differences need review, and what artefact proves the decision.
The unit the gate reads is a run directory — what evalkit.cli run writes:
runs/<name>/
results.jsonl one JSON row per case-run (evalkit.runner.CaseResult)
run.json the manifest: dataset fingerprint, git SHA, prompt/model/judge versions, budget
report.md the human-readable per-slice report posted to the PRevalkit.cli is the command layer 10A.8, 6.1 builds over evalkit.runner and evalkit.compare. Its own flags are low-level: run takes --cases <file>, --task module:function, --scorer module:function, --model, --out <parent dir>, --name <run dir name>, --repeats and --max-cost-usd, and gate takes the threshold values directly (--min-overall, --max-drop, --min-cases, --slice-dim, --slice-floor). The workflows in this lesson use a shorter, per-tier spelling that your project adds as a thin layer on top (a wrapper script, or a few more options in your copy of evalkit/cli.py):
python -m evalkit.cli run --suite <tier> --model <id> --out runs/<name> [--repeats k] [--budget-usd n]
python -m evalkit.cli gate --run <dir> --baseline <dir> --config gates/<tier>.yaml
python -m evalkit.cli compare --run <dir> --baseline <dir> --markdownThe layer makes four translations. --suite pr becomes --cases evals/pr.jsonl plus your task and scorer functions, so a tier is just a named slice of the dataset. --out runs/<name> is the run directory itself (10A.8's --out plus --name, joined). --budget-usd n becomes --max-cost-usd n. --config gates/<tier>.yaml becomes the threshold flags above, or the GateThresholds that scripts/eval_gate.py below builds from the same keys. Live calls sit behind two environment variables, EVALKIT_LIVE=1 and EVALKIT_API_KEY, which your task function reads, so the same commands run on fakes in smoke jobs. The layer is a hundred lines or so that you write once; every workflow in this lesson assumes it exists. If you would rather not write it, spell each call the 10A.8 way: the workflows' run and gate lines translate one-to-one.
A good gate has four properties:
- Versioned inputs — the
run.jsonmanifest records dataset fingerprint, prompt versions/hashes, model IDs, judge version and git SHA (10A.8, 7.1); a number without provenance is a rumour. - Explicit thresholds — the
GateThresholdsfields (min_overall,max_drop,slice_floors,min_cases,max_cost_usd,max_p95_latency_ms) live in a checked-ingates/<tier>.yaml, not buried in a script. - Three verdicts — blocking
FAIL, advisoryWARNandPASS; a noisy comparison should not silently become either pass or fail. - Readable evidence —
report.mdis uploaded as a workflow artefact and summarised in the PR;results.jsonl+run.jsonare the reproducible record.
3.2 Tiered suites#
10A.8, 3.1 owns the tier design — the table below reconciles its tiers with the pytest markers and evalkit.cli suite names the workflows use. The invariant that matters: tiers are named slices of one dataset, selected by tags, so "the smoke suite" can never drift away from "the real suite".
| Tier | pytest marker / CLI suite | ~Size | Runs when | Keys/services | Decision it supports |
|---|---|---|---|---|---|
| Smoke | eval_smoke / --suite smoke |
~20 cases, repeats=1 |
Every commit and PR | Fakes/replay or the cheapest live model | Plumbing breaks: template errors, parse failures, schema violations, gross regressions |
| Contract | cassette/replay tests (no eval marker) | Deterministic fixtures | Every PR | None | Request/response shape drift (03.10) |
| PR eval | eval_pr / --suite pr |
~50–150 cases | PRs touching prompts, models, tools, retrieval or eval config | Environment-scoped CI keys, --budget-usd cap |
Real quality regressions on the changed component |
| Nightly | eval_nightly / --suite nightly |
Full golden set + extended slices, repeats=2–3 |
Schedule, off-peak | Protected-environment keys | Slow drift, slice regressions, variance growth, judge drift |
| Pre-release | --suite full |
Exhaustive: full set × repeats, model matrix | Before a model/prompt promotion, on demand | Highest approved budget | The decision-grade evidence for a ship call |
| Canary/online | — (not pytest) | Live traffic sample | After deploy | Production observability | Continue, hold or rollback (10A.9, 11A.2) |
Two selection mechanisms do the same job at different seams: pytest -m eval_smoke selects cases for the pytest path (fake by default; --eval-live swaps in the real client), while evalkit.cli run --suite pr selects the same tagged slice for the runner path. Point both at the same tags so the two paths can never disagree about what "smoke" means.
The smoke suite should be deliberately boring: cases that have historically caught real regressions, hard requirements, format checks and a few representative slices. Do not try to measure a 2% lift on 20 cases — 10A.8, 2.4 shows the minimum detectable effect makes that impossible. Use smoke for "is it obviously broken?" and the PR/nightly tiers for "is it acceptable?"
3.3 Statistical gates that do not cry wolf#
Model outputs are non-deterministic, so a single run can move a score by chance. evaluate_gate in evalkit.compare already encodes the honest decision rule (10A.8, 4.1):
- Hard floors —
min_overall,slice_floors,min_casesand the operational budgets (max_cost_usd,max_p95_latency_ms) are point-estimate checks: deterministic assertions that need enough cases to be meaningful, not statistics. - Relative non-regression —
max_dropis judged on the paired bootstrap CI of per-case differences, not onbaseline.mean - current.mean. The CI produces three states: confident fail (the whole interval sits beyond the tolerance), confident pass, and "too wide to tell" — which becomes an advisory warning, not a coin-flip block. - Advisory warnings — a slice missing from the run, a floor the mean clears but the CI dips below, a possible drop inside noise: reported loudly and posted to the PR, never silently rounded to pass or fail.
This lesson's scripts/eval_gate.py is the CI-side adapter the course's evalkit.cli gate wraps: it reads a run directory, an optional baseline run directory, a gate config and (optionally) the dataset for slice mapping, then delegates every statistical decision to evalkit.compare. It exists so you can see the whole contract on fixtures — keep exactly one gate implementation in your project; do not fork the statistics.
# scripts/eval_gate.py
"""CI-side eval gate: turn an evalkit run directory into a ship/no-ship report.
This is the adapter the course's `evalkit.cli gate` wraps. It reads the
result store that `evalkit.cli run` writes:
runs/<name>/
results.jsonl one JSON row per case-run (evalkit.runner.CaseResult)
run.json the manifest: dataset/prompt/model/judge versions, budget
plus an optional baseline run directory and a gate config. All statistics
come from evalkit.compare (lesson 10A.8) — nothing here re-implements them.
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
from pathlib import Path
from typing import Any
from evalkit.compare import (
GateThresholds,
evaluate_gate,
paired_bootstrap_ci,
paired_diffs,
summarise_metric,
)
def load_run_dir(path: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Read results.jsonl + run.json from a run directory (or a bare .jsonl)."""
p = Path(path)
rows_path = p / "results.jsonl" if p.is_dir() else p
manifest_path = p / "run.json" if p.is_dir() else p.with_name("run.json")
rows = [json.loads(line) for line in rows_path.read_text().splitlines() if line.strip()]
manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
return rows, manifest
def ok_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Only 'ok' rows carry quality scores; infra/task/scorer errors are
quarantined by the runner and must not be averaged in (10A.8, Part 9)."""
return [r for r in rows if r.get("status") == "ok"]
def case_scores(rows: list[dict[str, Any]], metric: str) -> dict[str, float]:
"""case_id -> mean score across repeats — the unit paired diffs use."""
acc: dict[str, list[float]] = {}
for row in ok_rows(rows):
score = (row.get("scores") or {}).get(metric)
if score is not None:
acc.setdefault(str(row["case_id"]), []).append(float(score))
return {cid: sum(v) / len(v) for cid, v in acc.items()}
def load_slice_map(dataset: Path | None, tag: str) -> dict[str, str]:
"""case_id -> slice name, from the eval dataset JSONL.
Accepts 10A.2 EvalExample rows (example_id + tags{}) and 10A.1 Example rows
(id + metadata{}); the slice is the value of `tag` in whichever map exists.
"""
if dataset is None:
return {}
out: dict[str, str] = {}
for line in Path(dataset).read_text().splitlines():
if not line.strip():
continue
case = json.loads(line)
cid = str(case.get("example_id") or case.get("id") or "")
tags = case.get("tags") or case.get("metadata") or {}
if cid and tag in tags:
out[cid] = str(tags[tag])
return out
def manifest_cost(manifest: dict[str, Any]) -> float | None:
"""Run-level spend, wherever evalkit.cli recorded the Budget summary."""
for holder in (manifest, manifest.get("budget") or {}, manifest.get("usage") or {}):
if isinstance(holder, dict) and holder.get("cost_usd") is not None:
return float(holder["cost_usd"])
return None
def summarise_run(scores: dict[str, float], slice_map: dict[str, str]):
by_slice: dict[str, list[float]] = {}
for cid, val in scores.items():
name = slice_map.get(cid)
if name:
by_slice.setdefault(name, []).append(val)
return summarise_metric(list(scores.values()), slices=by_slice)
def evaluate(run: Path, baseline: Path | None, config: dict[str, Any],
dataset: Path | None) -> dict[str, Any]:
metric = str(config.get("metric", "accuracy"))
slice_tag = str(config.get("slice_tag", "type"))
rows, manifest = load_run_dir(run)
scores = case_scores(rows, metric)
slice_map = load_slice_map(dataset, slice_tag)
current = summarise_run(scores, slice_map)
diffs = None
baseline_mean = None
paired = None
if baseline is not None:
base_rows, _ = load_run_dir(baseline)
base_scores = case_scores(base_rows, metric)
diffs = paired_diffs(base_scores, scores) # current - baseline
if base_scores:
baseline_mean = statistics.fmean(base_scores.values())
if diffs:
d_mean, d_lo, d_hi = paired_bootstrap_ci(diffs)
paired = {"mean_diff": d_mean, "ci_lo": d_lo, "ci_hi": d_hi, "n_pairs": len(diffs)}
thresholds = GateThresholds(
min_overall=config.get("min_overall"),
max_drop=config.get("max_drop"),
slice_floors=config.get("slice_floors") or {},
min_cases=int(config.get("min_cases", 1)),
max_cost_usd=config.get("max_cost_usd"),
max_p95_latency_ms=config.get("max_p95_latency_ms"),
)
latencies = [float(r["latency_ms"]) for r in ok_rows(rows) if r.get("latency_ms")]
verdict = evaluate_gate(
current, diffs, thresholds,
baseline_mean=baseline_mean,
cost_usd=manifest_cost(manifest),
latencies_ms=latencies or None,
)
statuses: dict[str, int] = {}
for r in rows:
statuses[r.get("status", "?")] = statuses.get(r.get("status", "?"), 0) + 1
decision = "FAIL" if not verdict.passed else ("WARN" if verdict.warnings else "PASS")
return {
"run": manifest.get("run", run.name),
"git_sha": manifest.get("git_sha"),
"system": manifest.get("system", {}),
"metric": metric,
"decision": decision,
"n_scored": current.n,
"mean": current.mean,
"ci_lo": current.ci_lo,
"ci_hi": current.ci_hi,
"baseline_mean": baseline_mean,
"paired": paired,
"slices": current.slices,
"slice_n": current.slice_n,
"cost_usd": manifest_cost(manifest),
"statuses": statuses,
"failures": verdict.failures,
"warnings": verdict.warnings,
}
def markdown(report: dict[str, Any]) -> str:
lines = [
f"## Eval gate: {report['run']}",
"",
f"**Decision:** `{report['decision']}`"
+ (" — blocking" if report["decision"] == "FAIL"
else " — advisory, does not block" if report["decision"] == "WARN" else ""),
"",
"| Metric | Value |",
"|---|---:|",
f"| Cases scored (`{report['metric']}`) | {report['n_scored']} |",
f"| Mean | {report['mean']:.3f} 95% CI [{report['ci_lo']:.3f}, {report['ci_hi']:.3f}] |",
]
if report["paired"]:
p = report["paired"]
base = report["baseline_mean"]
lines.append(
f"| vs baseline | mean diff {p['mean_diff']:+.3f} "
f"95% CI [{p['ci_lo']:+.3f}, {p['ci_hi']:+.3f}] (n={p['n_pairs']}, baseline {base:.3f}) |"
)
lines += [
f"| Run cost | ${report['cost_usd']:.4f} |" if report["cost_usd"] is not None else "| Run cost | not recorded |",
f"| Row statuses | {', '.join(f'{k} {v}' for k, v in sorted(report['statuses'].items()))} |",
f"| Git SHA | `{report.get('git_sha') or 'unknown'}` |",
"",
f"| Slice (`{report.get('slice_tag', 'type')}`) | n | Mean |",
"|---|---:|---:|",
]
for name in sorted(report["slices"]):
lines.append(f"| {name} | {report['slice_n'].get(name, 0)} | {report['slices'][name]:.3f} |")
if report["failures"]:
lines += ["", "### Failures (blocking)", ""] + [f"- {item}" for item in report["failures"]]
if report["warnings"]:
lines += ["", "### Warnings (advisory)", ""] + [f"- {item}" for item in report["warnings"]]
return "\n".join(lines) + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run", type=Path, required=True, help="run dir (results.jsonl + run.json)")
parser.add_argument("--baseline", type=Path, help="baseline run dir to diff against")
parser.add_argument("--config", type=Path, required=True, help="gate config JSON")
parser.add_argument("--dataset", type=Path, help="eval dataset JSONL for slice floors")
parser.add_argument("--report-json", type=Path)
parser.add_argument("--fail-on-warning", action="store_true",
help="exit 2 on WARN too (advisory becomes blocking)")
args = parser.parse_args()
config = json.loads(args.config.read_text())
report = evaluate(args.run, args.baseline, config, args.dataset)
report["slice_tag"] = config.get("slice_tag", "type")
print(markdown(report))
if args.report_json:
args.report_json.parent.mkdir(parents=True, exist_ok=True)
args.report_json.write_text(json.dumps(report, indent=2, default=str) + "\n")
if report["decision"] == "FAIL" or (args.fail_on_warning and report["decision"] == "WARN"):
return 2
return 0
if __name__ == "__main__":
sys.exit(main())The gate config mirrors GateThresholds field-for-field, plus two adapter keys (metric, slice_tag) that tell the script which score and which dataset tag the floors apply to:
{
"metric": "accuracy",
"slice_tag": "type",
"min_overall": 0.80,
"max_drop": 0.05,
"slice_floors": {"billing": 0.90},
"min_cases": 10,
"max_cost_usd": 1.0,
"max_p95_latency_ms": 5000
}(Format note: the workflows below name the config gates/<tier>.yaml, while this stdlib-only adapter reads JSON because Python's standard library has no YAML parser. The keys are identical; keep one format per project and convert with a YAML loader if you prefer YAML.)
The run directories below are the shapes evalkit.runner.save_run writes — results.jsonl holds one CaseResult row per case-run, run.json the provenance manifest. The candidate run deliberately fails the billing slice and carries one quarantined infra_error row:
{"case_id": "t-001", "status": "ok", "scores": {"accuracy": 1.0}, "latency_ms": 800, "repeat": 0}
{"case_id": "t-002", "status": "ok", "scores": {"accuracy": 0.0}, "latency_ms": 870, "repeat": 0}
{"case_id": "t-011", "status": "infra_error", "scores": {}, "error": "ReadTimeout", "error_kind": "APITimeoutError", "latency_ms": 30000, "repeat": 0}{
"run": "pr-abc1234-openai_gpt-6-luna",
"created_at": "2026-11-06T04:12:00Z",
"git_sha": "abc1234",
"n_results": 12,
"system": {"dataset": "support-triage", "dataset_fp": "9f2c1ab77e30d4b1",
"prompt": "support.ticket-triage@1.1.0", "model": "openai/gpt-6-luna",
"judge": "accuracy@1.0"},
"config": {"workers": 4, "repeats": 1},
"budget": {"calls": 12, "cost_usd": 0.4218}
}Only three rows were shown, so here is a generator that writes the whole fixtures/ tree (12 cases: four billing, five shipping, three account; the baseline passes all of them; the candidate fails t-002 and hits an infrastructure error on t-011). Save it as make_fixtures.py next to scripts/ and run python3 make_fixtures.py:
# make_fixtures.py: writes fixtures/evals, fixtures/runs/{baseline,candidate} and fixtures/gates/pr.json
import json
from pathlib import Path
root = Path("fixtures")
CASES = { # case id -> slice (the "type" tag)
**{f"t-{i:03d}": "billing" for i in (1, 2, 3, 4)},
**{f"t-{i:03d}": "shipping" for i in (5, 6, 7, 8, 11)},
**{f"t-{i:03d}": "account" for i in (9, 10, 12)},
}
(root / "evals").mkdir(parents=True, exist_ok=True)
(root / "evals" / "support-triage.jsonl").write_text("".join(
json.dumps({"example_id": cid, "tags": {"type": kind}}) + "\n" for cid, kind in CASES.items()))
def write_run(dirname: str, run: str, git_sha: str, cost: float, scores: dict) -> None:
"""scores: case id -> accuracy, or None for a case that hit an infrastructure error."""
d = root / "runs" / dirname
d.mkdir(parents=True, exist_ok=True)
rows = []
for i, cid in enumerate(CASES):
if scores[cid] is None:
rows.append({"case_id": cid, "status": "infra_error", "scores": {}, "error": "ReadTimeout",
"error_kind": "APITimeoutError", "latency_ms": 30000, "repeat": 0})
else:
rows.append({"case_id": cid, "status": "ok", "scores": {"accuracy": scores[cid]},
"latency_ms": 800 + 10 * i, "repeat": 0})
(d / "results.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows))
(d / "run.json").write_text(json.dumps({
"run": run, "created_at": "2026-11-06T04:12:00Z", "git_sha": git_sha, "n_results": len(rows),
"system": {"dataset": "support-triage", "dataset_fp": "9f2c1ab77e30d4b1",
"prompt": "support.ticket-triage@1.1.0", "model": "openai/gpt-6-luna",
"judge": "accuracy@1.0"},
"config": {"workers": 4, "repeats": 1},
"budget": {"calls": len(rows), "cost_usd": cost}}, indent=2) + "\n")
write_run("baseline", "main-def5678-openai_gpt-6-luna", "def5678", 0.4011, {c: 1.0 for c in CASES})
candidate = {c: 1.0 for c in CASES}
candidate["t-002"] = 0.0 # a billing case regresses
candidate["t-011"] = None # one case hits an infrastructure error
write_run("candidate", "pr-abc1234-openai_gpt-6-luna", "abc1234", 0.4218, candidate)
(root / "gates").mkdir(parents=True, exist_ok=True)
(root / "gates" / "pr.json").write_text(json.dumps({
"metric": "accuracy", "slice_tag": "type", "min_overall": 0.80, "max_drop": 0.05,
"slice_floors": {"billing": 0.90}, "min_cases": 10,
"max_cost_usd": 1.0, "max_p95_latency_ms": 5000}, indent=2) + "\n")
print("fixtures written")--dataset points at the suite's JSONL so slice floors can be checked; each line is an EvalExample whose tags carry the slice dimensions ({"type": "billing"} in this fixture). Run it against the fixture runs:
PYTHONPATH=. uv run python scripts/eval_gate.py \
--run fixtures/runs/candidate --baseline fixtures/runs/baseline \
--config fixtures/gates/pr.json --dataset fixtures/evals/support-triage.jsonl \
--report-json fixtures/runs/candidate/gate_report.jsonOutput (deterministic; produced by running the script above against the fixtures that make_fixtures.py writes, with the Module 10A evalkit package on the path):
## Eval gate: pr-abc1234-openai_gpt-6-luna
**Decision:** `FAIL` — blocking
| Metric | Value |
|---|---:|
| Cases scored (`accuracy`) | 11 |
| Mean | 0.909 95% CI [0.727, 1.000] |
| vs baseline | mean diff -0.091 95% CI [-0.273, +0.000] (n=11, baseline 1.000) |
| Run cost | $0.4218 |
| Row statuses | infra_error 1, ok 11 |
| Git SHA | `abc1234` |
| Slice (`type`) | n | Mean |
|---|---:|---:|
| account | 3 | 1.000 |
| billing | 4 | 0.750 |
| shipping | 4 | 1.000 |
### Failures (blocking)
- slice 'billing' mean 0.750 < floor 0.900
### Warnings (advisory)
- mean 0.909 passes floor 0.800 but CI [0.727, 1.000] dips below it
- possible drop 0.091 near tolerance 0.050; CI [-0.273, 0.000] too wide to be sure — investigateThe exit code is 2 because the decision is FAIL. Read the report as the gate contract in five lines: the billing slice fell below its floor (blocking), the paired CI says the overall drop is "too wide to tell" (advisory), and the quarantined infra_error row is counted in statuses but never scored — exactly the blocking/advisory split 10A.8, 1.3 and 2.5 prescribe.
Exit-code semantics matter for the workflows: PASS and WARN exit 0; FAIL exits 2. WARN does not block the merge by design — the Module 10A model is that statistical uncertainty is advisory, posted to the PR for a human, because a gate that blocks on noise trains people to re-run until green and then misses the real regression. If your policy wants inconclusive-to-block, pass --fail-on-warning (or have evalkit.cli gate treat warnings as failures for that tier) — but write the choice down, because it changes what a red build means.
Part 4: CI mechanics that survive real repositories#
Deep-dive
4.1 The GitHub Actions spine#
The reference workflows below are deliberately explicit rather than clever. Keep provider keys out of pull-request jobs, make the fast checks a required status check before merge, and pin action versions in your real repository — commit SHAs are better than mutable major tags for supply-chain hygiene, and the majors move faster than most teams expect (the pins below were current in November 2026: checkout v7, setup-uv v10.3.3, upload-artifact v7, download-artifact v8, build-push-action v7, setup-buildx-action v4, attest v4, anchore/sbom-action v0 — latest releases on 9 November 2026: checkout v7.0.1, upload-artifact v7.0.2, download-artifact v8.0.2, setup-buildx-action v4.4.1, build-push-action v7.4.0, attest v4.2.2, sbom-action v0.24.3, setup-uv v10.3.3; every input used in these workflows exists on those majors, which run on Node 24 — check each action's releases page before copying). A cross-run download-artifact (the baseline fetch in the next workflow) also needs actions: read on the token, which a permissions: block that lists only other scopes removes.
# .github/workflows/ci.yml
name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with:
python-version: "3.13"
enable-cache: true
- run: uv sync --locked
- run: uv run ruff check .
- run: uv run pyright
- run: uv run pytest -m "not eval_smoke and not eval_pr and not eval_nightly and not live and not stand_in"
- run: uv run pytest --block-network tests/test_record_replay.py
- run: uv lock --check
- run: uv run python scripts/check_model_deprecations.py --config release/models.json --catalogue fixtures/model_catalogue.json --today 2026-11-06uv sync --locked installs exactly what uv.lock says; uv lock --check proves the lockfile was not hand-edited or left stale (uv docs). The -m expression excludes every eval tier — eval_smoke, eval_pr and eval_nightly are the markers 10A.8's conftest registers, and live/stand_in are 03.10's — so this job runs unit tests and nothing that can reach a provider. The cassette command is the same replay-only pattern as 03.10: no network, no keys, and a miss means the request changed. The deprecation check runs fixture-only here — deterministic, no keys — so a broken model config fails fast on every PR. --today 2026-11-06 freezes the clock: without it, the fixture's 2026-12-01 expiry would turn into an "expired" failure on that date and break every PR for a reason unrelated to the change; the live catalogue check is the nightly job's job (4.4).
4.2 Eval workflow with safe PR behaviour#
This is the release-pipeline side of the eval machinery 10A.8, Part 6 builds: the same evalkit runner, pytest markers and result store (called through the per-tier evalkit.cli spelling from 3.1), wired for environment protection, a model matrix and PR reporting. If you already have evals.yml from Module 10A, these are the additions that make it a release gate — keep one file, not two.
# .github/workflows/eval.yml
name: eval
on:
pull_request:
paths: ["prompts/**", "evals/**", "evalkit/**", "src/**", "release/**", "pyproject.toml", "uv.lock"]
push:
branches: [main]
workflow_dispatch:
inputs:
suite: {description: "smoke|pr|nightly|full", default: "pr"}
model: {description: "model override (provider/model id)", default: ""}
permissions:
contents: read
actions: read # download-artifact reads the baseline from an earlier run
pull-requests: write
concurrency:
group: eval-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
UV_FROZEN: "1"
jobs:
smoke:
# Every PR: the eval_smoke pytest tier on fakes/replay — no keys, seconds.
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with: {python-version: "3.13", enable-cache: true}
- run: uv sync --locked
- run: uv run pytest -m eval_smoke -n auto --junitxml=eval-smoke.xml
env:
EVALKIT_LIVE: "0" # live paths must stay off in the no-key job
- uses: actions/upload-artifact@v7
if: always()
with:
name: eval-smoke-${{ github.sha }}
path: eval-smoke.xml
if-no-files-found: warn
pr-eval:
# Live PR-tier evals, matrix over candidate models — that IS the
# model-comparison harness. Fork PRs get no secrets (see prose below).
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
timeout-minutes: 30
needs: smoke
environment: eval-ci # environment-scoped CI_* secrets
strategy:
fail-fast: false
matrix:
model: ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5"]
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with: {python-version: "3.13", enable-cache: true}
- run: uv sync --locked
- name: fetch accepted baseline
# Baseline is an artefact, not a branch: the run directory produced by
# the last accepted eval, promoted by updating this variable.
uses: actions/download-artifact@v8
continue-on-error: true # first run has no baseline yet
with:
name: eval-baseline
path: runs/baseline
github-token: ${{ secrets.GITHUB_TOKEN }}
repository: ${{ github.repository }}
run-id: ${{ vars.EVAL_BASELINE_RUN_ID }}
- name: map model to provider key and run slug
run: |
case "${{ matrix.model }}" in
openai/*) echo "PROVIDER_KEY=${{ secrets.CI_OPENAI_API_KEY }}" >> "$GITHUB_ENV" ;;
anthropic/*) echo "PROVIDER_KEY=${{ secrets.CI_ANTHROPIC_API_KEY }}" >> "$GITHUB_ENV" ;;
google/*) echo "PROVIDER_KEY=${{ secrets.CI_GEMINI_API_KEY }}" >> "$GITHUB_ENV" ;;
*) echo "PROVIDER_KEY=${{ secrets.CI_OPENROUTER_API_KEY }}" >> "$GITHUB_ENV" ;;
esac
echo "MODEL_SLUG=$(echo '${{ matrix.model }}' | tr '/~' '__')" >> "$GITHUB_ENV"
- name: run PR-tier suite
run: |
uv run python -m evalkit.cli run --suite pr --model "${{ matrix.model }}" \
--out "runs/pr-${{ github.sha }}-${MODEL_SLUG}" --budget-usd 5
env:
EVALKIT_API_KEY: ${{ env.PROVIDER_KEY }}
EVALKIT_LIVE: "1"
- name: gate vs accepted baseline
run: |
# First run: the baseline download above found nothing, so gate on the
# absolute thresholds only instead of failing on a missing directory.
BASELINE=()
if [ -d runs/baseline/latest ]; then BASELINE=(--baseline runs/baseline/latest); fi
uv run python -m evalkit.cli gate \
--run "runs/pr-${{ github.sha }}-${MODEL_SLUG}" \
"${BASELINE[@]}" \
--config gates/pr.yaml
- uses: actions/upload-artifact@v7
if: always()
with:
name: eval-pr-${{ env.MODEL_SLUG }}
path: runs/
if-no-files-found: error
comment:
needs: [smoke, pr-eval]
if: always() && github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v8
with:
pattern: eval-pr-*
merge-multiple: true
- name: Comment eval summary
env:
GH_TOKEN: ${{ github.token }}
run: |
{
echo "## Eval results"
find . -name report.md -not -path './.git/*' | sort | while read -r f; do
echo; echo "### \`${f%/report.md}\`"; cat "$f"
done
} > eval-comment.md
gh pr comment "${{ github.event.pull_request.number }}" --body-file eval-comment.md
continue-on-error: trueFour details matter here. First, pull_request runs the workflow file from the merge commit but, for forks, GitHub withholds secrets and gives a read-only GITHUB_TOKEN (GitHub Docs). The pr-eval condition is the guard: fork PRs get the deterministic smoke tier only — the paths: filter means doc-only PRs never pay for evals, and concurrency.cancel-in-progress means a force-push doesn't run three evals. Second, secrets are scoped to the eval-ci environment, not the repo: you can require reviewers, restrict which branches may use them and rotate keys without editing YAML (environment secrets). The CI_*_API_KEY names are deliberate — they are spend-limited CI keys, distinct from the production keys the service itself uses. Third, the matrix is over models, not suites: the same pr suite runs against each candidate model, which is precisely the model-comparison harness 10A.8, Part 6 describes — each leg lands as its own run directory and artifact, and the comment job posts every leg's report.md as a Markdown table a reviewer can actually read (decision, per-slice means, paired diff vs baseline, cost). Fourth, --budget-usd maps to evalkit.runner.Budget: the run stops at the cap and marks the rest not_run, which the gate treats as underpowered, not failed. if: always() on the comment job means a failed eval still reports its artefacts; the workflow status itself remains failed, so a blocking FAIL still stops the merge.
For providers that support it, prefer OIDC federation over long-lived cloud keys: grant id-token: write only to jobs that deploy, and let the cloud provider exchange the GitHub OIDC token for short-lived credentials. Never put cloud credentials or provider keys in caches, artifacts or PR comments.
4.3 Release workflow: build, scan, attest — deploy is 11C.1's#
# .github/workflows/release.yml
name: release
on:
push:
tags: ["v*"]
workflow_dispatch:
permissions:
contents: read
packages: write
id-token: write
attestations: write
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with: {python-version: "3.13", enable-cache: true}
- uses: docker/setup-buildx-action@v4
- name: Build image
id: build
uses: docker/build-push-action@v7
with:
context: .
push: false
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
outputs: type=docker,dest=/tmp/app.tar
- name: Scan dependencies and emit CycloneDX SBOM
run: |
uv sync --locked
mkdir -p sbom # the redirect below fails if the folder is missing
uv export --format requirements-txt --locked -o /tmp/reqs.txt
# pip-audit exits 1 when it finds a known vulnerability, which fails
# this step on purpose: findings must be visible before anything deploys.
uvx pip-audit -r /tmp/reqs.txt --format cyclonedx-json > sbom/python.cdx.json
# osv-scanner is a standalone Go binary, NOT preinstalled on the runner:
# install a release binary first (see its installation page), or drop this line.
osv-scanner scan source --lockfile=uv.lock
- name: SBOM the image tarball
uses: anchore/sbom-action@v0
with:
image: docker-archive:/tmp/app.tar
format: cyclonedx-json
output-file: sbom/image.cdx.json
upload-artifact: "false"
- name: Attest SBOM
uses: actions/attest@v4
with:
subject-path: /tmp/app.tar
sbom-path: sbom/image.cdx.json
- uses: actions/upload-artifact@v7
if: always()
with:
name: release-${{ github.sha }}
path: |
sbom/
/tmp/app.tar
if-no-files-found: errorThis workflow stops at a verified artefact — deployment itself, registry push and runtime configuration are 11C.1's. What it adds over a plain build:
- A real SBOM, twice over.
pip-audit --format cyclonedx-jsonemits a CycloneDX bill of materials for the resolved Python dependencies, andanchore/sbom-action(Syft under the hood) scans thedocker savetarball directly —docker-archive:is a documented Syft source, so no registry push is needed first. Both land insbom/as evidence. - A signed SBOM attestation.
actions/attestwithsubject-path+sbom-pathproduces an in-toto attestation binding the image tarball to its SBOM, signed with a short-lived Sigstore certificate (Fulcio/Rekor) — verify it later withgh attestation verify. The documented container-image flow —subject-name+subject-digest+push-to-registry: true— applies once 11C.1's pipeline pushes the image to a registry; until then the file-subject attestation above is the honest version. - Immutable identity. The image is tagged by
github.sha; the digest comes from the build output when you push. Dependency findings (pip-audit,osv-scanner) are visible before anything deploys.
4.4 Nightly and scheduled checks#
# .github/workflows/nightly.yml
name: nightly
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
permissions:
contents: read
issues: write
jobs:
live-evals:
runs-on: ubuntu-latest
timeout-minutes: 120
environment: nightly-evals
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with: {python-version: "3.13", enable-cache: true}
- run: uv sync --locked
- name: fetch accepted baseline
uses: actions/download-artifact@v8
continue-on-error: true
with:
name: eval-baseline
path: runs/baseline
github-token: ${{ secrets.GITHUB_TOKEN }}
repository: ${{ github.repository }}
run-id: ${{ vars.EVAL_BASELINE_RUN_ID }}
- name: nightly suite with repeats
run: |
uv run python -m evalkit.cli run --suite nightly --repeats 3 \
--out "runs/nightly-${{ github.run_id }}" --budget-usd 25
env:
EVALKIT_API_KEY: ${{ secrets.CI_OPENROUTER_API_KEY }}
EVALKIT_LIVE: "1"
- name: compare vs baseline
run: |
if [ -d runs/baseline/latest ]; then
uv run python -m evalkit.cli compare \
--run "runs/nightly-${{ github.run_id }}" \
--baseline runs/baseline/latest --markdown > nightly-report.md
else
echo "No accepted baseline yet: nothing to compare." > nightly-report.md
fi
- name: gate nightly suite
run: |
BASELINE=()
if [ -d runs/baseline/latest ]; then BASELINE=(--baseline runs/baseline/latest); fi
uv run python -m evalkit.cli gate \
--run "runs/nightly-${{ github.run_id }}" \
"${BASELINE[@]}" --config gates/nightly.yaml
- uses: actions/upload-artifact@v7
if: always()
with:
name: nightly-evals-${{ github.run_id }}
path: |
runs/nightly-${{ github.run_id }}
nightly-report.md
if-no-files-found: warn
model-lifecycle:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with: {python-version: "3.13", enable-cache: true}
- run: uv sync --locked
- name: Check configured models against provider catalogues
run: |
uv run python scripts/check_model_deprecations.py \
--config release/models.json \
--live --warn-days 60 --fail-on-warning \
--report evals/model_lifecycle.json \
--report-md evals/model_lifecycle.md
- name: Open upgrade issue on findings
if: failure()
env:
GH_TOKEN: ${{ github.token }}
run: gh issue create --title "Model lifecycle check found problems" --body-file evals/model_lifecycle.mdScheduled jobs are where provider drift is caught: model deprecations, judge drift, corpus drift and cost drift do not wait for a pull request. Keep them in protected environments with budgets, and make findings open an issue rather than silently retrying forever.
The model-lifecycle job deserves a closer look because it is the easiest scheduled job to get subtly wrong:
--livefetches only the public OpenRouter catalogue — no key needed. Models whoseproviderisopenai,anthropicorgeminihave no live fetcher yet, so the script reports them asNO DATA(unchecked), not as failures; a nightly job that opens an issue every night for "model not in catalogue" is worse than no job. Extendfetch_openrouter-style fetchers per provider (6.2) and the coverage grows honestly.--fail-on-warningmakes an expiry inside--warn-days 60or adeprecated/legacylifecycle exit non-zero, soif: failure()firesgh issue create. Without it, the exact early warning the watch exists for — "retires in 30 days" — would never open an issue.--report-mdwrites the Markdown table the issue body needs;--reportwrites the JSON artefact. The script creates parent directories itself, soevals/does not have to exist beforehand.
4.5 GitLab CI pattern#
The same contract maps cleanly to GitLab CI. rules decide when a job exists, needs lets eval jobs start without waiting for every earlier stage, artifacts pass result files forward, and environment gives deployment protection (GitLab YAML reference, rules, needs, artifacts).
# .gitlab-ci.yml
stages: [test, eval, release]
variables:
UV_FROZEN: "1"
python-tests:
stage: test
image: python:3.13
before_script:
- pip install uv
- uv sync --locked
script:
- uv run ruff check .
- uv run pyright
- uv run pytest -m "not eval_smoke and not eval_pr and not eval_nightly and not live and not stand_in"
- uv run pytest --block-network tests/test_record_replay.py
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
eval-smoke:
stage: eval
image: python:3.13
needs: [python-tests]
before_script:
- pip install uv
- uv sync
script:
- uv run pytest -m eval_smoke --junitxml=eval-smoke.xml
artifacts:
paths: [eval-smoke.xml]
expire_in: 30 days
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
eval-full:
stage: eval
image: python:3.13
needs: [python-tests]
environment: evals
variables:
EVALKIT_API_KEY: $CI_OPENROUTER_API_KEY
EVALKIT_LIVE: "1"
before_script:
- pip install uv
- uv sync
script:
- uv run python -m evalkit.cli run --suite full --out "runs/full-${CI_PIPELINE_IID}" --budget-usd 10
- uv run python -m evalkit.cli gate --run "runs/full-${CI_PIPELINE_IID}" --baseline runs/baseline/latest --config gates/full.yaml
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "schedule"Note the deliberate divergence from the GitHub pattern: eval-full here runs post-merge on the default branch and on schedule, not on merge requests — the cheaper smoke tier gates MRs, and the expensive live suite runs where it cannot block a contributor's pipeline. That is a defensible tiering, not an oversight; if you want parity with the GitHub pr-eval job, add - if: $CI_PIPELINE_SOURCE == "merge_request_event" to eval-full's rules and protect the CI_* variables so fork pipelines cannot read them. GitLab masked CI/CD variables play the role of environment secrets; protect the variables and limit which environments can read them. As with GitHub, untrusted pipelines should get deterministic checks only.
4.6 Off-the-shelf eval-in-CI tools you will meet#
This lesson builds the gate from evalkit so every decision is visible. Teams often adopt a tool instead; the contract in this lesson (tiers, baselines, paired statistics, protected secrets) is what you check any of them against.
| Tool | How it plugs into CI | What to check before relying on it |
|---|---|---|
| promptfoo (open-source CLI, MIT licence) | A declarative config of prompts, providers and assertions; the official promptfoo/promptfoo-action@v1 GitHub Action runs it on PRs that touch prompt files and posts the result to the PR. Its docs (checked 8 November 2026) require pull-requests: write for the comment and Node.js 22.22 or newer |
Promptfoo announced on 9 March 2026 that it agreed to be acquired by OpenAI and said it "will remain open source" (promptfoo.dev blog post "Promptfoo is joining OpenAI"); the repository README (November 2026) says it is now part of OpenAI and remains open source and MIT licensed. Check the project's governance and multi-provider support before standardising on it |
pytest-based eval libraries (for example DeepEval) and plain pytest |
Evals as parametrised tests, which is the eval_smoke/eval_pr pattern above |
Whether the library gives you paired comparisons and a baseline, or only per-run pass rates |
| Hosted eval and tracing platforms (Braintrust, LangSmith, Langfuse and similar) | Each offers an SDK or CI integration that uploads a run, compares it with a stored baseline and comments on the PR. For Braintrust, the braintrustdata/eval-action@v2 GitHub Action (README read 9 November 2026) runs evals (runtime: node, python or go) and posts a summary comment on the PR, and needs pull-requests: write; for the others see each product's current docs for the exact action or command |
Where your data and keys go, whether the baseline is versioned, whether you can export runs to git, and how a gate verdict maps to a blocking status check |
Whichever you choose, keep the three properties from 3.1: versioned inputs, explicit thresholds and a readable artefact. A tool that only prints a dashboard link is an observation, not a gate.
Part 5: Prompt delivery and release management#
5.1 Repo artefacts vs prompt registries#
04.10 already made the case for versioned prompt files: immutable versions, mutable aliases, content hashes and PR review. CI/CD adds the operational question: where does the running service resolve production from, and who can move it?
| Delivery model | Strengths | Risks | Use when |
|---|---|---|---|
| In-repo files + aliases | Diff review, git history, eval gates in the same PR, easy rollback | Prompt change requires a deploy or config reload | Default for most teams |
| Prompt registry with aliases | Instant promotion/rollback, non-engineer editing, per-environment labels | Changes can bypass code review unless registry writes are gated | Non-engineers edit daily, many tenants, or you need sub-minute rollback |
| Provider/hosted presets | Vendor-integrated routing and prompt config | Lock-in, less portable, may include model routing you did not review | You already accept the platform boundary |
The registry options verified in 04.10, 6.5 converge on the same model: immutable versions plus mutable environment pointers. Langfuse uses labels such as production, LangSmith uses commit tags, MLflow uses aliases, and OpenRouter presets are versioned request configurations. Whatever you choose, keep a canonical export in git and require the same eval evidence before a registry alias moves.
flowchart LR
DEV["dev alias and dev model"] --> GATE1{"Render tests and cassette eval pass?"}
GATE1 -->|"yes"| STAGE["staging alias and candidate model"]
GATE1 -->|"no"| FIX["Fix in the pull request"]
STAGE --> GATE2{"Full eval, live smoke and cost review pass?"}
GATE2 -->|"yes"| APPROVAL["Environment approval"]
GATE2 -->|"no"| FIX
APPROVAL --> PROD["production alias and pinned model"]
PROD --> CANARY["Canary traffic and monitors"]
CANARY --> GATE3{"Canary gate and online evals pass?"}
GATE3 -->|"yes"| FULL["Progressive rollout to 100%"]
GATE3 -->|"no"| ROLL["Move alias or flag back"]
ROLL --> PROD5.2 Promotion rules that keep registries honest#
If you use a registry, treat alias promotion as a deploy:
- The prompt version is immutable and its content hash is recorded.
dev/stagingaliases may move after automated eval gates.productionrequires an environment approval, an eval report artefact and a named owner.- Rollback is a pointer move to the previous immutable version, not an edit.
- Every runtime call logs
prompt_name,prompt_version,prompt_sha256(04.10'scontent_hash),model_id,alias_source(04.10'sresolved_from) and trace ID (11A.1). - A registry change must never bypass the safety suite owned by Module 12.
For A/B or canary prompt variants, use deterministic bucketing and sticky assignment as in 04.10, 8.2, then measure with 10A.9. The CI system should record which variant served each request so post-deploy analysis can attribute regressions.
5.3 The prompt-change PR template#
## Prompt change
- Prompt: `support.ticket-triage` — 1.0.0 → 1.1.0
- Model: `gpt-6-luna` (unchanged / changed from ___)
- Change class: mechanics / semantics / model / retrieval / dependency
- What changed: <one paragraph>
- Render tests: <pass/fail>
- Prompt diff: <link or pasted `diff_versions` output>
- Eval smoke: <decision, cases, pass rate>
- Eval full: <decision, baseline delta, slices>
- Cost/latency delta: <expected or measured>
- Rollback: move `production` alias to 1.0.0 / redeploy image digest ___
- Safety review: <required / not required, link>The template is not bureaucracy; it is the minimum evidence needed to answer "what exactly changed, what proved it was safe, and how do we undo it?" in an incident.
Part 6: Model change management#
6.1 Pin snapshots, not vibes#
02.9, Part 8 established the rule: production uses pinned snapshots or provider IDs whose lifecycle is understood, never floating latest aliases. CI/CD turns that into a checked artefact.
Keep a machine-readable model inventory:
{
"models": [
{"role": "chat_primary", "provider": "openrouter", "id": "openai/gpt-6-luna", "allow_alias": false},
{"role": "chat_fallback", "provider": "openrouter", "id": "anthropic/claude-haiku-5.5", "allow_alias": false},
{"role": "classifier", "provider": "openai", "id": "gpt-6-luna", "allow_alias": false}
]
}The inventory uses OpenRouter slugs only to show the provider field; with direct keys the same entries read "provider": "openai" and "provider": "anthropic", which is the primary setup in this course.
Each entry should also live in the capability registry from 03.11 or your own config, with owner, purpose, data policy, eval suite and deprecation review date.
6.2 Lifecycle checks and deprecation watch#
Provider lifecycle surfaces differ, so normalise them into one report. As of November 2026:
- OpenAI
GET /v1/models/ SDKmodels.list()exposesshutdown_dateon model objects; the deprecations page documents notice periods (OpenAI docs, models API). - Anthropic
models.list()exposes lifecycle fields such aslifecycleandretires_atin the Module 02 verified examples (02.9, Anthropic models, deprecations). - Gemini (optional provider) model metadata and deprecation pages must be checked on Google's official model/deprecation surfaces (Gemini models).
- OpenRouter (optional gateway) catalogue entries expose
expiration_datefor gateway removal andalias_targetfor floating aliases (OpenRouter models API, 02.9 lifecycle check).
The script below is a skeleton: it checks a config against a normalised catalogue JSON, and can fetch the public OpenRouter catalogue without a key. Extend it with provider SDK calls for OpenAI and Anthropic first (Gemini optional) in the same shape.
# scripts/check_model_deprecations.py
"""Check configured model IDs against a normalized catalogue.
Catalogue JSON shape:
{"openrouter": {"vendor/model": {"expiration_date": "2026-12-01",
"alias_target": {"slug": "vendor/new"}}},
"openai": {"gpt-6-luna": {"shutdown_date": null}},
"anthropic": {"claude-sonnet-5-5": {"lifecycle": "active", "retires_at": null}}}
"""
from __future__ import annotations
import argparse
import json
import sys
import urllib.request
from datetime import date, datetime
from pathlib import Path
from typing import Any
OPENROUTER_URL = "https://openrouter.ai/api/v1/models"
EXPIRY_KEYS = ("shutdown_date", "retires_at", "deprecation_date", "expiration_date")
FLOATING_PARTS = ("latest", "-preview", "-beta", "~")
def parse_date(value: Any) -> date | None:
if not value:
return None
text = str(value)[:10]
try:
return date.fromisoformat(text)
except ValueError:
return None
def is_floating(model_id: str) -> bool:
return model_id.startswith("~") or any(part in model_id for part in FLOATING_PARTS)
def fetch_openrouter() -> dict[str, Any]:
with urllib.request.urlopen(OPENROUTER_URL, timeout=30) as response:
data = json.loads(response.read().decode())
return {"openrouter": {m["id"]: m for m in data.get("data", [])}}
def load_catalogue(path: Path | None, live: bool) -> dict[str, Any]:
catalogue = fetch_openrouter() if live else {}
if path:
file_catalogue = json.loads(path.read_text())
for provider, models in file_catalogue.items():
catalogue.setdefault(provider, {}).update(models)
return catalogue
def entry_expiry(entry: dict[str, Any]) -> date | None:
for key in EXPIRY_KEYS:
parsed = parse_date(entry.get(key))
if parsed:
return parsed
return None
def check_model(model: dict[str, Any], catalogue: dict[str, Any], today: date, warn_days: int) -> dict[str, Any]:
provider, model_id = model.get("provider"), model.get("id")
problems: list[str] = []
warnings: list[str] = []
base = {"role": model.get("role"), "provider": provider, "id": model_id,
"problems": problems, "warnings": warnings}
if provider not in catalogue:
# No live fetcher covers this provider yet: report NO DATA, not a
# failure — otherwise every nightly run opens an issue for models the
# script was never able to check.
return {**base, "status": "unchecked",
"note": f"no catalogue source for provider '{provider}' — extend fetch_<provider>()"}
entry = catalogue.get(provider, {}).get(model_id)
if entry is None:
problems.append(f"{provider}/{model_id}: not present in catalogue")
return {**base, "status": "fail"}
if entry.get("alias_target") and not model.get("allow_alias"):
problems.append(f"{provider}/{model_id}: floating alias -> {entry['alias_target'].get('slug')}")
if is_floating(model_id) and not model.get("allow_alias"):
problems.append(f"{provider}/{model_id}: model ID looks like a floating alias")
lifecycle = str(entry.get("lifecycle", "")).lower()
if lifecycle == "retired":
problems.append(f"{provider}/{model_id}: lifecycle is retired")
elif lifecycle in {"deprecated", "legacy"}:
warnings.append(f"{provider}/{model_id}: lifecycle is {lifecycle}")
expiry = entry_expiry(entry)
if expiry:
delta = (expiry - today).days
if delta < 0:
problems.append(f"{provider}/{model_id}: expired {expiry.isoformat()}")
elif delta <= warn_days:
warnings.append(f"{provider}/{model_id}: expires {expiry.isoformat()} ({delta} days)")
return {**base, "status": "fail" if problems else ("warn" if warnings else "ok"),
"expires": expiry.isoformat() if expiry else None}
def markdown(reports: list[dict[str, Any]]) -> str:
lines = ["## Model lifecycle check", "", "| Role | Model | Result |", "|---|---|---|"]
for row in reports:
if row.get("status") == "unchecked":
status = f"NO DATA: {row.get('note', '')}"
else:
status = "FAIL" if row["problems"] else ("WARN" if row["warnings"] else "OK")
status += ": " + ("; ".join(row["problems"] + row["warnings"]) or "pinned")
lines.append(f"| {row.get('role')} | `{row.get('provider')}/{row.get('id')}` | {status} |")
return "\n".join(lines) + "\n"
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=Path, required=True)
parser.add_argument("--catalogue", type=Path)
parser.add_argument("--live", action="store_true", help="Fetch the public OpenRouter catalogue")
parser.add_argument("--warn-days", type=int, default=60)
parser.add_argument("--report", type=Path)
parser.add_argument("--report-md", type=Path, help="Markdown table for issue bodies")
parser.add_argument("--fail-on-warning", action="store_true")
parser.add_argument("--today", type=date.fromisoformat,
help="pretend today is this ISO date: makes fixture runs deterministic")
args = parser.parse_args()
config = json.loads(args.config.read_text())
catalogue = load_catalogue(args.catalogue, args.live)
today = args.today or date.today()
reports = [check_model(m, catalogue, today, args.warn_days) for m in config.get("models", [])]
failures = sum(r.get("status") == "fail" for r in reports)
warnings = sum(r.get("status") == "warn" for r in reports)
print(markdown(reports))
for out in (args.report, args.report_md):
if out:
out.parent.mkdir(parents=True, exist_ok=True)
if args.report:
args.report.write_text(json.dumps({"checked_at": today.isoformat(), "models": reports}, indent=2) + "\n")
if args.report_md:
args.report_md.write_text(markdown(reports))
if failures or (args.fail_on_warning and warnings):
return 2
return 0
if __name__ == "__main__":
sys.exit(main())A matching fixture lets CI run without keys:
{
"openrouter": {
"openai/gpt-6-luna": {"expiration_date": null},
"anthropic/claude-haiku-5.5": {"expiration_date": "2026-12-01"},
"openai/gpt-4-32k": {"expiration_date": "2026-10-01"}
},
"openai": {"gpt-6-luna": {"shutdown_date": null}},
"anthropic": {"claude-sonnet-5-5": {"lifecycle": "active", "retires_at": null}}
}6.3 Model upgrade playbook#
sequenceDiagram
participant CI as Scheduled CI
participant Cat as Provider catalogues
participant Eval as evalkit
participant Rel as Release config
CI->>Cat: List models and lifecycle fields
Cat-->>CI: Pinned IDs, aliases and expiry dates
CI->>Eval: Shadow suite on candidate model
Eval-->>CI: Score, cost and latency deltas
CI->>Rel: Open model-upgrade pull request
Rel-->>CI: Canary then promote or rollback- Detect — nightly
check_model_deprecations.py --liveplus provider notice emails/changelogs. - Choose replacement — use 02.9, Part 10 and your own eval set, not leaderboard position.
- Shadow evaluate — run the candidate on the full suite without serving traffic; compare quality, cost, latency and slices.
- Canary — route a small percentage or internal tenants first; watch 11A.2 metrics and 10A.9 sampled quality.
- Promote or roll back — move the model flag/alias; rollback is the same pointer move in reverse.
- Retire deliberately — keep the old snapshot available until the notice period ends and traces no longer need reproduction.
SDK bumps follow the same discipline: a provider SDK can change request serialisation, retry defaults, error types or streaming events. Treat openai, anthropic, google-genai, HTTP client and eval-library upgrades as release-unit changes — 03.11, 13.9 is the dependency-hygiene checklist they must pass — run cassette and contract tests, and prefer Renovate/Dependabot PRs so the upgrade is reviewed like code (Dependabot, Renovate).
Part 7: Data, index and dependency releases#
Deep-dive
7.1 Ingestion and index CI#
Retrieval changes are release-unit changes even when no prompt or model changed. 05.9 owns incremental ingestion, manifests, blue/green indexes and shadow evaluation; 06.10 owns retrieval metrics; 05.10 owns the per-stage data-quality checks that validate the corpus before it reaches an index. CI/CD's job is to make those mechanisms repeatable:
| Change | Pipeline stage | Gate |
|---|---|---|
| Corpus document added/edited/deleted | Ingestion job on staging index | Manifest diff, per-document isolation, freshness checks |
| Chunker/cleaner/embed-input change | Rebuild candidate index | Chunk diff report, embedding reuse estimate, smoke retrieval eval |
| Embedding model change | Full re-embed into green index | Retrieval eval, answer eval, cost/latency estimate |
| ACL/filter change | Index plus query path tests | Permission tests, negative retrieval tests |
| Index promotion | Alias flip | Shadow eval report, rollback alias kept |
flowchart LR
SRC["Manifest and raw documents"] --> BLUE["blue index serving production"]
SRC --> GREEN["green index built with new embedder or chunker"]
GREEN --> SHADOW["Shadow retrieval and answer eval"]
SHADOW --> GATE{"Quality, latency and cost gates pass?"}
GATE -->|"yes"| FLIP["Repoint prod alias and promote manifest"]
GATE -->|"no"| KEEP["Keep blue live and retire green later"]
FLIP --> BLUE
KEEP --> BLUEThe CI rule is strict: never promote an index alias without the manifest version that produced it. A green index built from manifest v14 must not be paired with a live manifest still at v13. 05.9, 5.2 explains why the manifest and index flip together; CI should encode that as one release record.
7.2 Dataset versioning for evals#
Eval datasets are release inputs too. A prompt or model change is meaningless without knowing which cases judged it. Store datasets as versioned artefacts: JSONL/Parquet plus a dataset card, content hash, split definitions and provenance. CI should fail if an eval run lacks dataset_hash, prompt_versions, model_ids, judge_version and git_sha. 10A.2 owns dataset construction; this lesson only requires the pipeline to carry the version forward into the gate report.
Part 8: Release, rollout and rollback#
8.1 Progressive rollout for LLM services#
Deploying code is only half the release. The release unit also includes prompt aliases, model flags, retrieval config and index aliases. Roll out in stages so each stage can falsify a different assumption:
| Stage | Traffic | Evidence required | Failure action |
|---|---|---|---|
| Build/scan | 0% | Unit/contract tests, eval gate, image scan, SBOM | Do not deploy |
| Staging | Internal only | Live smoke, full eval, cost report | Fix or abandon |
| Canary | ~1-5% | Error rate, latency, refusal rate, sampled quality, cost | Roll back pointers |
| Partial | ~25% | SLO budget, online eval drift, support signals | Pause or roll back |
| Full | 100% | Sustained monitors, eval comparison | Roll back and post-incident review |
The rollback target must be recorded before rollout: image digest, prompt alias versions, model IDs, index alias and config hash. A rollback that requires rebuilding "what was live yesterday" is not a rollback plan.
The table above is the manual version of progressive delivery. Metric-triggered promotion and rollback is what dedicated controllers automate: Flagger and Argo Rollouts watch Prometheus metrics (error rate, latency, custom KPIs) during a canary and auto-abort or roll back when thresholds break (Flagger docs, Argo Rollouts). For LLM services the same pattern applies with an LLM twist — the "metric" can be a sampled eval score or a refusal-rate proxy from 11A.2, not just HTTP health. If you do not run a progressive-delivery controller, the minimum viable version is an orchestrator or scheduled check that queries your metrics, compares them to the pre-deploy window, and calls the rollback pointer-flip itself — but write the thresholds down before the deploy, not during the incident.
8.2 Post-deploy verification#
After deploy, run three cheap checks before widening traffic:
- Smoke requests — one or two real calls per critical feature, asserting schema validity and expected route, not exact prose.
- Synthetic probes — scheduled canary prompts from 11A.2 that exercise retrieval, tools and refusal paths.
- Metric comparison — error rate, TTFT/p95 latency, token cost, fallback rate and refusal rate against the pre-deploy window.
If a probe fails, the release system should be able to move the affected pointer back without a full code rollback: prompt alias to previous version, model flag to previous snapshot, index alias to previous index. Only when the failure is in code or infrastructure should the image itself roll back.
Two cheap habits make post-deploy verification actually work at 3 a.m.:
- Annotate the dashboards. Deploy, prompt-alias, model-flag and index-alias changes should each emit an annotation/event on your metrics dashboards (Grafana annotations, Datadog events, your platform's equivalent), so a metric move can be lined up with the release that caused it. 11A.2 owns the dashboards; the deploy step owns emitting the marker — without it, "quality dropped at 02:14" and "we deployed at 02:13" stay separate facts.
- Record the canary verdict. Whether the rollout was promoted by a human, a Flagger/Argo-style metric check, or your own scheduled probe, write the decision and the metric window into the release evidence (9.3) — "auto-promoted at 25% after 30 minutes inside SLO" is audit-grade; "it seems fine" is not.
8.3 Failure gallery#
| Failure | Why it happens | Gate that should catch it |
|---|---|---|
| Fork PR steals provider key | Secrets exposed to untrusted workflow code | pull_request only, no secrets, environment protection |
| Prompt change bypasses review | Registry alias edited in UI | Registry write requires eval artefact and approval |
| Model alias silently changes | latest/~latest resolves to new snapshot |
Lifecycle check rejects floating aliases |
| Eval gate flakes shut down merges | One run treated as truth, or point-estimate gates on noisy metrics | Paired bootstrap CIs, WARN advisory outcome, allow-lists with expiry (10A.8) |
| Cassette hides prompt regression | Replay returns old answer | Cassette checks plumbing; eval gate checks behaviour |
| Index alias flips without manifest | Manual console change | Release record binds index+manifest+embedder versions |
| Dependency bump breaks provider SDK | Lockfile updated without contract tests | Cassette/mock-transport tests on every dependency PR |
| Deploy kills streams | No drain/rollback plan | 11C.1 owns graceful shutdown; CI verifies rollback pointer exists |
| Cost spike after model swap | Price/latency not in gate | Cost and p95 budgets in eval_gate.py and canary metrics |
| Secrets in logs/artifacts | Eval output contains prompts or keys | Redaction, cassette lint, artifact allow-lists |
8.4 Releasing an agent change: manifest, canary and rollback#
An agent change is a release-unit change with three extra hazards: a new tool can do something new, a longer loop costs more per task, and a flaky tool shows up as retries rather than as a failed request. The release machinery is the same as 8.1, with an agent manifest as the thing being versioned and agent metrics as the canary evidence.
The sketch below is pure stdlib, with fake runs standing in for real traffic. It has four parts:
AgentSpec: the manifest. It pins the model snapshot, prompt version, tool set (each tool with its schema version) and the loop limits, and hashes them into a digest.changed_fieldsandgates_for: what changed decides which gates run, the same idea as 1.4 applied to an agent.Router: two pointers,stableandcanary. Users are assigned to a bucket by a hash of their id, so one user keeps the same version for the whole canary.canary_verdict: thresholds on the agent signals from 11A.2, 4.8 (tool error rate, cost per run) plus a sampled quality score. They are written down before the rollout.
# agent_release.py: version an agent, canary it, roll it back (stdlib only)
from __future__ import annotations
import hashlib
import json
import random
from dataclasses import asdict, dataclass
@dataclass(frozen=True)
class AgentSpec:
"""Everything that decides how the agent behaves, as one versioned unit."""
agent_id: str
version: str
model: str # a pinned snapshot, never a floating alias
prompt: str # prompt name@version
tools: tuple[str, ...] # the tool set (each entry name@schema-version)
max_steps: int
max_cost_usd: float
def digest(self) -> str:
blob = json.dumps(asdict(self), sort_keys=True).encode()
return "sha256:" + hashlib.sha256(blob).hexdigest()[:12]
def changed_fields(old: AgentSpec, new: AgentSpec) -> dict[str, tuple]:
a, b = asdict(old), asdict(new)
return {k: (a[k], b[k]) for k in a if a[k] != b[k] and k != "version"}
def gates_for(changes: dict) -> list[str]:
"""Map what changed to the gates it needs (the 1.4 risk table, for agents)."""
gates = ["unit and contract tests"]
if "prompt" in changes:
gates.append("full prompt eval + trajectory eval")
if "model" in changes:
gates.append("shadow eval on the full suite + canary")
if "tools" in changes:
gates.append("schema lint + trajectory tests + security review")
if "max_steps" in changes or "max_cost_usd" in changes:
gates.append("cost and step-cap review + canary")
return gates
class Router:
"""Two pointers: stable and canary. Rollback is flipping the canary off."""
def __init__(self, stable: AgentSpec):
self.stable, self.canary, self.pct = stable, None, 0
def start_canary(self, spec: AgentSpec, pct: int) -> None:
self.canary, self.pct = spec, pct
def pick(self, user_id: str) -> AgentSpec:
bucket = int(hashlib.sha256(user_id.encode()).hexdigest(), 16) % 100
return self.canary if self.canary and bucket < self.pct else self.stable
def promote(self) -> None:
self.stable, self.canary, self.pct = self.canary, None, 0
def rollback(self) -> None:
self.canary, self.pct = None, 0
def fake_run(spec: AgentSpec, rng: random.Random) -> dict:
"""Stand-in for a real agent run: v1.3.0 adds a tool that is flaky and loops."""
flaky = "lookup_invoice@2" in spec.tools
steps = max(1, round(rng.gauss(7 if flaky else 5, 2)))
tool_calls = steps - 1
tool_errors = sum(rng.random() < (0.06 if flaky else 0.008)
for _ in range(tool_calls))
return {"steps": steps, "tool_calls": tool_calls, "tool_errors": tool_errors,
"cost": 0.012 * steps * rng.uniform(0.8, 1.2),
"judge_pass": rng.random() < (0.90 if flaky else 0.91)}
def summarise(runs: list[dict]) -> dict:
calls = sum(r["tool_calls"] for r in runs)
return {"runs": len(runs),
"tool_error_rate": sum(r["tool_errors"] for r in runs) / calls,
"cost_per_run": sum(r["cost"] for r in runs) / len(runs),
"judge_pass": sum(r["judge_pass"] for r in runs) / len(runs)}
def canary_verdict(stable: dict, canary: dict) -> tuple[str, list[str]]:
"""Thresholds are written down BEFORE the rollout, not during the incident."""
reasons = []
if canary["tool_error_rate"] > max(0.02, 2 * stable["tool_error_rate"]):
reasons.append(f"tool error rate {canary['tool_error_rate']:.1%} "
f"vs stable {stable['tool_error_rate']:.1%}")
if canary["cost_per_run"] > 1.25 * stable["cost_per_run"]:
reasons.append(f"cost per run ${canary['cost_per_run']:.4f} "
f"vs stable ${stable['cost_per_run']:.4f}")
# ~200 canary runs cannot resolve a 3-point drop (noise is about +-4 points),
# so this threshold is wide on purpose; widen the canary to tighten it.
if canary["judge_pass"] < stable["judge_pass"] - 0.05:
reasons.append(f"judge pass {canary['judge_pass']:.1%} "
f"vs stable {stable['judge_pass']:.1%}")
return ("ROLLBACK" if reasons else "PROMOTE"), reasons
def canary_run(router: Router, candidate: AgentSpec, rng: random.Random) -> str:
router.start_canary(candidate, pct=10)
by_version = {router.stable.version: [], candidate.version: []}
for i in range(2000):
spec = router.pick(f"user-{i}")
by_version[spec.version].append(fake_run(spec, rng))
stable_s = summarise(by_version[router.stable.version])
canary_s = summarise(by_version[candidate.version])
print(f" traffic: stable={stable_s['runs']} canary={canary_s['runs']} runs")
for name, m in (("stable", stable_s), ("canary", canary_s)):
print(f" {name:<7} tool_err={m['tool_error_rate']:.2%} "
f"cost/run=${m['cost_per_run']:.4f} judge={m['judge_pass']:.1%}")
verdict, reasons = canary_verdict(stable_s, canary_s)
if verdict == "PROMOTE":
router.promote()
else:
router.rollback()
print(f" verdict: {verdict}" + (" <- " + "; ".join(reasons) if reasons else ""))
return verdict
v1_2 = AgentSpec("support_agent", "1.2.0", "openai/gpt-6-luna",
"support.triage@4", ("search_docs@3", "get_order@1"), 20, 0.25)
v1_3 = AgentSpec("support_agent", "1.3.0", "openai/gpt-6-luna",
"support.triage@4", ("search_docs@3", "get_order@1",
"lookup_invoice@2"), 20, 0.25)
v1_4 = AgentSpec("support_agent", "1.4.0", "openai/gpt-6-luna",
"support.triage@5", ("search_docs@3", "get_order@1"), 20, 0.25)
router = Router(v1_2)
print(f"live: {router.stable.version} {router.stable.digest()}")
for candidate in (v1_3, v1_4):
changes = changed_fields(router.stable, candidate)
print(f"\ncandidate {candidate.version} {candidate.digest()}")
print(" changed:", {k: f"{o} -> {n}" for k, (o, n) in changes.items()})
print(" gates: ", "; ".join(gates_for(changes)))
canary_run(router, candidate, random.Random(42))
print(f" live now: {router.stable.version} {router.stable.digest()}")live: 1.2.0 sha256:614c0ca6afb7
candidate 1.3.0 sha256:0807e014b58b
changed: {'tools': "('search_docs@3', 'get_order@1') -> ('search_docs@3', 'get_order@1', 'lookup_invoice@2')"}
gates: unit and contract tests; schema lint + trajectory tests + security review
traffic: stable=1801 canary=199 runs
stable tool_err=0.74% cost/run=$0.0606 judge=91.1%
canary tool_err=6.28% cost/run=$0.0831 judge=89.4%
verdict: ROLLBACK <- tool error rate 6.3% vs stable 0.7%; cost per run $0.0831 vs stable $0.0606
live now: 1.2.0 sha256:614c0ca6afb7
candidate 1.4.0 sha256:72e3c512f144
changed: {'prompt': 'support.triage@4 -> support.triage@5'}
gates: unit and contract tests; full prompt eval + trajectory eval
traffic: stable=1801 canary=199 runs
stable tool_err=0.68% cost/run=$0.0601 judge=91.8%
canary tool_err=0.89% cost/run=$0.0602 judge=92.0%
verdict: PROMOTE
live now: 1.4.0 sha256:72e3c512f144What to take from the output:
- 1.3.0 added a tool. The change shows up as
tools, so the gates include a security review. In the canary, quality looks fine (89.4% against 91.1%, inside the margin), but the tool error rate is about eight times higher and the cost per run is 37% up. A quality-only check would have promoted it. The verdict isROLLBACK, and rollback is one call (router.rollback()): thecanarypointer is cleared and 100% of traffic is back on 1.2.0. No image rebuild and no redeploy. - 1.4.0 changed only the prompt. It needs the prompt-eval and trajectory gates, passes the canary and is promoted. The next candidate is compared against 1.4.0.
- Keep the previous manifest. Before you promote, write the outgoing manifest (here 1.2.0 and its digest) into the release evidence (9.3) as the rollback target. A rollback that needs "what was live yesterday" is not a rollback plan (8.1).
- The canary is small, so its thresholds are wide. About 200 runs cannot resolve a 3-point quality change. Use the wide margin as a tripwire, and let the statistics of 10A.8, Part 2 and a larger canary make the finer calls.
In production the Router is a feature flag or a service-mesh weight, the fake runs are real run records, and the metrics come from the agent counters and histograms in 11A.2. Annotate the dashboards with the agent version and digest at every flip (8.2), so a step or cost change lines up with the release that caused it. Budgets and kill switches for agents (what to cut off when a canary is burning money) belong to 11B.6 and 11B.7.
Part 9: Reproducibility, policy and audit#
Deep-dive
9.1 Reproducible environments#
CI should reproduce the developer environment rather than approximate it. For Python, that means pyproject.toml plus uv.lock, uv sync --locked, pinned Python version and a lockfile check in CI (uv docs). A .devcontainer/devcontainer.json extends the same idea to editors — the Dev Container spec lets VS Code and compatible tools boot the identical image, tools and extensions CI uses, so "works on my machine" and "works in CI" converge on one definition. For containers, pin the base image digest and scan the final image. For prompts and models, pin versions and hashes. For evals, pin dataset and judge versions.
The same discipline applies one level up: infrastructure and policy as code. Environments, IAM roles, registry rules, network policy and the pipeline definitions themselves (.github/workflows/, *.tf, *.yaml) are code — lint them (actionlint, tflint, your cloud's policy checker), review them in PRs, and keep them inside the release unit. 11C.1 owns the deployment-side IaC (Terraform/Pulumi/CDK for the service itself); this lesson's point is narrower: a workflow that can mint credentials or move a production alias is a release, and it deserves the same gates as one.
9.2 Least privilege and secrets hygiene#
- Give each job the minimum
permissions:it needs;contents: readis the safe default. - Put provider keys in protected environments or masked CI variables, never in caches, artifacts, PR comments or workflow logs.
- Use OIDC federation for cloud deploy credentials where supported instead of long-lived secrets.
- Never run untrusted fork code with secrets; use
pull_request, notpull_request_target, for code from forks (GitHub Docs). - Treat caches as untrusted input: do not cache secrets or provider responses containing sensitive data (GitHub dependency caching).
- Sign what you ship where the platform supports it:
actions/attestproduces Sigstore-signed attestations for images and SBOMs (4.3); verify them at deploy time rather than trusting an unsigned artefact. cosign/Sigstore cover the same ground for registries and binaries outside GitHub (Sigstore docs).
9.3 Release evidence and audit trail#
Every release should produce a compact record answering: what changed, what evidence passed, who approved it, what was deployed, and how to undo it.
{
"release_id": "2026-11-06-support-triage-1.1.0",
"git_sha": "abc1234",
"image_digest": "sha256:...",
"prompts": {"support.ticket-triage": {"version": "1.1.0", "hash": "sha256:..."}},
"models": {"primary": "openai/gpt-6-luna"},
"index": {"alias": "prod", "manifest_hash": "sha256:..."},
"evals": {"smoke": "PASS", "full": "PASS", "baseline_delta": "+0.4%"},
"approvals": ["release-manager"],
"rollback": {"prompt_alias": "1.0.0", "image": "sha256:previous"}
}Store this as an artefact and, where your platform supports it, attach it to the deployment or release object. 11C.4 owns governance, incident review and the production checklist; this lesson only ensures the evidence exists before you need it.
Release notes from eval diffs. The same evidence generates the release notes almost for free: evalkit.cli compare --run <new> --baseline <old> --markdown produces the paired mean difference with its confidence interval (plus a per-slice table when you pass --slice-dim), and the gate reports carry the verdicts. A release-notes job can concatenate those into "what changed and what it did to quality" — which slices moved, which cases flipped (join the two results.jsonl files on case_id for that), cost and latency deltas — instead of a hand-written summary that drifts from the evidence. Keep the generated section next to the release-evidence JSON; reviewers trust notes they can trace to a run directory.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A prompt change is not a code change." | It changes production behaviour, so it needs versioning, review, eval gates and rollback just like code. |
| "JSON mode or structured output makes evals unnecessary." | It constrains format, not truth; semantic and business correctness still need evals. |
| "Run the full eval suite on every commit." | That is too slow and too expensive; use tiered smoke/full/nightly suites and statistical gates. |
| "A green CI run means the model is safe." | CI proves the tested release unit passed its gates; safety, privacy and adversarial review belong to Module 12 and production monitoring. |
| "Prompt registries remove the need for git." | They move the system of record; keep canonical exports and require eval evidence before alias promotion. |
"Model latest aliases are convenient in production." |
They make behaviour, cost and lifecycle non-reproducible; pin snapshots and check deprecations. |
| "Dependency updates are routine and safe." | SDK changes can alter wire formats, retries, errors and streaming; treat them as release-unit changes. |
| "Rollback means redeploy yesterday's code." | For LLM systems it may mean moving prompt/model/index aliases while keeping the same image; record every pointer. |
Key takeaways#
- The release unit includes prompts, models, tools, schemas, retrieval config, indexes, guardrails, dependencies and data — not just application code.
- Use a test pyramid: deterministic unit/contract/cassette checks on every PR, statistical eval smoke for relevant changes, full eval gates before merge, live smoke after deploy and online evaluation in production.
- Classify changes by risk and run the smallest gate set that can falsify the risky assumption.
- Keep provider keys out of fork PRs; use protected environments, least-privilege permissions and OIDC where possible.
- Treat prompt aliases and model flags as deployment pointers: immutable versions, mutable aliases, approvals and instant rollback.
- Pin model snapshots, monitor lifecycle/deprecation surfaces, shadow-evaluate replacements and canary before promotion.
- Ship index changes blue/green with manifest+index+embedder versions bound together.
- Produce release evidence: git SHA, image digest, prompt/model/index versions, eval reports, approvals and rollback targets.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Release unit | The set of code, prompts, models, tools, schemas, retrieval config, indexes, guardrails, dependencies and data versioned and rolled back together |
| Eval gate | A policy that turns an evalkit run directory into a blocking FAIL, advisory WARN or PASS using GateThresholds and a baseline run |
| Smoke suite | A small high-signal eval tier run frequently to catch obvious regressions |
| Full suite | The larger statistical eval tier run before merge, nightly or pre-release |
| Canary eval | Production-sampled quality checks used during progressive rollout |
| Change-risk class | A label for what changed, used to select the required gates |
| Environment protection | CI/CD rules that restrict secrets and deployments to approved branches/actors |
| OIDC federation | Short-lived cloud credentials exchanged from a CI OIDC token instead of stored secrets |
| Prompt registry | A managed store of versioned prompts with aliases or labels for environments |
| Model inventory | A machine-readable list of configured model roles, providers, IDs and policies |
| Shadow evaluation | Running a candidate model/index on eval traffic without serving users |
| Progressive rollout | Serving a release to increasing traffic percentages while monitoring gates |
| Release evidence | The artefact recording versions, eval results, approvals and rollback targets |
| Agent manifest | A small versioned file pinning an agent's prompt, model snapshot, tool set and loop limits, hashed to a digest so the whole agent is promoted and rolled back as one unit |
| Canary pointer | The release pointer that sends a small, sticky share of users to the candidate version; clearing it is the rollback |
| Run directory | The evalkit.cli run output — results.jsonl + run.json + report.md — that gates, compares and audits all read |
| SBOM | A software bill of materials listing dependencies in a release artefact |
Exercises#
- Classify a change. Given a PR that edits
prompts/support/ticket-triage.v2.md, changesaliases.yaml, and bumpsanthropicinuv.lock, list the release-unit components and the minimum gates from Part 1.4. - Run the gate. With the Module 10A
evalkitpackage onPYTHONPATH, copyscripts/eval_gate.pyand thefixtures/tree shape from Part 3, then verify the fixture run exits2. Flip thebillingslice's failing score to1.0and confirm the decision becomesPASS(exit0); then shrink the run belowmin_casesand observe the blocking failure. - Fork safety. Explain why
pr-evalis skipped for fork PRs ineval.yml, and what would happen if you usedpull_request_targetwith secrets instead. - Prompt registry policy. Write the approval rule you would configure for a
productionalias move in Langfuse or LangSmith, including the eval artefact required. - Model lifecycle. Extend
check_model_deprecations.pyto call OpenAI'smodels.list()whenOPENAI_API_KEYis set, normalisingshutdown_dateinto the same report shape. - Index release. Draw the release record for a green index promotion, including manifest hash, embedder version, index alias and rollback alias.
- Dependency upgrade. Create a Dependabot
dependabot.ymlentry foruv/pip and list which CI jobs must run before merging anopenaiSDK bump. - Rollback drill. For the running
llm_servicefrom Modules 11A to 11C, write the exact pointer moves needed to roll back a bad prompt+model release without redeploying code.
Hints for the exercises
- Components touched: prompts (the
.mdfile), the alias pointer (aliases.yaml), dependencies (uv.lock), and, becauseanthropicis the SDK, the model client path. Minimum gates: render tests and prompt diff, cassette replay and contract tests (the SDK bump), eval smoke plus the PR-tier eval for the prompt semantics,uv lock --check, an audit scan, and a rollback pointer note in the PR. - Expect exit code
2on the fixture (thebillingslice fails its floor). After you flip the failing billing scores, the slice floor passes, but the report may still print advisory warnings: that isWARN, exit0. To trigger themin_casesfailure, delete rows until fewer thanmin_casescases remain. pr-evalskips forks because a fork's workflow code is untrusted and secrets must not reach it. Withpull_request_targetthe workflow runs in the base repository's context with secrets, so a PR that edits the eval code (or just a prompt your job executes) can exfiltrate keys. The safe pattern ispull_requestwith no secrets, or a maintainer-triggered run on a reviewed commit.- Example rule: moving
productionrequires a named owner, a linkedreport.mdfrom a passingprorfullrun of the same prompt hash, the safety suite result, and one approver who did not author the change. Registries differ in what they enforce natively, so back the rule with a CI check that refuses an alias write lacking the artefact. - Use the OpenAI SDK's
models.list()and map each model'sshutdown_date(if present) into the{"openai": {id: {"shutdown_date": ...}}}catalogue shape. Treat a missing key or a network failure asunchecked, never as a failure. - Fields:
release_id,git_sha,index.alias,index.manifest_hash,index.embedder,index.chunker_version, shadow-eval report link,rollback.index_aliasand who approved. - A
dependabot.ymlentry withpackage-ecosystem: "uv"(orpip) and a weekly schedule. Before merging anopenaibump: lockfile check, contract and cassette tests, mock-transport adapter tests, the eval smoke tier, and the audit scan. - Move the prompt alias back to the previous version, set the model flag or alias back to the previous snapshot, and repoint the index alias if it changed; the image digest stays the same. Record each pointer in the release evidence before the release, not during the incident.
Check yourself#
- Why is a prompt file part of the release unit even when no Python changes?Because prompt text changes model behaviour; it needs the same versioning, review, eval and rollback discipline as code.
- What are the three kinds of evidence a CI/CD pipeline for LLMs needs?Deterministic evidence, statistical eval evidence and production evidence.
- Which checks should run on every PR without provider keys?Lint/type/unit tests, prompt render tests, cassette replay, schema lint, lockfile check and dependency audit.
- Why is a cassette replay not a substitute for an eval gate?Cassettes prove request/response plumbing; they do not prove the new prompt or model produces good answers.
- What verdicts should an eval gate produce, and why is
WARNadvisory rather than blocking?FAIL(blocking),WARN(advisory) andPASS;WARNcovers the "too wide to tell" state so noisy comparisons are investigated loudly without blocking merges on noise. - Why should fork pull requests not receive provider secrets?Fork code is untrusted; secrets could be exfiltrated or used to attack provider accounts.
- What is the difference between a prompt version and a prompt alias?A version is immutable content; an alias is a mutable pointer used for environment promotion and rollback.
- When is a prompt registry worth the extra operational surface?When non-engineers edit daily, instant rollback is required, or per-environment/per-tenant variants are needed.
- Why must model snapshots be pinned in production?Floating aliases can change behaviour, cost, capability and lifecycle without a code change.
- What does
check_model_deprecations.pynormalise across providers?Missing/retired models, floating aliases, lifecycle status and expiry/deprecation dates. - Why must index alias and manifest version flip together?Because the index was built from that manifest; pairing mismatched versions corrupts retrieval provenance and rollback.
- Name three post-deploy checks before widening rollout traffic.Smoke requests, synthetic probes and metric comparison against the pre-deploy window.
- What should a release-evidence record contain so rollback is possible?Git SHA, image digest, prompt/model/index versions and hashes, eval reports, approvals and rollback targets.
- Which dependency updates should trigger provider contract tests?SDKs and HTTP/tooling libraries that can change request shape, retries, errors, streaming or parsing.
Further resources#
- GitHub Actions workflow syntax
- GitHub Actions secrets
- GitHub deployments and environments
- Securely using
pull_request_target - GitHub artifact attestations
- GitHub dependency caching
- GitLab CI/CD YAML syntax
- uv project locking and syncing
- uv project guide
- pip-audit
- OSV-Scanner supported lockfiles
- Dependabot version updates
- Renovate bot comparison
- OpenAI deprecations
- OpenAI models API
- Anthropic models overview
- Anthropic model deprecations
- Google Gemini models
- OpenRouter models API
- In-repo: 10A.8 regression testing and CI (the evalkit runner, statistics and gate this lesson's workflows call), 04.10 prompt templates and versioning, 03.10 debugging and testing, 05.9 ingestion pipelines, 02.9 model landscape
- Syft / anchore SBOM tooling
- Flagger progressive delivery
- Argo Rollouts
- Dev Container specification
- Sigstore
← 11C.1 — Deploying LLM Services | Module 11C overview | 11C.3 — Fallbacks, Gateways and Reliability →