Sub topic 14
Checking notebooks automatically
A notebook that ran cleanly last month can fail today. A teammate may have committed a cell with stale output, or a dependency may have changed. This chapter shows how to run a few checks on every push, so a broken notebook is caught by a machine before a person has to find it.
This chapter assumes you have read the earlier chapters or know their content:
- You can run a notebook from the command line with
jupyter nbconvert --execute. - Your dependencies are pinned in
requirements.txt. - You know that seeds and data hashes belong in the notebook or its modules.
- You have used Git and have seen a basic CI configuration.
The examples use GitHub Actions. The same ideas apply to GitLab CI, Jenkins, or a scheduled job on your own server.
What a CI check should prove
Continuous integration (CI) means a service runs a defined set of commands on a clean machine whenever the repository changes. A clean machine matters because it has no leftover files, no globally installed packages, and no hidden kernel state. If the notebook runs there, it does not depend on anything on your laptop.
For notebooks, there are four useful levels of check. Start with the first and add the others as the project needs them.
| Check | What it catches | Cost |
|---|---|---|
| Execute top to bottom | Errors, missing files, undeclared dependencies, cell-order bugs | Notebook runtime |
| Outputs are stripped | Large or noisy diffs, leaked data in outputs | Seconds |
| Run twice and compare | Unseeded randomness, time-dependent results | Twice the runtime |
| Data and environment checks | Changed inputs, drifted packages | Seconds |
Check 1: execute the notebook
The most valuable check is the simplest. Run the whole notebook in a fresh kernel and fail if any cell raises an exception. This is the automated version of "Restart and run all".
jupyter nbconvert --to notebook --execute notebooks/analysis.ipynb \
--output-dir build --ExecutePreprocessor.timeout=600nbconvert exits with a non-zero status when a cell fails. CI treats any non-zero exit status as a failed job, so you need no extra logic. The --output-dir option writes the executed copy to build/ and leaves the committed notebook untouched. The timeout option sets how many seconds a single cell may run. The default is 30, which is too low for many analyses.
This check catches several common problems:
- A cell uses a variable that an earlier, deleted cell used to define.
- A file path points to your home directory.
- A package is imported but missing from
requirements.txt. - A data file was never committed or downloaded.
Check 2: outputs are stripped
Earlier chapters used nbstripout so outputs do not enter Git history. A local filter only works on machines where someone ran nbstripout --install. CI should check the rule, so a contributor who skipped the setup cannot bypass it.
The script below reads the notebook JSON and fails if any code cell has outputs or an execution count.
import json
import sys
from pathlib import Path
def dirty_cells(path):
nb = json.loads(Path(path).read_text(encoding="utf-8"))
bad = []
for index, cell in enumerate(nb.get("cells", [])):
if cell.get("cell_type") != "code":
continue
if cell.get("outputs") or cell.get("execution_count") is not None:
bad.append(index)
return bad
def main(paths):
failed = False
for path in paths:
bad = dirty_cells(path)
if bad:
failed = True
print(f"{path}: cells with outputs or counts: {bad}")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))Save it as tools/check_clean.py. Run it on the committed notebooks before you execute anything. Executing first would fill the outputs and make the check meaningless, unless you point it at the original files and write executed copies elsewhere, as the earlier command does.
Check 3: run twice and compare
A notebook can run without errors and still give different numbers each time. The usual causes are an unseeded random generator, a timestamp in a result, or an unordered set whose iteration order changes between processes. Running the notebook twice and comparing the text output finds these problems.
import sys
import nbformat
def text_outputs(path):
nb = nbformat.read(path, as_version=4)
results = []
for cell in nb.cells:
if cell.cell_type != "code":
continue
for out in cell.get("outputs", []):
if out.output_type == "stream":
results.append(out.text)
elif out.output_type == "execute_result":
results.append(out.data.get("text/plain", ""))
return results
def main(first, second):
a = text_outputs(first)
b = text_outputs(second)
if len(a) != len(b):
print(f"Different number of outputs: {len(a)} vs {len(b)}")
return 1
mismatches = [i for i, (x, y) in enumerate(zip(a, b)) if x != y]
for i in mismatches:
print(f"Output {i} differs:\n--- run 1\n{a[i]}\n--- run 2\n{b[i]}")
return 1 if mismatches else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2]))Save it as tools/compare_runs.py. It compares only printed text and cell results. It skips display_data, which holds figures, because a figure's text form often includes a memory address such as <Figure size 640x480 at 0x7f3a...>. That address changes on every run even when the plot is identical.
Putting it together in a workflow
The workflow below runs all three checks on every push and pull request. Save it as .github/workflows/notebooks.yml.
name: notebooks
on:
push:
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- name: Install pinned dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install nbconvert nbformat ipykernel
- name: Check outputs are stripped
run: python tools/check_clean.py notebooks/analysis.ipynb
- name: Execute notebook, run 1
run: |
jupyter nbconvert --to notebook --execute notebooks/analysis.ipynb \
--output-dir build/run1 --ExecutePreprocessor.timeout=600
- name: Execute notebook, run 2
run: |
jupyter nbconvert --to notebook --execute notebooks/analysis.ipynb \
--output-dir build/run2 --ExecutePreprocessor.timeout=600
- name: Compare runs
run: python tools/compare_runs.py build/run1/analysis.ipynb build/run2/analysis.ipynb
- name: Keep executed notebooks
if: always()
uses: actions/upload-artifact@v4
with:
name: executed-notebooks
path: build/Some details in this file are easy to get wrong:
if: always()on the upload step keeps the executed notebooks even when an earlier step failed. A failed run's notebook shows which cell broke and what it printed, so it is the one you most want to read.- The extra
pip installline adds the tools that run the checks. Put them in a separaterequirements-dev.txtif you prefer to keep them out of the analysis environment. - Pinning the Python version in
setup-pythonmatters as much as pinning packages. A different minor version can change results. - The
cache: pipoption speeds up installs. It does not change what is installed, because the versions come fromrequirements.txt.
Checking the data and the environment
The data hash check from the provenance chapter runs inside the notebook, so the first execution already covers it. If the input file changes, the assert fails and so does the job. If the data is too large for the repository, add a step before execution that downloads it and verifies the hash. A job that cannot fetch the data should fail loudly.
The environment can also drift without anyone editing it. If requirements.txt pins only top-level packages, a transitive dependency (a package that one of yours depends on) can update and change behavior. A scheduled run catches this. Add a trigger to the on: section:
on:
push:
pull_request:
schedule:
- cron: "0 6 * * 1"This runs the checks every Monday at 06:00 UTC even if nobody pushed. A failure then points to something outside your repository, such as a changed service, an expired download link, or an unpinned package.
Failure modes and trade-offs
- Long runtimes. Running a notebook twice doubles the cost. For a slow analysis, run the full check on a schedule or before release. On each pull request, run a reduced version using a small data sample selected by a parameter.
- Secrets and credentials. Notebooks that read from a database or API need credentials. Provide them through the CI service's secret store as environment variables. Never write them into a cell. A secret printed in an output ends up in the uploaded artifact.
- Flaky checks. A check that fails randomly gets ignored. If the comparison fails intermittently, find the cause (threads, time, network). Do not add retries.
- Passing is not correctness. These checks show the notebook runs and repeats. They do not show the analysis is right. Pair them with ordinary tests for the functions you moved into modules.
- Environment mismatch. CI runs Linux. If your team works on macOS or Windows, results that depend on the platform may differ. Recording platform details with the results, as in the run metadata chapter, lets you see why.
Exercise
Your CI job passes, but a colleague points out that the executed notebook prints a different mean value each time they run it locally. Which of the three checks in this chapter should have caught this, why did it not, and what is one likely cause?
Show answer
The run-twice-and-compare check should have caught it. It did not because the job in this chapter only runs it if that step is present, or because the output that varies is a figure or other displaydata output, which the comparison script skips. A common cause is a random generator that is not seeded, for example calling np.random.defaultrng() with no seed. Seed it with a fixed value, make sure the varying value is printed as text or returned as a cell result, and rerun the comparison.