Programming Search⌘K

Conceptcore

Lock files

Also called lock file, lockfile, package-lock.json, Cargo.lock, uv.lock, packages.lock.json, go.sum, hash-checking mode, deterministic install.

A lock file records the exact version, and often a hash, of every package that a resolution chose, so that later installs on other machines get the same packages.

Applies to
core-languages

Idea

A manifest gives ranges, such as "any 1.x version of log". The resolver turns them into exact versions, and the result depends on the day: when a new version is published, the same manifest resolves to other packages. A lock file writes down the result of one resolution, so that the next install uses the same versions and does not resolve again.

npm describes its file package-lock.json this way: "It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates." The file "is intended to be committed into source repositories", so that "teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies".1 Cargo gives the same purpose for Cargo.lock: it describes "the state of the world at the time of a successful build", and Cargo uses it "to provide deterministic builds at different times and on different systems".2

How it works

A lock file has one entry for each package in the whole tree, direct and transitive. An entry usually holds:

  • the name and the exact version that the resolver chose;
  • where the package came from, such as a registry URL, a Git commit or a local path;
  • a hash of the package file. In package-lock.json, the field integrity is "A sha512 or sha1 Standard Subresource Integrity string for the artifact that was unpacked in this location".1

The package manager uses the file in two ways:

  1. Prefer the locked versions. When a lock file exists, the resolver starts from it. Cargo "gives the highest priority to versions contained in the Cargo.lock file", to balance reproducible builds with changes in the manifest.3 uv "will prefer the previously locked versions of packages", and a version changes only if the constraints of the project exclude it.4
  2. Check the hashes. After a download, the package manager computes the hash and compares it with the locked hash. A mismatch stops the install. In Go, the go command "computes a cryptographic hash and checks that it matches a hash in the main module’s go.sum file"; if the hash does not match, it "reports a security error and does not install the file".5

The examples below resolve two packages, write a lock file with a SHA-256 hash for each, and install from it twice. When a new version of log is published, a new resolution would take it, but the install from the lock file keeps 1.2.0. When the bytes of web 2.0.1 change on the registry, the hash check fails.

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA hash library such as OpenSSL gives SHA-256, and a std::vector of structs holds the entries. Alternative: The Java example.
JavaIdiom
CIdiomA hash library such as OpenSSL gives SHA-256, and an array of structs holds the entries. Alternative: The Go example.
C#Idiom
JavaScriptIdiomNode:crypto createHash('sha256') hashes the bytes; npm itself stores a sha512 integrity string in package-lock.json. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with an interface for an entry of the lock file. Alternative: The Go example.
GoIdiom
RustIdiomThe sha2 crate hashes the bytes, and Cargo writes the checksum of each crate in Cargo.lock. Alternative: The Go example.
KotlinIdiomJava.security.MessageDigest, as in the Java example, with a data class for an entry. Alternative: The Java example.
SQLDoes not applyA table can store the entries of a lock file, but SQL has no standard SHA-256 function. Alternative: The Python example.
BashIdiomSha256sum -c checks files against a list of hashes, which is the same check as the install step. Alternative: The Python example.
PowerShellIdiomGet-FileHash -Algorithm SHA256 hashes a file, and a hashtable holds the entries. Alternative: The C# example.
HTMLDoes not applyMarkup does not compute hashes; the integrity attribute of a script element checks a hash in the browser.
CSSDoes not applyStyle rules do not compute hashes.
Regular expressionsDoes not applyA pattern does not compute hashes.

Each example keeps the registry in memory as a map from a name and a version to bytes, and prints the first 16 hexadecimal digits of each hash. Python uses hashlib.sha256, Go uses crypto/sha256, Java uses MessageDigest and HexFormat, and C# uses SHA256.HashData and Convert.ToHexStringLower.

PythonGitHub
# A lock file records the exact version and the SHA-256 hash of each package, and an install checks both.
import hashlib

