Reproducible notebooks
可复现 Notebook
Separate saved output from a fresh execution, with a real Jupyter baseline.
notebook-practiceThe output is still there. Can the notebook produce it again?
A notebook displays 8.0 and a passing assertion. You delete the line that defined scale, save the notebook, and send it to a colleague. The saved output can still say 8.0. Your colleague starts a fresh kernel, runs from the top and gets a NameError. The visible result belonged to an earlier execution state.
A notebook is useful because explanation, code and observations live together. That convenience also makes it easy to mistake an old observation for a result of the current source. Reproducibility needs a fresh execution path, declared inputs and an environment that someone else can reconstruct.
We will build a real .ipynb document, execute it with a real Python Jupyter kernel, and deliberately create the stale-output failure. The data are three literal numbers. A plain Python script is the non-notebook baseline: if the work does not benefit from interleaved explanation and exploration, a script may be easier to maintain.
A kernel has history; a document stores selected evidence
Treat each cell as a transformation of the kernel state. For deterministic code with fixed data D and environment E, top-to-bottom execution has the form:
The initial state matters. Running cell two after an old cell one is a different computation from running cell two in a new kernel. Mutable files, random generators and external services add state beyond the variables shown in the document. A restart removes kernel variables, but does not revert files or freeze remote data.
A notebook file records cell source and may record outputs and execution counts. Those fields do not establish that the saved source produced the saved outputs. The nbformat v5.10.4 format description distinguishes code, outputs and execution counts. Ascending counts are useful clues, but they are neither a complete execution log nor a provenance certificate.
Our baseline is deliberately small:
Cell setup defines the values and scale, compute prints the result, and check asserts the expected answer. The literal expected answer makes the baseline independently understandable. A notebook that executes without exceptions can still compute the wrong quantity; assertions and domain-specific evaluation remain necessary.
Define what a clean run includes
Record the notebook source revision, input identity, interpreter and package versions, kernel choice, working directory and meaningful output checks. For this example, the data are inline and exact integer arithmetic precedes a division whose result is exactly representable. There are no downloads, random choices or model APIs inside the notebook.
nbclient v0.10.2 provides programmatic execution with a chosen kernel, working directory and per-cell timeout. Its default error behavior stops on an error. Silently allowing every error would defeat our baseline check. A timeout is a bound for this execution policy; it is not a sandbox or a guarantee that arbitrary code has no side effects.
Generate, execute and then break a tiny notebook
Save this complete standard-library program as notebook_example.py and run it with Python 3.12. Without arguments it writes and rereads an unexecuted notebook inside a temporary directory, then removes that directory. It does not pretend to execute a Jupyter kernel. With a new output path it keeps the generated document, refusing to overwrite an existing file.
import json
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
def make_notebook():
sources=[('setup','values = [1, 3, 8]\nscale = 2'),
('compute','result = scale * sum(values) / len(values)\nprint(result)'),
('check','assert result == 8.0')]
return {'nbformat':4,'nbformat_minor':5,
'metadata':{'kernelspec':{'name':'python3','display_name':'Python 3',
'language':'python'}},
'cells':[{'id':cell_id,'cell_type':'code','metadata':{},
'source':text,'execution_count':None,'outputs':[]}
for cell_id,text in sources]}
def save_new(path):
with Path(path).open('x',encoding='utf-8') as handle:
json.dump(make_notebook(),handle,ensure_ascii=False,indent=2)
handle.write('\n')
if __name__ == '__main__':
if len(sys.argv) == 2:
save_new(sys.argv[1])
print('wrote unexecuted notebook:',sys.argv[1])
elif len(sys.argv) == 1:
with TemporaryDirectory() as directory:
path=Path(directory)/'demo.ipynb'
save_new(path)
notebook=json.loads(path.read_text())
print('cell IDs:',[cell['id'] for cell in notebook['cells']])
print('execution counts:',[cell['execution_count'] for cell in notebook['cells']])
print('stored output count:',sum(len(cell['outputs']) for cell in notebook['cells']))
else:
raise SystemExit('usage: notebook_example.py [new-output.ipynb]')
Output without arguments:
cell IDs: ['setup', 'compute', 'check']
execution counts: [None, None, None]
stored output count: 0
For an actual kernel run, download the accompanying execution script and version requirements. In a dedicated Python 3.12 environment, install those requirements, generate the document, then execute it. The following are terminal commands, assuming the downloaded files and example program are in the working directory:
python -m pip install -r requirements.txt
python notebook_example.py demo.ipynb
python run-notebook.py demo.ipynb
The execution script validates the notebook schema, starts a Python kernel, runs in the notebook’s directory with a 30-second per-cell limit, and writes demo.executed.ipynb only after successful execution. It refuses to replace an existing result. It uses nbclient 0.10.2, nbformat 5.10.4 and ipykernel 6.29.5. The recorded local test used CPython 3.12.4; the accompanying environment snapshot records the resolved packages on macOS rather than claiming a portable, hash-locked environment.
In the verified run, the three execution counts were 1,2,3, the printed result was 8.0, and the assertion passed. After deleting scale = 2 from an already-executed copy, that copy still contained the saved output 8.0. Executing it in a fresh kernel raised NameError. Recreating the original notebook and running in another fresh kernel produced 8.0 again. This checks actual kernel behavior, not a simulated dictionary interpreter.
Kernel startup dominates such a tiny workload; no speed comparison is claimed. The notebook’s sum takes O(n) work for n input values. Large embedded images or outputs can also make notebook storage and review expensive, independently of model computation.
Restart-and-run-all is necessary evidence, not the whole experiment
A clean run does not pin a database snapshot, a model download or a system library. Record those inputs separately. A package list does not pin wheels, the operating system or every hardware behavior. A random seed does not make every parallel or GPU operation deterministic. See environments and random seeds for those boundaries.
Clearing saved outputs can reduce noisy diffs and accidental disclosure, but it does not remove credentials embedded in source, metadata, attachments or files. This example has no credentials and no external data; do not treat an output-clearing step as a universal sanitizer. Only execute notebooks whose code and provenance you have assessed, because a kernel runs ordinary code with its process permissions.
For a larger analysis, keep reusable transformations and tests in modules. Let the notebook explain the question, invoke those transformations and display selected evidence. Evaluation metrics should match the real task; our exact answer of 8 is a baseline check, not a score for model quality or scientific validity.
Ask what the saved result actually proves
- A notebook’s saved output says 8.0 after the scale assignment was deleted. What can you conclude?
Answer 1: Only that the file contains that saved output. It does not prove that the current source can produce it. A fresh run in this example raises NameError.
- Why is a passing top-to-bottom run stronger evidence than execution counts 1,2,3 in a saved file?
Answer 2: The run actively checks execution of the current source under a stated initial state. Stored counts can survive edits and do not establish which source or inputs were used.
- If the values move into a CSV file, what additional evidence should accompany a result?
Answer 3: The exact input file or a retrievable version with a content hash, its schema and interpretation, and the path/working-directory convention. A file name alone can refer to changing bytes.
- Change scale from 2 to 3. How should the baseline check change, and what should remain unchanged?
Answer 4: The expected result becomes 12. The same three-cell dependency order, fresh-kernel execution and input values remain. Record the changed parameter and expected result together; stale output 8 must not be presented as the new result.
Make the readable analysis rerunnable
The pinned Jupyter documentation supplies the file and execution interfaces; this chapter’s document, baseline and deliberate failure are original. The downloadable runner keeps execution policy outside the scientific calculation, so it can be reused in automation.
Continue with Git reproducibility to tie the notebook to a source revision, and model evaluation to choose checks beyond “it ran.” A useful project is a short notebook that reads a tiny versioned table, compares a non-AI baseline with a model, and fails when either the input schema or a declared evaluation bound changes.
Make a prediction, then check
After deleting a variable assignment, does a saved output prove the edited notebook still runs?
Learning objectives
- Explain why saved outputs do not validate current source.
- Execute a declared baseline in a fresh kernel and detect hidden state.
Prerequisites & connections
Explore related knowledge →References
- The Notebook file format — nbformat v5.10.4
Project Jupyter - Executing notebooks — nbclient v0.10.2
Project Jupyter
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.
- Four portable tests and real CPython 3.12.4 Jupyter executions passed: output 8, stale output retained after deleting scale, fresh-kernel NameError, repair to 8 and overwrite refusal. Two paired formulas and four answers render.
- Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- The Notebook file format — nbformat v5.10.4 · Pinned v5.10.4 docs lines 93–116: code source, output list, integer/null execution count; read raw GitHub source.
- Executing notebooks — nbclient v0.10.2 · Pinned v0.10.2 docs lines 31–55 and 176–177: schema read, explicit kernel/cwd/timeout, execute and allow_errors default; read raw GitHub source.
Related topics