TExcelTAD
Home › Build Fundamentals: From Source to Binary › Dependency Resolution & Lockfiles

Dependency Resolution & Lockfiles

Your manifest says what you accept (web ^2.1, log ~1.3). Your dependencies have manifests too, with their own ranges. Dependency resolution is the job of picking one concrete version of every package so that all those ranges are satisfied at once. A lockfile records the answer, so the next build (on your laptop, a colleague's, or CI) uses exactly the same versions instead of solving again.

Ecosystem Manifest Lockfile
npm / pnpm / Yarn package.json package-lock.json / pnpm-lock.yaml / yarn.lock
Cargo Cargo.toml Cargo.lock
Python (Poetry, uv) pyproject.toml poetry.lock / uv.lock
Go go.mod go.sum (hashes; go.mod already pins versions)
Conan conanfile.py / .txt conan.lock
vcpkg vcpkg.json a builtin-baseline commit plus overrides
Gradle build.gradle.kts gradle.lockfile (opt-in)

Model: a backtracking resolver

The registry below has a few versions of four packages. The resolver tries the highest version of each package first and backtracks when a choice leads to a conflict. This is the basic algorithm; production resolvers (PubGrub in Cargo, uv and Poetry; SAT solvers in others) are smarter about which choice to undo and how to explain failures, but they answer the same question:

python · try it yourself
REGISTRY = {   # package -> version -> {dependency: allowed versions}
    "web":   {"2.1.0": {"http": ["1.2", "1.3"], "log": ["1.3", "1.4"]},
              "2.2.0": {"http": ["1.4"],        "log": ["1.4"]}},
    "http":  {"1.2": {"tls": ["3.0"]}, "1.3": {"tls": ["3.0", "3.1"]}, "1.4": {"tls": ["3.1"]}},
    "log":   {"1.3": {}, "1.4": {}},
    "tls":   {"3.0": {}, "3.1": {}},
}

def resolve(requirements, chosen=None, depth=0):
    """requirements: list of (package, allowed versions). Returns {package: version} or None."""
    chosen = dict(chosen or {})
    if not requirements:
        return chosen
    (pkg, allowed), rest = requirements[0], requirements[1:]
    if pkg in chosen:                                   # already picked: must be compatible
        return resolve(rest, chosen, depth) if chosen[pkg] in allowed else None
    for version in sorted(allowed, key=lambda v: [int(x) for x in v.split(".")], reverse=True):
        print("  " * depth + f"try {pkg} {version}")
        deps = list(REGISTRY[pkg][version].items())
        result = resolve(rest + deps, {**chosen, pkg: version}, depth + 1)
        if result:
            return result
        print("  " * depth + f"backtrack: {pkg} {version} leads to a conflict")
    return None

# our manifest: any web 2.x, but log must be 1.3 (say 1.4 has a bug we hit)
lock = resolve([("web", ["2.1.0", "2.2.0"]), ("log", ["1.3"])])
print("resolved:", lock)
try web 2.2.0
  try log 1.3
    try http 1.4
    backtrack: http 1.4 leads to a conflict
  backtrack: log 1.3 leads to a conflict
backtrack: web 2.2.0 leads to a conflict
try web 2.1.0
  try log 1.3
    try http 1.3
      try tls 3.1
resolved: {'web': '2.1.0', 'log': '1.3', 'http': '1.3', 'tls': '3.1'}

The resolver first tried the newest web 2.2.0, then log 1.3 (the only version our manifest allows) and http 1.4. Then it reached web 2.2.0's own requirement log 1.4, which contradicts the log 1.3 already chosen. With no alternatives left on that path, it undid the choices one by one up to web, tried web 2.1.0, and found a consistent set. A human doing this by hand for 500 transitive dependencies would never finish; that's why every modern package manager has a solver.

Why lock?

Ranges make a resolution depend on what the registry contains today. Publish one new version, and the same manifest resolves differently. The model below resolves once, writes a lockfile, then a new tls 3.2 is published:

python · try it yourself
import hashlib, json

REGISTRY = {
    "http": {"1.3": {"tls": ["3.0", "3.1", "3.2"]}},
    "tls":  {"3.0": {}, "3.1": {}},
}
manifest = {"http": ["1.3"]}

def resolve(reqs):
    picked, todo = {}, list(reqs.items())
    while todo:
        pkg, allowed = todo.pop(0)
        candidates = [v for v in allowed if v in REGISTRY[pkg]]
        version = max(candidates, key=lambda v: [int(x) for x in v.split(".")])
        picked[pkg] = version
        todo += list(REGISTRY[pkg][version].items())
    return picked

def tarball(pkg, version):            # stand-in for the downloaded archive's bytes
    return f"{pkg}-{version} source code".encode()

def write_lock(picked):
    return {pkg: {"version": v, "sha256": hashlib.sha256(tarball(pkg, v)).hexdigest()[:16] + "..."}
            for pkg, v in sorted(picked.items())}

lock = write_lock(resolve(manifest))
print("lockfile:", json.dumps(lock, indent=1))

REGISTRY["tls"]["3.2"] = {}           # upstream publishes a new release
print("fresh resolve today:", resolve(manifest))
print("install from lockfile:", {p: e["version"] for p, e in lock.items()})
lockfile: {
 "http": {
  "version": "1.3",
  "sha256": "61cc55df3c9b855a..."
 },
 "tls": {
  "version": "3.1",
  "sha256": "bb07bd04803e3231..."
 }
}
fresh resolve today: {'http': '1.3', 'tls': '3.2'}
install from lockfile: {'http': '1.3', 'tls': '3.1'}

Without the lockfile, today's build silently picks up tls 3.2, a version nobody on the team has tested. With it, every machine installs 3.1 until someone deliberately updates (cargo update, npm update, uv lock --upgrade), and that update shows up as a reviewable diff of the lockfile in version control.

The lockfile also stores a hash of each package's archive. If the registry (or a mirror, or an attacker) later serves different bytes under the same version number, the install fails instead of building with them.

Verifying hashes for real

Package managers check those hashes for you. The same check by hand, with sha256sum -c, which reads a file of <hash> <path> lines:

bash · try it yourself
mkdir -p vendor && cd vendor
printf 'tls 3.1 source code\n' > tls-3.1.tar
sha256sum tls-3.1.tar > deps.lock          # record the hash at lock time
sha256sum -c deps.lock
printf 'tls 3.1 source code, plus a backdoor\n' > tls-3.1.tar   # same name, different bytes
sha256sum -c deps.lock || echo "refusing to build with a modified dependency"
tls-3.1.tar: OK
tls-3.1.tar: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
refusing to build with a modified dependency

Rules of thumb

  • Applications commit their lockfile. That is what makes their builds repeatable.
  • Libraries publish ranges in their manifest; their lockfile (if any) only affects their own CI, because a library's users resolve versions for the whole application.
  • CI installs from the lockfile and fails if it is out of date: npm ci, cargo build --locked, uv sync --locked, poetry install (it uses the lock), pnpm install --frozen-lockfile.
  • Update on purpose and often. A lockfile that is never updated means security fixes never arrive. Bots such as Dependabot and Renovate open the update pull requests for you (Software Supply Chain Security).

Test yourself

Why did the resolver backtrack from web 2.2.0?

  1. It is a pre-release
  2. It requires log 1.4, but the manifest only allows log 1.3
  3. It was the oldest version
  4. The registry was offline

What does a lockfile protect against when upstream publishes a new version?

  1. Nothing
  2. Builds silently picking up an untested version: installs use the recorded versions until a deliberate update
  3. Slow downloads
  4. Compiler errors

Why do lockfiles record a hash of each package?

  1. To compress them
  2. So that different bytes served under the same version number are rejected
  3. To sort them
  4. For licensing