Prompt Versioning, Regression Diffs & Release Gates
Versioned prompt metadata, baseline-vs-candidate evaluation regression diffs, and automated release gate checks verified with pytest and GitHub Actions.
In real AI engineering, prompts evolve constantly as teams refine edge cases, tighten instructions, or test new models. Without prompt versions, baseline-vs-candidate diffs, and release gates, subtle regressions slip into production unnoticed.
In this module, you will model versioned prompts and evaluation snapshots, validate snapshot and diff consistency, compute structured diffs between a baseline run and a candidate run on identical golden sets, enforce release gate thresholds in the practice assignment, and verify everything with pytest and GitHub Actions.
What You Will Build
- Versioned prompt and snapshot schemas: Represent prompt versions with version IDs, templates, and changelog notes, and validate evaluation snapshots and diffs for finite numbers, matching version IDs, consistent deltas and case ID lists, duplicate-free case IDs, and outcome consistency.
- Regression diff engine: Require matching, duplicate-free case IDs across baseline and candidate snapshots, then compute newly failed cases, newly passed cases, unchanged cases, pass-rate delta, cost delta, and P95 latency delta.
- Release gate assignment: Implement
evaluate_release_gatein the practice assignment to approve or block candidates with clear diagnostic reasons, explicit finite-threshold checks, and safe zero-baseline handling. - Tests and CI: Verify prompt versioning, diff logic, edge cases, and gate rules with
pytestand GitHub Actions on pushes and pull requests.
1. Prompt Versioning, Regression Diffs, and Release Gates
- Treating prompts as versioned artifacts: Prompts control model behavior just like code or configuration. Tagging each prompt revision with a semantic version or identifier (such as
triage-v1.0.0vs.triage-v1.1.0) makes evaluation comparisons auditable and reproducible. - Baseline vs. candidate regression diffs and consistency validation: Comparing two evaluation runs requires the same golden-set case IDs with no duplicate IDs inside a snapshot, matching version IDs on the diff and its embedded snapshots, a
pass_ratethat matches the recordedoutcomes(this exercise validates thatpass_ratematchesoutcomes, where an empty outcome list haspass_rate == 0.0), and deltas and case-flip lists that match the embedded snapshots. Tracking newly failed cases, newly passed cases, unchanged cases, cost delta, and P95 latency delta shows both aggregate shifts and per-case flips. - Automated release gates and zero-baseline ratios: A release gate combines quality, cost, and latency rules into an explicit go/no-go decision before promoting a candidate. When a baseline metric is
0.0and the candidate is positive, an infinite increase ratio (float("inf")) is an internal comparison result for gating, not a value that should be serialized into strict JSON as a standard JSON number. Returning explicit reasons makes blocked runs actionable.
2. Step-by-Step Build Walkthrough
- Set up the
fde-01-4repository and virtual environment: Create the package layout, configure.env.example,.gitignore, andpyproject.toml, and install editable dev dependencies.macOS / Linux:
mkdir -p fde-01-4/src/fde_01_4 fde-01-4/tests cd fde-01-4 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .envWindows (PowerShell):
mkdir fde-01-4 cd fde-01-4 py -m venv .venv .\.venv\Scripts\Activate.ps1 py -m pip install --upgrade pip py -m pip install -e ".[dev]" Copy-Item .env.example .envWindows (CMD):
mkdir fde-01-4 cd fde-01-4 py -m venv .venv .venv\Scripts\activate.bat python -m pip install --upgrade pip python -m pip install -e ".[dev]" copy .env.example .env - Define prompt version, validated snapshot, diff, and gate decision models: Use Pydantic v2 models with strict validation, finite float checks (
math.isfinite), duplicate case ID checks, pass-rate consistency checks againstoutcomes, and full consistency validation onRegressionDiff(version IDs, deltas, and newly failed, newly passed, and unchanged case IDs).import math from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator def _require_finite(value: float, field_name: str) -> float: if not math.isfinite(value): raise ValueError(f"{field_name} must be finite") return value class PromptVersion(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) version_id: str = Field(min_length=1) template: str = Field(min_length=1) changelog_note: str = Field(min_length=1) class CaseOutcome(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) case_id: str = Field(min_length=1) passed: bool class EvalSnapshot(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) prompt_version_id: str = Field(min_length=1) pass_rate: float = Field(ge=0.0, le=1.0) total_cost_usd: float = Field(ge=0.0) p95_latency_ms: float = Field(ge=0.0) outcomes: list[CaseOutcome] @field_validator("pass_rate", "total_cost_usd", "p95_latency_ms") @classmethod def _validate_finite_fields(cls, v: float, info) -> float: return _require_finite(v, info.field_name) @model_validator(mode="after") def _validate_consistency(self) -> "EvalSnapshot": seen_ids: set[str] = set() for item in self.outcomes: if item.case_id in seen_ids: raise ValueError(f"Duplicate case_id in snapshot: {item.case_id}") seen_ids.add(item.case_id) if not self.outcomes: expected_rate = 0.0 else: passed_count = sum(1 for item in self.outcomes if item.passed) expected_rate = passed_count / len(self.outcomes) if not math.isclose(self.pass_rate, expected_rate, rel_tol=1e-9, abs_tol=1e-9): raise ValueError( f"pass_rate ({self.pass_rate}) does not match outcomes ({expected_rate})" ) return self class RegressionDiff(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) baseline_version_id: str = Field(min_length=1) candidate_version_id: str = Field(min_length=1) baseline: EvalSnapshot candidate: EvalSnapshot pass_rate_delta: float cost_delta_usd: float p95_latency_delta_ms: float newly_failed_case_ids: list[str] newly_passed_case_ids: list[str] unchanged_case_ids: list[str] @field_validator("pass_rate_delta", "cost_delta_usd", "p95_latency_delta_ms") @classmethod def _validate_finite_deltas(cls, v: float, info) -> float: return _require_finite(v, info.field_name) @model_validator(mode="after") def _validate_diff_consistency(self) -> "RegressionDiff": if self.baseline_version_id != self.baseline.prompt_version_id: raise ValueError( "baseline_version_id must match baseline.prompt_version_id" ) if self.candidate_version_id != self.candidate.prompt_version_id: raise ValueError( "candidate_version_id must match candidate.prompt_version_id" ) base_map = {item.case_id: item.passed for item in self.baseline.outcomes} cand_map = {item.case_id: item.passed for item in self.candidate.outcomes} if set(base_map.keys()) != set(cand_map.keys()): raise ValueError( "baseline and candidate snapshots must have identical case IDs" ) ordered_ids = sorted(base_map.keys()) expected_failed = [ cid for cid in ordered_ids if base_map[cid] is True and cand_map[cid] is False ] expected_passed = [ cid for cid in ordered_ids if base_map[cid] is False and cand_map[cid] is True ] expected_unchanged = [ cid for cid in ordered_ids if base_map[cid] == cand_map[cid] ] if self.newly_failed_case_ids != expected_failed: raise ValueError("newly_failed_case_ids does not match snapshot outcomes") if self.newly_passed_case_ids != expected_passed: raise ValueError("newly_passed_case_ids does not match snapshot outcomes") if self.unchanged_case_ids != expected_unchanged: raise ValueError("unchanged_case_ids does not match snapshot outcomes") expected_pass_delta = self.candidate.pass_rate - self.baseline.pass_rate expected_cost_delta = self.candidate.total_cost_usd - self.baseline.total_cost_usd expected_lat_delta = self.candidate.p95_latency_ms - self.baseline.p95_latency_ms if not math.isclose( self.pass_rate_delta, expected_pass_delta, rel_tol=1e-9, abs_tol=1e-9 ): raise ValueError("pass_rate_delta does not match candidate minus baseline") if not math.isclose( self.cost_delta_usd, expected_cost_delta, rel_tol=1e-9, abs_tol=1e-9 ): raise ValueError("cost_delta_usd does not match candidate minus baseline") if not math.isclose( self.p95_latency_delta_ms, expected_lat_delta, rel_tol=1e-9, abs_tol=1e-9 ): raise ValueError("p95_latency_delta_ms does not match candidate minus baseline") return self class GateDecision(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) approved: bool reasons: list[str] - Compute regression diffs between baseline and candidate snapshots: Verify that both snapshots share the exact same set of
case_ids before computing deltas and deterministic newly failed, newly passed, and unchanged case IDs.def build_regression_diff( baseline: EvalSnapshot, candidate: EvalSnapshot, ) -> RegressionDiff: base_map = {item.case_id: item.passed for item in baseline.outcomes} cand_map = {item.case_id: item.passed for item in candidate.outcomes} if set(base_map.keys()) != set(cand_map.keys()): raise ValueError("Baseline and candidate snapshots must have identical case IDs") ordered_ids = sorted(base_map.keys()) newly_failed = [ cid for cid in ordered_ids if base_map[cid] is True and cand_map[cid] is False ] newly_passed = [ cid for cid in ordered_ids if base_map[cid] is False and cand_map[cid] is True ] unchanged = [ cid for cid in ordered_ids if base_map[cid] == cand_map[cid] ] return RegressionDiff( baseline_version_id=baseline.prompt_version_id, candidate_version_id=candidate.prompt_version_id, baseline=baseline, candidate=candidate, pass_rate_delta=candidate.pass_rate - baseline.pass_rate, cost_delta_usd=candidate.total_cost_usd - baseline.total_cost_usd, p95_latency_delta_ms=candidate.p95_latency_ms - baseline.p95_latency_ms, newly_failed_case_ids=newly_failed, newly_passed_case_ids=newly_passed, unchanged_case_ids=unchanged, ) - Run tests, configure GitHub Actions CI, and commit to Git: Run
pytestlocally, add.github/workflows/pytest.ymlso CI runs the test suite on pushes and pull requests (failing the CI check if any test or release-gate assertion fails), and commit your changes.python -m pytest -v git status git add . git commit -m "Complete FDE module 01.4"Example
.github/workflows/pytest.yml:name: pytest on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run tests run: python -m pytest -v
3. Common Pitfalls and Operational Hygiene
- Comparing mismatched or inconsistent snapshots and diffs: Always require matching golden-set IDs without duplicates, verify
pass_ratematchesoutcomes, and validate that diff version IDs, deltas, and case ID lists match the embedded snapshots. - Allowing non-finite floats or serializing infinite ratios into strict JSON: Reject
NaNandinfin snapshot, diff, and gate threshold validation, and treatfloat("inf")as an internal gate comparison rather than a standard JSON number. - Looking only at overall pass rate when cases flip: A candidate might pass two new cases while breaking a high-priority case; inspect
newly_failed_case_idsalongsidenewly_passed_case_idsandunchanged_case_ids.
4. Practice Assignment
In fde-01-4, implement evaluate_release_gate(diff: RegressionDiff, min_pass_rate: float, max_pass_rate_drop: float, max_cost_increase_ratio: float, max_p95_latency_increase_ratio: float) -> GateDecision in src/fde_01_4/gate.py that validates threshold inputs (raising ValueError if min_pass_rate is non-finite or outside [0.0, 1.0], or if any delta or ratio limit is non-finite or negative) and evaluates:
- Candidate pass rate meets
min_pass_rate. - Pass-rate regression does not exceed
max_pass_rate_drop(where a drop ismax(0.0, baseline.pass_rate - candidate.pass_rate)). - Relative cost increase does not exceed
max_cost_increase_ratio(whenbaseline.total_cost_usd > 0.0, ratio is(candidate.total_cost_usd - baseline.total_cost_usd) / baseline.total_cost_usd; ifbaseline.total_cost_usd == 0.0, positive candidate cost has internal ratiofloat("inf")and zero has0.0). - Relative P95 latency increase does not exceed
max_p95_latency_increase_ratio(using the same rule againstbaseline.p95_latency_ms). - Returns a
GateDecisionwithapproved: boolandreasons: list[str].
Add unit tests in tests/test_gate.py and tests/test_diffing.py covering newly failed, newly passed, and unchanged cases, diff version-ID, delta, and case-list mismatches, different golden-set IDs, duplicate case IDs, empty snapshots, pass-rate consistency, finite/non-finite thresholds, and exact threshold boundaries, then run python -m pytest -v and push fde-01-4 (including .github/workflows/pytest.yml) to GitHub.
5. Knowledge Check
- Why should prompt templates and system instructions carry explicit version identifiers and change notes alongside code commits?
- What is the difference between a per-case regression (a specific golden case flipping from pass to fail) and an aggregate pass-rate delta, and why must snapshot case IDs, pass rates, and diff fields be validated?
- Why can a candidate prompt that improves overall pass rate still be blocked by a release gate?
- How should you handle zero baseline cost or zero baseline latency when computing relative increase ratios, and why should
float("inf")stay an internal comparison value rather than a strict JSON number? - Why should release gates return explicit reasons rather than a single boolean flag alone, and what does GitHub Actions CI verify on pushes and pull requests?
Self-Review Answers
- 1. Prompt versioning: Explicit version IDs and notes let teams tie evaluation scores, token costs, and incidents back to exact prompt revisions instead of guessing what changed.
- 2. Case-level vs. aggregate deltas and consistency validation: Aggregate pass rate can stay flat or rise while critical edge cases flip from pass to fail; validating matching, duplicate-free case IDs,
pass_rateconsistency againstoutcomes, and version-ID, delta, and case-list alignment against the snapshots prevents misleading diffs. - 3. Multi-metric release gates: Production rollouts balance quality against cost and tail latency; a candidate that breaches cost or P95 latency ratios can be blocked for tuning even if accuracy rises.
- 4. Zero-baseline ratios and strict JSON: Guard zero baselines so zero-to-zero is
0.0and zero-to-positive isfloat("inf")for internal gate evaluation, avoidingZeroDivisionErrorand avoiding non-standardInfinityvalues in strict JSON payloads. - 5. Actionable gate reasons and CI: Clear reasons pinpoint which threshold failed, and GitHub Actions runs
pyteston pushes and pull requests so a failing test or failed release-gate check fails the CI run.
6. Completion Criteria
PromptVersion,EvalSnapshot,RegressionDiff, andGateDecisionmodels enforce strict validation, finite numbers, matching diff version IDs, consistent deltas and case lists, duplicate-free case IDs, and outcome/pass-rate consistency.build_regression_diffrejects mismatched case-ID sets and computes deltas plus newly failed, newly passed, and unchanged case IDs cleanly.evaluate_release_gateimplemented and tested across passing, blocked, exact-boundary, zero-baseline, and invalid/non-finite threshold cases.- All
pytesttests pass locally and in GitHub Actions on pushes and pull requests, and the repository is committed to GitHub.
Build this
In fde-01-4, implement evaluate_release_gate(diff: RegressionDiff, min_pass_rate: float, max_pass_rate_drop: float, max_cost_increase_ratio: float, max_p95_latency_increase_ratio: float) -> GateDecision in src/fde_01_4/gate.py that validates threshold inputs (raising ValueError if min_pass_rate is outside [0.0, 1.0] or any delta/ratio limit is negative) and evaluates:
- Candidate pass rate meets
min_pass_rate. - Pass-rate regression does not exceed
max_pass_rate_drop(where a drop ismax(0.0, baseline.pass_rate - candidate.pass_rate)). - Relative cost increase does not exceed
max_cost_increase_ratio(whenbaseline.total_cost_usd > 0.0, ratio is(candidate.total_cost_usd - baseline.total_cost_usd) / baseline.total_cost_usd; ifbaseline.total_cost_usd == 0.0, any positive candidate cost has ratiofloat("inf")and zero has0.0). - Relative P95 latency increase does not exceed
max_p95_latency_increase_ratio(using the same rule againstbaseline.p95_latency_ms). - Returns a
GateDecisionwithapproved: booland a clear list ofreasons: list[str]explaining any blocked checks.
Add unit tests in tests/test_gate.py covering approved releases, pass-rate drops, cost or latency ratio breaches, zero-baseline edge cases, and invalid thresholds, then run python -m pytest -v and push fde-01-4 (including .github/workflows/pytest.yml) to GitHub.
Test your understanding
- Why should prompt templates and system instructions carry explicit version identifiers and change notes alongside code commits?
- What is the difference between a per-case regression (a specific golden case flipping from pass to fail) and an aggregate pass-rate delta?
- Why can a candidate prompt that improves overall pass rate still be blocked by a release gate?
- How should you handle zero baseline cost or zero baseline latency when computing relative increase ratios?
- Why should release gates return explicit reasons rather than a single boolean flag alone?
Reveal self-review answers (attempt the questions first)
- Prompt versioning: Explicit version IDs and notes let teams tie evaluation scores, token costs, and incidents back to exact prompt revisions instead of guessing what changed.
- Case-level vs. aggregate deltas: Aggregate pass rate can stay flat or rise while critical edge cases flip from pass to fail; inspecting newly failed and newly passed case IDs catches targeted regressions.
- Multi-metric release gates: Production rollouts balance quality against cost and tail latency; a candidate that breaches cost or P95 latency ratios can be blocked for tuning even if accuracy rises.
- Zero-baseline ratios: Dividing by zero fails with
ZeroDivisionError; guard zero baselines explicitly so zero-to-zero is0.0and zero-to-positive is treated as an unbounded increase (inf). - Actionable gate reasons: Clear reasons tell engineers exactly which threshold failed (such as P95 latency or pass-rate floor) so they can fix the bottleneck quickly.
Questions or notes on this module?