REGISTRY = {  # name -> version -> the bytes of the package
    "log": {"1.1.0": b"log 1.1.0", "1.2.0": b"log 1.2.0"},
    "web": {"2.0.0": b"web 2.0.0", "2.0.1": b"web 2.0.1"},
}
MANIFEST = {"log": 1, "web": 2}  # name -> the major version that the project accepts


def key(version):
    return tuple(int(part) for part in version.split("."))


def sha256(data):
    return hashlib.sha256(data).hexdigest()[:16]


def resolve():
    chosen = {}
    for name, major in sorted(MANIFEST.items()):
        fits = [v for v in REGISTRY[name] if key(v)[0] == major]
        chosen[name] = max(fits, key=key)
    print("resolve:", ", ".join(f"{n} {v}" for n, v in chosen.items()))
    return chosen


def lock(chosen):
    lockfile = {name: (version, sha256(REGISTRY[name][version])) for name, version in chosen.items()}
    print("lock file:")
    for name, (version, digest) in lockfile.items():
        print(f"  {name} {version} sha256 {digest}")
    return lockfile


def install(lockfile):
    print("install from the lock file:")
    for name, (version, digest) in lockfile.items():
        actual = sha256(REGISTRY[name][version])
        if actual == digest:
            print(f"  {name} {version} ok")
        else:
            print(f"  {name} {version} error: expected sha256 {digest}, got {actual}")


lockfile = lock(resolve())
REGISTRY["log"]["1.3.0"] = b"log 1.3.0"
print("log 1.3.0 is published")
resolve()
install(lockfile)
REGISTRY["web"]["2.0.1"] = b"web 2.0.1 with other code"
print("web 2.0.1 is changed on the registry")
install(lockfile)
Output
resolve: log 1.2.0, web 2.0.1
lock file:
  log 1.2.0 sha256 bc5900c6e46c5b3f
  web 2.0.1 sha256 a72ce45f235c38b5
log 1.3.0 is published
resolve: log 1.3.0, web 2.0.1
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 ok
web 2.0.1 is changed on the registry
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 error: expected sha256 a72ce45f235c38b5, got 6745f93439ad7399
  • Verdict: idiom. hashlib.sha256(data).hexdigest() gives the hash as hexadecimal text.
  • The lock file is a dict from each name to a tuple of the version and the hash. A real tool writes it to a file in a format such as TOML or JSON.
  • install reads only the lock file, so the new version 1.3.0 does not change what it installs.
JavaGitHub
// A lock file records the exact version and the SHA-256 hash of each package, and an install checks both.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    // name -> version -> the bytes of the package
    static final Map<String, Map<String, byte[]>> REGISTRY = new TreeMap<>();
    // name -> the major version that the project accepts
    static final Map<String, Integer> MANIFEST = new TreeMap<>(Map.of("log", 1, "web", 2));

    record Entry(String name, String version, String digest) {}

    static int[] key(String v) {
        return Arrays.stream(v.split("\\.")).mapToInt(Integer::parseInt).toArray();
    }

    static String sha256(byte[] data) throws NoSuchAlgorithmException {
        byte[] sum = MessageDigest.getInstance("SHA-256").digest(data);
        return HexFormat.of().formatHex(sum).substring(0, 16);
    }

    static void publish(String name, String version, String content) {
        REGISTRY.computeIfAbsent(name, n -> new TreeMap<>()).put(version, content.getBytes(StandardCharsets.UTF_8));
    }

    static List<Entry> resolve() {
        List<Entry> chosen = new ArrayList<>();
        for (var m : MANIFEST.entrySet()) {
            String best = REGISTRY.get(m.getKey()).keySet().stream()
                    .filter(v -> key(v)[0] == m.getValue())
                    .max(Comparator.comparing(Main::key, Arrays::compare))
                    .orElseThrow();
            chosen.add(new Entry(m.getKey(), best, ""));
        }
        System.out.println("resolve: " + chosen.stream()
                .map(e -> e.name() + " " + e.version()).collect(Collectors.joining(", ")));
        return chosen;
    }

    static List<Entry> lock(List<Entry> chosen) throws NoSuchAlgorithmException {
        System.out.println("lock file:");
        List<Entry> lockfile = new ArrayList<>();
        for (Entry e : chosen) {
            String digest = sha256(REGISTRY.get(e.name()).get(e.version()));
            System.out.println("  " + e.name() + " " + e.version() + " sha256 " + digest);
            lockfile.add(new Entry(e.name(), e.version(), digest));
        }
        return lockfile;
    }

    static void install(List<Entry> lockfile) throws NoSuchAlgorithmException {
        System.out.println("install from the lock file:");
        for (Entry e : lockfile) {
            String actual = sha256(REGISTRY.get(e.name()).get(e.version()));
            if (actual.equals(e.digest())) {
                System.out.println("  " + e.name() + " " + e.version() + " ok");
            } else {
                System.out.println("  " + e.name() + " " + e.version() + " error: expected sha256 "
                        + e.digest() + ", got " + actual);
            }
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        publish("log", "1.1.0", "log 1.1.0");
        publish("log", "1.2.0", "log 1.2.0");
        publish("web", "2.0.0", "web 2.0.0");
        publish("web", "2.0.1", "web 2.0.1");
        List<Entry> lockfile = lock(resolve());
        publish("log", "1.3.0", "log 1.3.0");
        System.out.println("log 1.3.0 is published");
        resolve();
        install(lockfile);
        publish("web", "2.0.1", "web 2.0.1 with other code");
        System.out.println("web 2.0.1 is changed on the registry");
        install(lockfile);
    }
}
Output
resolve: log 1.2.0, web 2.0.1
lock file:
  log 1.2.0 sha256 bc5900c6e46c5b3f
  web 2.0.1 sha256 a72ce45f235c38b5
