Sub topic 7
Verifying Packages with Hashes
Prerequisites
Assume you know basic Python, pip, virtual environments, and lock files. This chapter focuses on verifying package files after dependency resolution.
A package version identifies a release, such as numpy==1.26.4. A hash identifies the exact file downloaded for that release. Hash pinning records both. This prevents an installer from accepting a different artifact that has the same name and version.
Why Version Pins Are Not Enough
A version pin controls which release pip requests, but a release can have several distribution files. For example, a package may publish different wheels for Linux, macOS, Windows, and different CPU architectures. A source archive may also exist.
| Specification | Controls | Does not fully control |
|---|---|---|
| `numpy` | Nothing exact | Version and artifact |
| `numpy==1.26.4` | Release version | Downloaded file |
| Version plus hash | Release and accepted file | Python, OS, and hardware |
A hash is calculated from the package file's bytes. If the file changes, its hash changes. With hash checking enabled, pip refuses a file whose hash is not listed in the lock file.
Generate and Use Hashes
Keep direct requirements in a small input file:
# requirements.in
numpy
scikit-learn
torchUse pip-tools to resolve direct and transitive dependencies. The --generate-hashes option adds hashes for every accepted artifact:
python -m pip install pip-tools
pip-compile --generate-hashes -o requirements.lock requirements.in
python -m pip install --require-hashes -r requirements.lockThe generated file contains resolved versions, dependencies, and one or more hashes. Multiple hashes are normal because different platforms may need different wheels. pip accepts an artifact only when its hash matches one of the entries.
--require-hashes also requires every installed dependency to be pinned. A requirement without a version or hash causes installation to fail. This includes transitive dependencies, which is why hand-writing only the direct requirements is unsafe.
What Hash Checking Does Not Cover
Hash-pinned Python packages do not pin the complete runtime environment. Results can still differ because of:
- The Python interpreter version.
- Operating-system libraries and compiler behavior.
- CUDA drivers and CUDA user-space libraries.
- Input data, model checkpoints, and configuration.
- Random seeds and nondeterministic operations.
Treat the lock file as one layer of reproducibility. Containers can pin more of the operating-system layer, while data and model versioning covers the inputs.
Verification Flow
Exercise
Why can a lock file contain several hashes for one package version?
Show answer
The version may have different valid wheel or source files for different platforms or Python versions, so the lock file lists each accepted artifact.