Sub topic 8
Running the Suite in CI
This chapter assumes you can write pytest tests, call an LLM API, and read a GitHub Actions workflow. It also assumes you have a golden dataset and deterministic checks from earlier chapters. Here you will connect them to a pipeline that runs on every relevant change and blocks merges that make the feature worse.
What CI has to do differently for LLM tests
A normal unit test suite is cheap, fast, and deterministic. An LLM eval suite is none of these. Each case makes a network call that costs money, takes seconds, and can return a different answer on the next run. CI for evals therefore has to answer four questions that ordinary CI skips:
- When should the suite run, so you do not pay for runs that cannot change behavior?
- Where does the API key come from, and who can use it?
- What counts as a failure: one bad case, or a drop in the overall pass rate?
- How does a reviewer see what failed?
The rest of the chapter takes these in order.
Choosing triggers
Run the suite when something that affects model output changes. From earlier chapters, those surfaces are prompts, the model and its parameters, and the code that builds the context. A path filter on the pull request trigger expresses this directly.
name: prompt-regression
on:
pull_request:
paths:
- "prompts/**"
- "evals/**"
- "app/**"
jobs:
evals:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- run: pytest evals -q
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}The paths filter means a documentation-only pull request never triggers a paid run. Two cautions apply:
- Include every file that can alter a request. If the model name lives in
config/models.yaml, addconfig/**. A missed path is a silent hole in your coverage, which is the failure this whole tutorial is trying to prevent. - If you mark the workflow as a required status check, a path-filtered workflow that does not run leaves the check in a "pending" state, and the pull request cannot merge. Either avoid making it required, or add a lightweight always-running job that reports success when nothing relevant changed.
Handling the API key safely
The workflow reads the key from repository secrets and exposes it as an environment variable only to the step that needs it. Keep these rules:
- Scope the key to the eval step with
env:on that step, not to the whole job. - Use a dedicated key for CI with a spending limit set at the provider. A runaway loop or a malicious change should hit a cap, not your billing account.
- Never print the key or full request headers in test logs.
- Understand the fork limitation. Pull requests from forks do not receive repository secrets, so the suite cannot call the model. For public repositories, either run evals only on branches in the main repository, or have a maintainer trigger them after reviewing the fork's code.
The last point is also a security issue. A workflow that runs untrusted pull request code with secrets available lets the author of that code read the key. Do not switch to the pull_request_target trigger just to make secrets available to fork code unless you fully understand the risk. That trigger runs with secrets and write permissions, so it must never check out and execute untrusted code.
Turning per-case results into a gate
The pytest file from the previous chapter turns each line of the golden dataset into one test case:
import json
from pathlib import Path
import pytest
from app.llm import run_prompt # your own wrapper around the model call
CASES = [
json.loads(line)
for line in Path("evals/cases.jsonl").read_text(encoding="utf-8").splitlines()
if line.strip()
]
@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
def test_case(case):
output = run_prompt(case["input"])
data = json.loads(output)
assert set(case["required_keys"]) <= set(data)
for phrase in case.get("must_contain", []):
assert phrase.lower() in output.lower()This works for small suites with stable output. If you run it as is, any single failing case fails the build. With nondeterministic output, a case that passes 19 times out of 20 will eventually block an unrelated pull request. That is a flaky test, and flaky tests teach a team to ignore red builds.
The fix is a suite-level gate. Collect pass or fail for every case, compute the pass rate, and compare it to a stored baseline with a tolerance:
def pass_rate(results):
return sum(1 for passed in results if passed) / len(results)
def check_regression(current, baseline, tolerance=0.02):
if current < baseline - tolerance:
raise SystemExit(
f"Pass rate {current:.2%} is below baseline {baseline:.2%} "
f"minus tolerance {tolerance:.0%}"
)SystemExit with a string message prints the message to stderr and exits with status 1, which makes the CI step fail. With a baseline of 94% and a tolerance of 2 points, a run at 93% passes and a run at 91% fails.
To use this gate you need a runner that records outcomes instead of stopping at the first assertion failure. There are two common designs:
| Design | How it works | Trade-off |
|---|---|---|
| Pytest with a results file | Each test appends its outcome to a JSON file. A final step loads the file and calls `check_regression`. | Keeps per-case reporting and `-k` filtering. Needs a second step. |
| Standalone script | A script loops over cases, calls the model, and computes the rate itself. | Simple. Loses pytest features such as parametrized IDs and fixtures. |
Both designs keep the hard failures that should never be tolerated. Some cases are critical, such as a safety refusal or a required output schema. Mark them in the dataset, for example with "critical": true, and fail the build on any single critical failure regardless of the overall rate. Use the tolerance only for the ordinary cases.
The two-stage flow
A typical pipeline has a test stage that writes results and a gate stage that reads them. Writing results to a file also lets you upload them as an artifact for later inspection.
Making failures readable
A red check with a stack trace for one of 200 cases is hard to act on. Add three things to the workflow:
- Upload the results file as an artifact so a reviewer can download the full outputs.
- Write a short summary to the job summary page. GitHub Actions renders anything appended to the file named by
$GITHUB_STEP_SUMMARY. - Always run the upload and summary steps, even when the tests fail, using
if: always().
- run: pytest evals -q --results evals/results.json
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
- run: python evals/gate.py evals/results.json
- if: always()
uses: actions/upload-artifact@v4
with:
name: eval-results
path: evals/results.jsonThe --results option and evals/gate.py are your own code: a small pytest plugin or conftest.py hook that writes outcomes, and a script that loads them and calls pass_rate and check_regression. The gate step must come after the test step, and the test step should not abort the job before the gate runs. If you want the gate to be the only judge of pass or fail, run pytest with || true on that step, or give it continue-on-error: true, and let the gate step set the final status. Otherwise the job stops at the first failing step and the gate never runs.
Timeouts, retries, and rate limits
Network calls fail for reasons unrelated to your change. Treat these as infrastructure errors, not regressions.
- Set a timeout on every model call and a
timeout-minutesvalue on the job, so a hung request cannot hold a runner for six hours, which is the GitHub default. - Retry transient errors (HTTP 429 and 5xx) with exponential backoff inside
run_prompt. Do not retry on a wrong answer, because that hides regressions. - Distinguish error from failure in the results file. A case that raised a timeout should be recorded as
error, notfail. If the error rate is above a small limit, fail the job with a message about infrastructure so people do not hunt for a prompt bug that does not exist. - Limit concurrency to stay under the provider's rate limit. With
pytest-xdist,-n 4is a reasonable start. Raise it only if you see no 429 responses.
Concurrent runs and stale results
Two pushes to the same pull request in quick succession start two paid runs. Cancel the older one:
concurrency:
group: prompt-regression-${{ github.ref }}
cancel-in-progress: trueAdd this at the top level of the workflow. It saves money and prevents an old run from reporting a status on a newer commit.
Common mistakes
- Baseline stored only in a developer's head or a wiki. Keep it in the repository, for example
evals/baseline.json, so a change to it appears in the diff and gets reviewed. - Comparing against the main branch run live. It doubles the cost and makes the baseline itself noisy. A stored value is cheaper and stable.
- Running the full suite on every push. Fast pull request runs and a fuller scheduled run are covered in the next chapter on test tiers.
- Letting the gate read the secret from a log. Keep keys out of output, and remember that failure messages can echo model responses that include user data from your dataset.
- Skipping the check on documentation changes but forgetting config files. Review the
pathslist whenever the project layout changes.
Verify your pipeline
Before you rely on the gate, test it. Open a throwaway pull request that deliberately breaks the prompt, for example by removing the instruction to return JSON. Confirm the check fails, the summary names the failing cases, and the artifact downloads. Then revert and confirm the check passes. A gate that has never been seen failing gives you no information.
Exercise
Your eval workflow uses a paths filter and is a required status check. A pull request that only edits README.md cannot merge because the check stays pending. Give two ways to fix this.
Show answer
A path-filtered workflow that does not run never reports a status, so the required check waits forever. One fix is to remove the check from the required list. The other is to add an always-running job (or a second workflow without path filters) that reports success when no relevant files changed, and require that job instead.
Exercise
A suite of 200 cases has a baseline of 94% and a tolerance of 2 points. A run completes 170 calls successfully with 160 passes, and 30 calls time out. Why is reporting 94.1% (160/170) wrong, and what should the job do?
Show answer
The 30 timeouts were never evaluated, so excluding them hides a sixth of the suite. The job should record them as errors, not count them as passes, and fail with an infrastructure message because the error rate (15%) is above any small limit. After fixing timeouts or rate limits, rerun. If you did count the errors as failures, the rate would be 80%, which is also below the gate.