log 1.3.0 is published
resolve: log 1.3.0, web 2.0.1
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 ok
web 2.0.1 is changed on the registry
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 error: expected sha256 a72ce45f235c38b5, got 6745f93439ad7399
  • Verdict: idiom. MessageDigest.getInstance("SHA-256") computes the hash, and HexFormat.of().formatHex turns it into text.
  • getInstance declares the checked exception NoSuchAlgorithmException, although every Java platform must support SHA-256.
  • A TreeMap keeps the names in order, so the output is the same on each run.
// A lock file records the exact version and the SHA-256 hash of each package, and an install checks both.
using System.Security.Cryptography;
using System.Text;

// name -> version -> the bytes of the package
var registry = new Dictionary<string, Dictionary<string, byte[]>>
{
    ["log"] = new() { ["1.1.0"] = "log 1.1.0"u8.ToArray(), ["1.2.0"] = "log 1.2.0"u8.ToArray() },
    ["web"] = new() { ["2.0.0"] = "web 2.0.0"u8.ToArray(), ["2.0.1"] = "web 2.0.1"u8.ToArray() },
};
// name -> the major version that the project accepts
var manifest = new SortedDictionary<string, int>(StringComparer.Ordinal) { ["log"] = 1, ["web"] = 2 };

string Sha256(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data))[..16];

List<Entry> Resolve()
{
    var chosen = manifest
        .Select(m => new Entry(m.Key, registry[m.Key].Keys.Where(v => Version.Parse(v).Major == m.Value).MaxBy(Version.Parse)!, ""))
        .ToList();
    Console.WriteLine("resolve: " + string.Join(", ", chosen.Select(e => $"{e.Name} {e.Version}")));
    return chosen;
}

List<Entry> Lock(List<Entry> chosen)
{
    Console.WriteLine("lock file:");
    var lockfile = chosen.Select(e => e with { Digest = Sha256(registry[e.Name][e.Version]) }).ToList();
    foreach (var e in lockfile)
    {
        Console.WriteLine($"  {e.Name} {e.Version} sha256 {e.Digest}");
    }
    return lockfile;
}

void Install(List<Entry> lockfile)
{
    Console.WriteLine("install from the lock file:");
    foreach (var e in lockfile)
    {
        var actual = Sha256(registry[e.Name][e.Version]);
        Console.WriteLine(actual == e.Digest
            ? $"  {e.Name} {e.Version} ok"
            : $"  {e.Name} {e.Version} error: expected sha256 {e.Digest}, got {actual}");
    }
}

