Conceptcore
Dependency resolution
Also called dependency resolution, version resolution, version solving, dependency solver, resolver, backtracking resolver, PubGrub, minimal version selection, MVS.
Dependency resolution chooses one version of each package so that every version requirement in the graph is true. Resolvers use backtracking, conflict learning or minimal version selection.
- Applies to
- core-languages
Idea
A project names its direct dependencies, and each one gives a range of versions that it accepts. Each version of each dependency has its own requirements. Dependency resolution, also called version solving, chooses one version of each package so that all these requirements are true at the same time. The pub documentation states the goal: all dependencies are satisfied, "only one version of each package is selected", and every selected package is reachable from the root package.1
The problem is hard. Abate and others write that "Dependency solving is a hard (NP-complete) problem in all non-trivial component models", because two versions of the same package cannot both be installed, or because packages declare conflicts.2 In practice, resolvers solve the common cases fast and give an error for the rest.
The result of a resolution is usually written to a lock file, so that the next install does not resolve again; see Lock files.
How it works
A resolver keeps a partial solution: the packages that it has chosen so far, and the requirements that it must still check. The basic algorithm is a search with backtracking:
- Take the next requirement. If the package is already chosen, check that the chosen version fits the range. If it does not, the partial solution has a conflict.
- Otherwise, try the versions of the package in order of preference, usually the newest first. Choose one, add its own requirements to the list, and continue.
- On a conflict, go back to the last choice and try the next version. If no version is left, go back further. If the first choice has no version left, there is no solution.
pip works this way. When it finds that an earlier assumption is wrong, "it has to backtrack, which means also discarding some of the work that has already been done, and going back to choose another path". The pip documentation adds that this "is not unexpected behaviour or a bug".3 The Cargo resolver also walks the dependencies, tries a version, and backtracks when no valid solution is found.4
The examples below resolve two cases. app needs web from 1.0 up to 3.0 and log from 1.0 up to 2.0. The newest web, 2.0, needs log 2.0 or later, so it conflicts with the requirement of app. The resolver tries the three versions of log that fit, then goes back and chooses web 1.1. In the second case app needs web 2.0, and the resolver reports that there is no solution.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | A std::map for the chosen versions and a recursive function that returns std::optional. Alternative: The Java example. |
| Java | Idiom | |
| C | Idiom | Arrays of structs for the versions and an array of chosen indexes, with an undo step after each failed try. Alternative: The Go example. |
| C# | Idiom | |
| JavaScript | Idiom | A Map for the versions and a recursive solve that returns null on failure, as in the Python example. Alternative: The Python example. |
| TypeScript | Idiom | As in JavaScript, with a type for a requirement and the return type Map<string, string> | null. Alternative: The C# example. |
| Go | Idiom | |
| Rust | Idiom | A recursive function that returns Option<BTreeMap<String, String>> and clones the map for each try. Alternative: The Go example. |
| Kotlin | Idiom | A data class for a requirement and a recursive function that returns a nullable sorted map. Alternative: The Java example. |
| SQL | Does not apply | A recursive query can walk a dependency table, but a search that goes back on a conflict is not a natural fit for SQL. |
| Bash | Idiom | The resolver is part of the package manager, such as pip, npm or apt, so a script calls the tool. Alternative: The Python example. |
| PowerShell | Idiom | Hashtables for the versions and a recursive function, as in the C# example. Alternative: The C# example. |
| HTML | Does not apply | Markup does not choose versions. |
| CSS | Does not apply | Style rules do not choose versions. |
| Regular expressions | Does not apply | A pattern does not choose versions. |
Each example stores the requirements as triples of a name, the lowest allowed version and the first version that is not allowed. solve takes the list of open requirements and the map of chosen versions. It returns the map, or nothing when the branch fails, so the caller tries the next version. The map is copied for each choice, so going back needs no undo step.
# A backtracking dependency resolver: try the newest version first, and go back on a conflict.
# A requirement is (package, lowest allowed version, first version not allowed).
VERSIONS = {
"web": {"2.0": [("log", "2.0", "3.0")],
"1.1": [("log", "1.1", "2.0")],
"1.0": [("log", "1.0", "2.0")]},
"log": {"2.0": [], "1.2": [], "1.1": [], "1.0": []},
}
def key(version):
return tuple(int(part) for part in version.split("."))
def fits(version, lo, hi):
return key(lo) <= key(version) < key(hi)
def solve(todo, chosen):
if not todo:
return chosen
(name, lo, hi, who), rest = todo[0], todo[1:]
if name in chosen:
if fits(chosen[name], lo, hi):
return solve(rest, chosen)
print(f" conflict: {who} needs {name} >={lo},<{hi}, but {name} {chosen[name]} is chosen")
return None
for version in sorted(VERSIONS[name], key=key, reverse=True):
if fits(version, lo, hi):
print(f"try {name} {version}")
deps = [(dep, dlo, dhi, f"{name} {version}") for dep, dlo, dhi in VERSIONS[name][version]]
result = solve(rest + deps, {**chosen, name: version})
if result is not None:
return result
return None
for root in ([("web", "1.0", "3.0", "app"), ("log", "1.0", "2.0", "app")],
[("web", "2.0", "3.0", "app"), ("log", "1.0", "2.0", "app")]):
print("app needs", ", ".join(f"{n} >={lo},<{hi}" for n, lo, hi, _ in root))
result = solve(root, {})
if result is None:
print("result: no solution")
else:
print("result:", ", ".join(f"{n} {v}" for n, v in sorted(result.items())))
app needs web >=1.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
try web 1.1
try log 1.2
result: log 1.2, web 1.1
app needs web >=2.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
result: no solution
- Verdict: idiom. A dict maps each package to its versions, and each version to its requirements.
solveis recursive.{**chosen, name: version}makes a new dict for each choice, so a failed branch leaves the caller's dict as it was.sorted(..., key=key, reverse=True)tries the newest version first. The key turns "1.10" into a tuple of numbers, so that it sorts after "1.9".
// A backtracking dependency resolver: try the newest version first, and go back on a conflict.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
// who needs name in the range [lo, hi).
record Req(String name, String lo, String hi, String who) {}
static final Map<String, Map<String, List<Req>>> VERSIONS = Map.of(
"web", Map.of(
"2.0", List.of(new Req("log", "2.0", "3.0", "")),
"1.1", List.of(new Req("log", "1.1", "2.0", "")),
"1.0", List.of(new Req("log", "1.0", "2.0", ""))),
"log", Map.of("2.0", List.of(), "1.2", List.of(), "1.1", List.of(), "1.0", List.of()));
static int cmp(String a, String b) {
String[] pa = a.split("\\."), pb = b.split("\\.");
for (int i = 0; i < pa.length; i++) {
int d = Integer.parseInt(pa[i]) - Integer.parseInt(pb[i]);
if (d != 0) {
return d;
}
}
return 0;
}
static boolean fits(String v, String lo, String hi) {
return cmp(lo, v) <= 0 && cmp(v, hi) < 0;
}
static TreeMap<String, String> solve(List<Req> todo, TreeMap<String, String> chosen) {
if (todo.isEmpty()) {
return chosen;
}
Req r = todo.get(0);
List<Req> rest = todo.subList(1, todo.size());
String v = chosen.get(r.name());
if (v != null) {
if (fits(v, r.lo(), r.hi())) {
return solve(rest, chosen);
}
System.out.printf(" conflict: %s needs %s >=%s,<%s, but %s %s is chosen%n",
r.who(), r.name(), r.lo(), r.hi(), r.name(), v);
return null;
}
List<String> list = new ArrayList<>(VERSIONS.get(r.name()).keySet());
list.sort(Comparator.comparing((String s) -> s, Main::cmp).reversed());
for (String version : list) {
if (!fits(version, r.lo(), r.hi())) {
continue;
}
System.out.println("try " + r.name() + " " + version);
List<Req> next = new ArrayList<>(rest);
for (Req d : VERSIONS.get(r.name()).get(version)) {
next.add(new Req(d.name(), d.lo(), d.hi(), r.name() + " " + version));
}
var c = new TreeMap<>(chosen);
c.put(r.name(), version);
var result = solve(next, c);
if (result != null) {
return result;
}
}
return null;
}
public static void main(String[] args) {
List<List<Req>> roots = List.of(
List.of(new Req("web", "1.0", "3.0", "app"), new Req("log", "1.0", "2.0", "app")),
List.of(new Req("web", "2.0", "3.0", "app"), new Req("log", "1.0", "2.0", "app")));
for (List<Req> root : roots) {
System.out.println("app needs " + root.stream()
.map(r -> r.name() + " >=" + r.lo() + ",<" + r.hi())
.collect(Collectors.joining(", ")));
var result = solve(root, new TreeMap<>());
if (result == null) {
System.out.println("result: no solution");
} else {
System.out.println("result: " + result.entrySet().stream()
.map(e -> e.getKey() + " " + e.getValue())
.collect(Collectors.joining(", ")));
}
}
}
}
app needs web >=1.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
try web 1.1
try log 1.2
result: log 1.2, web 1.1
app needs web >=2.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
result: no solution
- Verdict: idiom. A record holds one requirement, and
Map.ofbuilds the registry. - A
TreeMapkeeps the chosen versions sorted by name. A newTreeMapis made for each try, so a failed branch does not change the map of the caller. nullmeans that the branch failed; anOptionalwould also work.
// A backtracking dependency resolver: try the newest version first, and go back on a conflict.
var versions = new Dictionary<string, Dictionary<string, Req[]>>
{
["web"] = new()
{
["2.0"] = [new("log", "2.0", "3.0", "")],
["1.1"] = [new("log", "1.1", "2.0", "")],
["1.0"] = [new("log", "1.0", "2.0", "")],
},
["log"] = new() { ["2.0"] = [], ["1.2"] = [], ["1.1"] = [], ["1.0"] = [] },
};
int Cmp(string a, string b) =>
a.Split('.').Select(int.Parse).Zip(b.Split('.').Select(int.Parse), (x, y) => x - y)
.FirstOrDefault(d => d != 0);
bool Fits(string v, string lo, string hi) => Cmp(lo, v) <= 0 && Cmp(v, hi) < 0;
SortedDictionary<string, string>? Solve(List<Req> todo, SortedDictionary<string, string> chosen)
{
if (todo.Count == 0)
{
return chosen;
}
var r = todo[0];
var rest = todo.Skip(1).ToList();
if (chosen.TryGetValue(r.Name, out var v))
{
if (Fits(v, r.Lo, r.Hi))
{
return Solve(rest, chosen);
}
Console.WriteLine($" conflict: {r.Who} needs {r.Name} >={r.Lo},<{r.Hi}, but {r.Name} {v} is chosen");
return null;
}
foreach (var version in versions[r.Name].Keys.Order(Comparer<string>.Create(Cmp)).Reverse())
{
if (!Fits(version, r.Lo, r.Hi))
{
continue;
}
Console.WriteLine($"try {r.Name} {version}");
var next = rest.Concat(versions[r.Name][version].Select(d => d with { Who = $"{r.Name} {version}" })).ToList();
var c = new SortedDictionary<string, string>(chosen, StringComparer.Ordinal) { [r.Name] = version };
if (Solve(next, c) is { } result)
{
return result;
}
}
return null;
}
List<Req>[] roots =
[
[new("web", "1.0", "3.0", "app"), new("log", "1.0", "2.0", "app")],
[new("web", "2.0", "3.0", "app"), new("log", "1.0", "2.0", "app")],
];
foreach (var root in roots)
{
Console.WriteLine("app needs " + string.Join(", ", root.Select(r => $"{r.Name} >={r.Lo},<{r.Hi}")));
var result = Solve(root, new SortedDictionary<string, string>(StringComparer.Ordinal));
Console.WriteLine(result is null
? "result: no solution"
: "result: " + string.Join(", ", result.Select(e => $"{e.Key} {e.Value}")));
}
// Who needs Name in the range [Lo, Hi).
record Req(string Name, string Lo, string Hi, string Who);
app needs web >=1.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
try web 1.1
try log 1.2
result: log 1.2, web 1.1
app needs web >=2.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
result: no solution
- Verdict: idiom. A positional record holds one requirement, and
d with { Who = ... }copies it with the name of the package that needs it. - A
SortedDictionarywithStringComparer.Ordinalkeeps the chosen versions sorted by name, and a new one is made for each try. - The return type
SortedDictionary<string, string>?is nullable, andis { } resulttests for a solution.
// A backtracking dependency resolver: try the newest version first, and go back on a conflict.
package main
import (
"fmt"
"maps"
"slices"
"strconv"
"strings"
)
// req says that who needs name in the range [lo, hi).
type req struct{ name, lo, hi, who string }
var versions = map[string]map[string][]req{
"web": {
"2.0": {{"log", "2.0", "3.0", ""}},
"1.1": {{"log", "1.1", "2.0", ""}},
"1.0": {{"log", "1.0", "2.0", ""}},
},
"log": {"2.0": nil, "1.2": nil, "1.1": nil, "1.0": nil},
}
func cmp(a, b string) int {
pa, pb := strings.Split(a, "."), strings.Split(b, ".")
for i := range pa {
x, _ := strconv.Atoi(pa[i])
y, _ := strconv.Atoi(pb[i])
if x != y {
return x - y
}
}
return 0
}
func fits(v, lo, hi string) bool { return cmp(lo, v) <= 0 && cmp(v, hi) < 0 }
func solve(todo []req, chosen map[string]string) map[string]string {
if len(todo) == 0 {
return chosen
}
r, rest := todo[0], todo[1:]
if v, ok := chosen[r.name]; ok {
if fits(v, r.lo, r.hi) {
return solve(rest, chosen)
}
fmt.Printf(" conflict: %s needs %s >=%s,<%s, but %s %s is chosen\n", r.who, r.name, r.lo, r.hi, r.name, v)
return nil
}
list := slices.SortedFunc(maps.Keys(versions[r.name]), func(a, b string) int { return cmp(b, a) })
for _, v := range list {
if !fits(v, r.lo, r.hi) {
continue
}
fmt.Println("try", r.name, v)
next := slices.Clone(rest)
for _, d := range versions[r.name][v] {
next = append(next, req{d.name, d.lo, d.hi, r.name + " " + v})
}
c := maps.Clone(chosen)
c[r.name] = v
if result := solve(next, c); result != nil {
return result
}
}
return nil
}
func main() {
roots := [][]req{
{{"web", "1.0", "3.0", "app"}, {"log", "1.0", "2.0", "app"}},
{{"web", "2.0", "3.0", "app"}, {"log", "1.0", "2.0", "app"}},
}
for _, root := range roots {
var needs []string
for _, r := range root {
needs = append(needs, fmt.Sprintf("%s >=%s,<%s", r.name, r.lo, r.hi))
}
fmt.Println("app needs", strings.Join(needs, ", "))
result := solve(root, map[string]string{})
if result == nil {
fmt.Println("result: no solution")
continue
}
var parts []string
for _, n := range slices.Sorted(maps.Keys(result)) {
parts = append(parts, n+" "+result[n])
}
fmt.Println("result:", strings.Join(parts, ", "))
}
}
app needs web >=1.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
try web 1.1
try log 1.2
result: log 1.2, web 1.1
app needs web >=2.0,<3.0, log >=1.0,<2.0
try web 2.0
try log 1.2
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.2 is chosen
try log 1.1
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.1 is chosen
try log 1.0
conflict: web 2.0 needs log >=2.0,<3.0, but log 1.0 is chosen
result: no solution
- Verdict: idiom. A map of maps holds the versions, and a struct holds one requirement.
maps.Clonecopies the chosen versions for each try, andslices.Clonecopies the open requirements, so thatappenddoes not change the slice of the caller.- Go map order is random, so
slices.SortedFuncsorts the versions, newest first, andslices.Sortedsorts the names of the result.
Variations and related ideas
- Conflict-driven clause learning. Simple backtracking can try the same failing combination again and again. In the example, the resolver tries all three versions of
logwithweb2.0, although the cause of the conflict isweb2.0 itself. PubGrub backtracks to the package that caused the conflict, and it "also records the root cause of that conflict", so it does not repeat the same dead end.1 It is "a SAT solver using conflict-driven clause learning".5 uv uses pubgrub-rs, the Rust implementation of PubGrub.6 The records of the conflicts also give a clear error message that names the packages involved.6 - Generic solvers. Some package managers give the problem to a general SAT, PBO or MILP solver. Abate and others found that SAT-based dependency solving is starting to take off.2
- Minimal version selection. Go modules avoid the search. A
requiredirective "declares a minimum required version", and the go command uses minimal version selection (MVS) to produce the build list.7 To construct the build list, Cox writes, start with the target and append the build list of each requirement, and "If a module appears in the list multiple times, keep only the newest version".8 So the result is the highest of the minimums, not the newest version in the registry. Because a requirement has no upper limit, there are no conflicts to backtrack from. The program below follows this definition:
# Minimal version selection: visit every requirement, then keep the highest of the minimums.
REQUIRES = {
("A", "1.0"): [("B", "1.2"), ("C", "1.2")],
("B", "1.2"): [("D", "1.3")],
("C", "1.2"): [("D", "1.4")],
("D", "1.3"): [],
("D", "1.4"): [],
("D", "1.5"): [], # newer, but nothing asks for it
}
def key(version):
return tuple(int(part) for part in version.split("."))
def build_list(target):
seen, todo = set(), [target]
while todo:
module = todo.pop()
if module not in seen:
seen.add(module)
todo.extend(REQUIRES[module])
print("reachable:", ", ".join(f"{m} {v}" for m, v in sorted(seen)))
newest = {}
for module, version in seen:
if module not in newest or key(version) > key(newest[module]):
newest[module] = version
return sorted(newest.items())
print("build list:", ", ".join(f"{m} {v}" for m, v in build_list(("A", "1.0"))))
reachable: A 1.0, B 1.2, C 1.2, D 1.3, D 1.4
build list: A 1.0, B 1.2, C 1.2, D 1.4
- Lowest applicable version. NuGet restores "the lowest possible version of a package as defined by its dependencies". When a package is also a direct dependency of the application, the direct version wins, and when two subgraphs need different versions, NuGet uses the lowest version that satisfies all of the requirements.9
- Nearest definition. Maven does not search. When the tree holds several versions of one artifact, Maven picks the "nearest definition", the version that is closest to the project in the tree. If two versions are at the same depth, the first declaration wins.10
- Unification. Cargo prefers the highest version that is available, and it tries to reuse one version of a package for all the packages that need it. If conflicts stop this, Cargo backtracks, "erroring if no solution is found, rather than selecting multiple versions". When multiple versions of one crate do appear in the graph, the Rust compiler treats their types as different types, and
cargo tree -dshows where the duplicates come from.4 See Transitive dependencies.
Pitfalls
- Long backtracking. On a large graph a backtracking resolver can try many versions. pip may download several versions of the same package while it backtracks.3 Narrow the ranges of your direct dependencies, or use a lock file.
- Silent downgrades. Under the rule that a direct dependency wins, NuGet can pick a lower version than a transitive package needs. NuGet warns that this "can result in a downgrade of the package version, thus potentially breaking other dependencies in the graph", and it gives a warning.9
- A version that the build did not test. With Maven's nearest definition, a deep dependency that needs version 2.0 can get version 1.0, because 1.0 is nearer to the project.10 Declare the version in your own POM to choose it.
- Resolving again by accident. A resolver gives a different result when the registry changes. Cargo "gives the highest priority to versions contained in the Cargo.lock file", to balance reproducible builds with changes in the manifest.4 Commit the lock file of an application.
Cost
The general problem is NP-complete, so no known resolver is fast on every input.2 A backtracking resolver can try many combinations before it finds a solution, and pip must download the distribution files of a package to get its dependencies.3 Conflict learning cuts the repeated work on many real graphs.1 Minimal version selection is easy to compute: Cox describes it as efficient to implement "using nothing more complex than recursive graph traversals".8
History
In 2018 Russ Cox proposed minimal version selection for Go, in the post of February 21, 2018.8 In the same year Natalie Weizenbaum introduced PubGrub in a blog post, for the Dart package manager.5 pip got a backtracking resolver in version 20.3.3 In 2020 Abate and others reviewed the research on dependency solving and the solvers of the main package managers.2
References
- Dart pub repository, doc/solver.md, the PubGrub version solving algorithm, Overview; Conflict Resolution
- Pietro Abate, Roberto Di Cosmo, Georgios Gousios and Stefano Zacchiroli, Dependency Solving Is Still Hard, but We Are Getting Better at It, SANER 2020, abstract
- pip documentation, Dependency Resolution, Backtracking
- The Cargo Book, Dependency Resolution, Resolver algorithm (key steps); Version numbers; Lock file
- pubgrub-rs, PubGrub (README), The PubGrub Algorithm
- uv documentation, Reference, Internals, Resolver, Resolver
- Go Modules Reference, require directive
- Russ Cox, Minimal Version Selection (Go and Versioning, Part 4), 2018, the introduction; Algorithm 1, Construct Build List
- NuGet documentation, NuGet Package Dependency Resolution, Dependency resolution rules
- Maven, Introduction to the Dependency Mechanism, Transitive Dependencies; dependency mediation
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2X57E3 Edit this page History Report an error Markdown