Git and reproducibility: retain the version that actually ran
Git 与实验复现
Run a disposable Git experiment to distinguish committed snapshots, staged edits, ignored data and retained evidence.
git-reproducibility“Same commit” did not produce the same result
A teammate reports a result and supplies a Git commit. You check out that commit, run the command and obtain a different number. Neither person needs to have made a mathematical mistake. One may have run an unstaged configuration; the other may have used a different data file that Git ignored.
Git preserves selected project snapshots. An experiment also depends on the actual input bytes, configuration, runtime and execution choices. This chapter makes that distinction visible in a disposable repository: three versions of a configuration coexist, and a later data change alters the result while git status remains clean.
The calculation is deliberately small: multiply the sum of two observations by a configured factor. There is no trained model or random optimizer to obscure which dependency changed.
A commit is one part of an experiment record
The working tree, index and commit are separate
The working tree contains the files a normal program reads. The index, also called the staging area, holds the version prepared for the next commit. HEAD names the current commit in this example. Editing a file after git add does not update its staged version; a plain git commit records the index. These snapshot concepts are described in Pro Git, second edition.
Our configured factor moves through these states:
| Moment | HEAD | Index | Working tree | Result on [2,3] |
|---|---|---|---|---|
| Initial commit | 1 | 1 | 1 | 5 |
| Stage 2, then edit to 3 | 1 | 2 | 3 | 15 |
| Commit the index | 2 | 2 | 3 | 15 |
| Restore the working file from the index | 2 | 2 | 2 | 10 |
git diff compares the working tree with the index. git diff --cached compares the index with HEAD by default. Both differences matter when reconstructing an uncommitted run. A commit recorded next to a metric does not silently include either difference. Git diff reference
Clean status has a defined scope
For ordinary tracked paths, status distinguishes changes in the index and working tree. The program requests stable porcelain version 1 with NUL-separated paths and all untracked files. MM config.json means the index differs from HEAD and the working file differs from the index. ?? note.txt is untracked. This tiny example has no conflicts, renames or submodules. Git status reference
An ignored, untracked file normally does not appear. .gitignore does not archive that file, and it does not stop tracking a file already in Git. Here observations.json is intentionally excluded to represent separately managed data. A clean status therefore says nothing about whether its bytes changed. Git ignore reference
Record the dependency boundary
For our deterministic calculation, the result is a function of the executed source, configuration and observations:
The experiment report records the commit, status, SHA-256 of those three files, the result, and actual Python and Git versions. File hashes identify the bytes observed by this recorder; they do not store the bytes or prove their origin. An artifact must still be retained somewhere accessible. The Git commit ID and the separate SHA-256 file fingerprints are different identifiers.
The example demonstrates a failed implication:
In a training pipeline, enlarge the record to cover preprocessing, split IDs, hyperparameters, seeds and relevant environment details. A seed constrains a random stream under specified conditions; it does not pin a dataset, a library implementation or nondeterministic hardware execution.
Run the failure and its reconstruction
The complete program requires Python 3.12 and a Git executable. It creates one temporary repository, uses no remotes, runs only its own short Python calculation, and deletes that repository afterward. Git settings and illustrative author identity are passed to the subprocess, with global/system configuration and inherited Git overrides excluded. An empty template and hook directory keep the demo independent of user hooks. No existing repository or global configuration is modified.
The fixed author date makes the demonstration commits less variable; it is not a claimed date of a real experiment. The repository explicitly uses SHA-1 Git objects. The program’s SHA-256 file fingerprints are unaffected by that choice.
from pathlib import Path
from tempfile import TemporaryDirectory
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
RUNNER = '''from pathlib import Path
import json
config = json.loads(Path('config.json').read_text())
data = json.loads(Path('observations.json').read_text())
print(config['factor'] * sum(data))
'''
def encode(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
def digest(data):
return hashlib.sha256(data).hexdigest()
def experiment():
executable = shutil.which('git')
if executable is None:
raise RuntimeError('Git must be installed and available on PATH')
env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT='0', LC_ALL='C',
GIT_AUTHOR_DATE='2026-01-01T00:00:00+00:00',
GIT_COMMITTER_DATE='2026-01-01T00:00:00+00:00')
with TemporaryDirectory(prefix='aiwiki-git-example-') as name:
root = Path(name)
repo = root / 'repo'
template = root / 'empty-template'
template.mkdir()
options = [executable, '-c', 'user.name=AI Wiki Example',
'-c', 'user.email=example@example.invalid',
'-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false',
'-c', 'core.excludesFile=' + os.devnull,
'-c', 'core.hooksPath=' + str(template)]
def git(*args):
return subprocess.run(options + ['-C', str(repo), *args],
env=env, check=True, capture_output=True).stdout
subprocess.run(options + ['init', '--quiet', '--initial-branch=main',
'--object-format=sha1', '--template=' + str(template),
str(repo)], env=env, check=True, capture_output=True)
(repo / 'run.py').write_text(RUNNER)
(repo / '.gitignore').write_text('/observations.json\n')
(repo / 'config.json').write_bytes(encode({'factor': 1}))
data = encode([2, 3])
(repo / 'observations.json').write_bytes(data)
git('add', '--', 'run.py', '.gitignore', 'config.json')
git('commit', '--quiet', '-m', 'Record calculation and configuration')
def record():
names = ('run.py', 'config.json', 'observations.json')
before = {n: (repo / n).read_bytes() for n in names}
result = subprocess.run([sys.executable, '-I', '-B', 'run.py'],
cwd=repo, env=env, check=True, capture_output=True).stdout
after = {n: (repo / n).read_bytes() for n in names}
if before != after:
raise RuntimeError('inputs changed while the example ran')
return {'commit': git('rev-parse', 'HEAD').decode().strip(),
'status': git('status', '--porcelain=v1', '-z',
'--untracked-files=all').decode(),
'sha256': {n: digest(b) for n, b in before.items()},
'result': int(result), 'python': platform.python_version(),
'git': git('--version').decode().strip()}
baseline = record()
(repo / 'config.json').write_bytes(encode({'factor': 2}))
git('add', '--', 'config.json')
(repo / 'config.json').write_bytes(encode({'factor': 3}))
layers = {'head': json.loads(git('show', 'HEAD:config.json'))['factor'],
'index': json.loads(git('show', ':config.json'))['factor'],
'worktree': json.loads((repo / 'config.json').read_bytes())['factor'],
'staged_diff': git('diff', '--cached', '--', 'config.json').decode(),
'unstaged_diff': git('diff', '--', 'config.json').decode()}
staged = record()
git('commit', '--quiet', '-m', 'Commit the staged factor two')
committed = record()
committed_factor = json.loads(git('show', 'HEAD:config.json'))['factor']
# Only this disposable repository is restored.
git('restore', '--worktree', '--', 'config.json')
restored = record()
(repo / 'observations.json').write_bytes(encode([2, 4]))
changed_data = record()
ignored = git('check-ignore', '--', 'observations.json').decode().strip()
(repo / 'observations.json').write_bytes(data)
replayed = record()
(repo / 'note.txt').write_text('An untracked note.\n')
with_untracked = record()
return {'layers': layers, 'committed_factor': committed_factor,
'ignored': ignored, 'baseline': baseline, 'staged': staged,
'committed': committed, 'restored': restored,
'changed_data': changed_data, 'replayed': replayed,
'with_untracked': with_untracked}
def main():
r = experiment()
print('HEAD / index / worktree:', r['layers']['head'],
r['layers']['index'], r['layers']['worktree'])
print('staged status / run:', repr(r['staged']['status']), r['staged']['result'])
print('committed factor / worktree run:', r['committed_factor'], r['committed']['result'])
a, b = r['restored'], r['changed_data']
print('same commit / both clean:', a['commit'] == b['commit'],
a['status'] == b['status'] == '')
print('ignored-data results / hash changed:', a['result'], b['result'],
a['sha256']['observations.json'] != b['sha256']['observations.json'])
print('restored bytes / result:', r['replayed']['sha256'] == a['sha256'],
r['replayed']['result'])
print('untracked status:', repr(r['with_untracked']['status']))
if __name__ == '__main__':
main()
Output:
HEAD / index / worktree: 1 2 3
staged status / run: 'MM config.json\x00' 15
committed factor / worktree run: 2 15
same commit / both clean: True True
ignored-data results / hash changed: 10 12 True
restored bytes / result: True 10
untracked status: '?? note.txt\x00'
After staging factor 2 and editing to 3, the actual calculation still reads 3 and produces 15. Committing does not replace that working file. The later restore is deliberately limited to this temporary repository; it copies factor 2 from the index into the working tree, producing 10.
Changing ignored observations from [2,3] to [2,4] produces 12 with the same commit and a clean status. The data fingerprint changes. Restoring the saved input bytes recovers 10. Finally, a new untracked note is reported by status even though the calculation does not read it. Being dirty is a reason to inspect dependencies, not proof that every reported change affected a result.
record compares the three files before and after execution. That catches an ordinary persistent edit during the run, but it is not an atomic filesystem snapshot: a concurrent process could change and restore a file between reads. This demo has no concurrent writer. A production recorder needs an immutable input location or a stronger snapshot mechanism.
If the three recorded files contain B bytes, hashing and retaining their pre/post snapshots takes O(B) work and memory. The deliberately simple calculation is linear in the number of observations it reads. Git status, object lookup and commit costs also depend on repository size and storage; the example makes no constant-time or throughput claim. Returned reports are evidence for a few fixed inputs, not a complete experiment-tracking service.
Reconstruction requires more than a fingerprint
The report is scoped to three files and two version strings. It does not freeze the Python executable, operating system, transitive dependencies or external services. This integer-only example reproduces locally, but a GPU training job may require tolerance-based checks rather than bitwise-identical outputs. Choose the acceptance test before comparing reruns: same input identities, same metric within a stated tolerance, or the same scientific conclusion are different requirements.
Git does not provide a data-retention policy. Large or restricted artifacts can remain in separate storage with immutable identifiers and a recorded retrieval procedure. A hash is useful for checking a retrieved artifact; a missing artifact cannot be reconstructed from its hash. Ignoring a file also does not remove earlier committed versions from history.
Prefer a recorded, retained commit for a shared experiment. Branch names can move. If an exploratory run uses uncommitted changes, save the actual source snapshot or appropriate staged and unstaged patches as well as the dependency record. The narrow recorder here does not capture arbitrary untracked code, renamed paths, submodule state or file permissions.
The temporary example contains no credentials or private data. It illustrates what to retain for reproducibility, not a reason to put every dataset or configuration value into a repository.
Identify the missing evidence
- Read the three versions. Factor 2 is staged, then the working file is edited to 3. What does a plain commit store, and what does the program run?
Follow the two reads
Answer: The commit stores the staged factor 2. The program reads the working-tree factor 3, so [2,3] produces 15. To see both differences beforehand, inspect git diff --cached and git diff.
- Audit a clean run. Why can two runs on the same clean commit produce 10 and 12 in the example?
Look outside tracked files
Answer: The ignored observations changed from [2,3] to [2,4], while tracked factor 2 remained unchanged. The independent input hashes distinguish the runs; ordinary clean status does not.
- Recover the input. A report contains a data SHA-256 but the artifact has been deleted. Is that sufficient for a rerun?
Identification is not storage
Answer: No. The hash can check candidate bytes but does not supply them. Retain the artifact or a reproducible acquisition procedure with an immutable source version, and verify the recovered bytes against the recorded fingerprint.
- Interpret a changed status. The final report contains
?? note.txt, but the result is still 10. Does an untracked file necessarily invalidate the calculation?
Check the dependency graph
Answer: No. This calculation never reads the note. The status reveals a file outside the commit, which should be assessed rather than silently ignored. An untracked module that the program imports would be a relevant missing dependency and would need to be captured.
Connect version control to experimental evidence
Pro Git gives the snapshot and staging model. The references for diff, status and ignore rules make its observable boundaries precise. Their value for AI experiments is to establish which source version was retained and which differences remain outside it.
Continue with environments and dependencies for runtime isolation and randomness and seeds for stochastic execution. SQL for AI data work shows why preserving a query still leaves its source data and information-time boundary to be recorded.
Make a prediction, then check
A clean commit stays the same, but an ignored data file changes. Must the result stay the same?
Learning objectives
- Distinguish the executed working file, staged version and committed snapshot.
- Explain why clean status and a commit ID do not identify ignored input data.
- Retain dependency fingerprints alongside recoverable artifacts and explicit runtime scope.
Prerequisites & connections
Explore related knowledge →References
- Pro Git, second edition — What is Git?
Scott Chacon; Ben Straub - git-diff — Git 2.52.0 documentation
Git contributors - git-status — Git documentation
Git contributors - gitignore — Git 2.52.0 documentation
Git contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass under Python 3.12.4 with actual Git 2.52.0. All Git mutations and calculation subprocesses run exclusively in TemporaryDirectory repositories with no remotes. Tests inject bogus inherited GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE and inspect subprocess arguments to verify their removal, isolated configuration and temporary-only target paths. Both tested temporary repositories are cleaned up.
- An independent reader decompresses loose Git objects, checks object header lengths and SHA-1 identities, parses binary tree entries and follows commit-parent links without git show or ls-tree. It verifies exactly two committed snapshots with factors 2 and 1 and only the three declared tracked files; observations are absent. Literal-byte SHA-256 checks verify factor-two configuration and both data revisions without reusing the canonical JSON encoder.
- Tests check staged/unstaged diff endpoints, all seven actual results, status transitions, unchanged HEAD versus changed working state, equal clean commits with differing ignored inputs, exact replay report equality, irrelevant untracked-note status and explicit missing-Git failure. The program is a fixed deterministic provenance experiment rather than a general repository recorder; its before/after input comparison is explicitly not an atomic snapshot.
- Complete original bilingual prose contains identical executable Python, seven stdout lines, two matching formulas, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass. Fixed illustrative commit dates are not represented as real historical events. Dependency retention, hash/authenticity scope, version/seed limitations and byte-cost bounds were reread under the Humanizer prose guidance. Status remains written with AI author checks, not human or whole-site approval.
- 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:
- Pro Git, second edition — What is Git? · Actually read official Pro Git second-edition chapter lines 190–206 for snapshots/local history and 220–245 for modified/staged/committed states, working tree, index and plain commit workflow. The old chapter SHA-1 wording is not generalized to all modern repositories; the demo explicitly requests SHA-1 objects and separately uses SHA-256 artifact fingerprints. No book diagrams, examples or code are copied.
- git-diff — Git 2.52.0 documentation · Actually read fixed Git 2.52.0 git-diff reference lines 285–310 and 1156–1170 for working tree versus index, --cached versus HEAD, and named commit comparisons. The two captured diffs are actually executed and checked at their independent endpoints. No unstaged-patch capture service is claimed.
- git-status — Git documentation · Actually read official git-status live page lines 259–278 for porcelain/untracked options, 438–461 for two-column states, and 485–493 for stable v1 and NUL path format. The attempted /2.52.0 and trailing-slash URLs returned only a three-line redirect document, so the source card is explicitly unversioned rather than pretending that version was read. Actual runtime is Git 2.52.0; the tiny example contains no conflicts, renames or submodules.
- gitignore — Git 2.52.0 documentation · Actually read fixed Git 2.52.0 gitignore reference lines 223–239 for deliberately untracked files, tracked-file exclusion from these rules, and ignore-file precedence. Demo uses an explicit .gitignore with global excludes disabled, actual check-ignore, and a separately fingerprinted input. No claim that ignore rules remove history or retain data.
- Pro Git, second edition — What is Git? · Actually read the official second-edition chapter on snapshots and local history, and The Three States (lines 220–245). Plain commit records the index. SHA-1 discussion is scoped to the explicitly selected demo object format.
- git-diff — Git 2.52.0 documentation · Actually read the fixed 2.52.0 reference, DESCRIPTION lines 285–310: default index/worktree, --cached HEAD/index and explicit commit comparisons.
- git-status — Git documentation · Actually read the live official reference, short format lines 390–461 and porcelain v1 lines 485–493: index/worktree columns, ignored/untracked scope and NUL termination. Runtime tested Git 2.52.0; source card correctly remains unversioned.
- gitignore — Git 2.52.0 documentation · Actually read fixed 2.52.0 DESCRIPTION lines 223–239: intentionally untracked files, already-tracked exception and precedence. Ignoring does not erase tracked history or retain input data.
Related topics