var lockfile = Lock(Resolve());
registry["log"]["1.3.0"] = Encoding.UTF8.GetBytes("log 1.3.0");
Console.WriteLine("log 1.3.0 is published");
Resolve();
Install(lockfile);
registry["web"]["2.0.1"] = Encoding.UTF8.GetBytes("web 2.0.1 with other code");
Console.WriteLine("web 2.0.1 is changed on the registry");
Install(lockfile);

record Entry(string Name, string Version, string Digest);
Output
resolve: log 1.2.0, web 2.0.1
lock file:
  log 1.2.0 sha256 bc5900c6e46c5b3f
  web 2.0.1 sha256 a72ce45f235c38b5
log 1.3.0 is published
resolve: log 1.3.0, web 2.0.1
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 ok
web 2.0.1 is changed on the registry
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 error: expected sha256 a72ce45f235c38b5, got 6745f93439ad7399
  • Verdict: idiom. SHA256.HashData hashes a byte array in one call, and Convert.ToHexStringLower gives lower-case hexadecimal text.
  • The literal "log 1.1.0"u8 is a UTF-8 byte span, and ToArray copies it into an array.
  • e with { Digest = ... } copies a record with one new value, so the chosen entries stay as they were.
// A lock file records the exact version and the SHA-256 hash of each package, and an install checks both.
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"maps"
	"slices"
	"strconv"
	"strings"
)

// registry maps a name to a version to the bytes of the package.
var registry = map[string]map[string][]byte{
	"log": {"1.1.0": []byte("log 1.1.0"), "1.2.0": []byte("log 1.2.0")},
	"web": {"2.0.0": []byte("web 2.0.0"), "2.0.1": []byte("web 2.0.1")},
}

// manifest maps a name to the major version that the project accepts.
var manifest = map[string]int{"log": 1, "web": 2}

type entry struct{ name, version, digest string }

func key(v string) []int {
	var k []int
	for _, part := range strings.Split(v, ".") {
		n, _ := strconv.Atoi(part)
		k = append(k, n)
	}
	return k
}

func hash(data []byte) string {
	sum := sha256.Sum256(data)
	return hex.EncodeToString(sum[:])[:16]
}

func resolve() []entry {
	var chosen []entry
	var parts []string
	for _, name := range slices.Sorted(maps.Keys(manifest)) {
		best := ""
		for v := range registry[name] {
			if key(v)[0] == manifest[name] && (best == "" || slices.Compare(key(v), key(best)) > 0) {
				best = v
			}
		}
		chosen = append(chosen, entry{name, best, ""})
		parts = append(parts, name+" "+best)
	}
	fmt.Println("resolve:", strings.Join(parts, ", "))
	return chosen
}

func lock(chosen []entry) []entry {
	fmt.Println("lock file:")
	var lockfile []entry
	for _, e := range chosen {
		e.digest = hash(registry[e.name][e.version])
		fmt.Printf("  %s %s sha256 %s\n", e.name, e.version, e.digest)
		lockfile = append(lockfile, e)
	}
	return lockfile
}

func install(lockfile []entry) {
	fmt.Println("install from the lock file:")
	for _, e := range lockfile {
		if actual := hash(registry[e.name][e.version]); actual == e.digest {
			fmt.Printf("  %s %s ok\n", e.name, e.version)
		} else {
			fmt.Printf("  %s %s error: expected sha256 %s, got %s\n", e.name, e.version, e.digest, actual)
		}
	}
}

func main() {
	lockfile := lock(resolve())
	registry["log"]["1.3.0"] = []byte("log 1.3.0")
	fmt.Println("log 1.3.0 is published")
	resolve()
	install(lockfile)
	registry["web"]["2.0.1"] = []byte("web 2.0.1 with other code")
	fmt.Println("web 2.0.1 is changed on the registry")
	install(lockfile)
}
Output
resolve: log 1.2.0, web 2.0.1
lock file:
  log 1.2.0 sha256 bc5900c6e46c5b3f
  web 2.0.1 sha256 a72ce45f235c38b5
log 1.3.0 is published
resolve: log 1.3.0, web 2.0.1
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 ok
web 2.0.1 is changed on the registry
install from the lock file:
  log 1.2.0 ok
  web 2.0.1 error: expected sha256 a72ce45f235c38b5, got 6745f93439ad7399
  • Verdict: idiom. sha256.Sum256 returns an array of 32 bytes, and hex.EncodeToString turns a slice of it into text.
  • The lock file is a slice of structs, so its order is fixed; Go map order is random, so resolve sorts the names first.
  • lock sets the field digest on a copy of each entry, because the loop variable is a copy.
  • The names of the files. npm writes package-lock.json, Cargo writes Cargo.lock, and uv writes uv.lock.124 NuGet writes packages.lock.json when the MSBuild property RestorePackagesWithLockFile is true, and it "lists all the package dependencies".6
  • Pinned requirements files. A pip requirements file can pin each package with == and add a hash, as in FooProject == 1.2 --hash=sha256:.... In hash-checking mode, which you can force with --require-hashes, every requirement must have a hash and be pinned.78 uv can export uv.lock to requirements.txt and to pylock.toml, the format of PEP 751.4
  • Checksums without a lock file. Go records the minimum version of each dependency in go.mod, and the file go.sum holds the hashes. When a hash is not in go.sum, the go command gets it from the checksum database, by default sum.golang.org.5
  • Locked mode. In CI you want an error, not a new resolution, when the manifest and the lock file disagree. With dotnet restore --locked-mode, NuGet will "either restore the exact packages as listed in the lock file or fail" if the dependencies of the project changed.6

Pitfalls

  • Libraries and lock files. The lock file of a library does not control what its users get. Cargo warns that "Cargo.lock does not affect the consumers of your package, only Cargo.toml does that".2 NuGet says the same: the lock file of a common code project "has little say over the packages resolved for projects that depend on it".6 Test a library with the newest versions that its ranges allow, too.
  • Merge conflicts. Two branches that both add dependencies change the same lock file. Cargo notes that "The lockfile can also be a source of merge conflicts".2 Resolve the conflict in the manifest, then let the tool write the lock file again; do not edit the file by hand.
  • A stale lock file is not an update policy. A lock file keeps old versions with known bugs and vulnerabilities until someone updates it. Update on purpose, for example with uv lock --upgrade, and review the change.4
  • Hashes need pinned versions. pip requires that requirements are pinned in hash-checking mode. This "prevents a surprising hash mismatch upon the release of a new version that matches the requirement specifier".8
  • cargo install ignores the lock file by default. It "will select the latest dependencies unless --locked is passed in".2

Cost

A lock file is a text file of one entry for each package, and a large project has hundreds of entries. It saves the time of a resolution on each install. Hash checks cost one hash computation for each download. The cost is in the review: an update can change many lines of the file, and the change must still be checked.

History

npm 3 already updated a file npm-shrinkwrap.json when you saved a dependency. npm 5.0.0, released on 26 May 2017, creates package-lock.json automatically, unless a file npm-shrinkwrap.json exists.9 pip added hash-checking mode in version 8.0.8 Today Cargo, npm, NuGet and uv each write a lock file, and Go keeps hashes in go.sum.21645

References

  1. npm Docs (v11), package-lock.json, Description; packages, integrity and resolved
  2. The Cargo Book, Frequently Asked Questions, Why have Cargo.lock in version control?
  3. The Cargo Book, Dependency Resolution, Lock file
  4. uv documentation, Locking and syncing, Upgrading locked package versions; Exporting the lockfile
  5. Go Modules Reference, go.sum files; Authenticating modules
  6. NuGet documentation, PackageReference in project files, Locking dependencies; Enabling the lock file; restore behavior with lock file
  7. pip documentation, Repeatable Installs, Pinning the package versions; Hash-checking
  8. pip documentation, Secure installs, Hash-checking Mode; Forcing Hash-checking mode
  9. npm, release v5.0.0, 26 May 2017, the release notes

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RYQCPN/text.yaml