Programming Search⌘K

Conceptcore

Transitive dependencies

Also called transitive dependency, indirect dependency, dependency of a dependency, dependency tree, dependency graph, diamond dependency, duplicate dependencies, hoisting.

A transitive dependency is a package that a project needs only because one of its dependencies needs it. Shared dependencies form diamonds, and conflicting needs can bring in two versions.

Applies to
core-languages

Idea

A project lists its direct dependencies: the packages that its own code uses. Each of these packages has its own dependencies, and they have theirs. All the packages that the project gets in this way, but does not list itself, are its transitive dependencies, also called indirect dependencies.

Package managers install them without being asked. Maven "avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically", and "There is no limit to the number of levels that dependencies can be gathered from".1 Maven notes that "the graph of included libraries can quickly grow quite large".1

Go marks the difference in the file go.mod. An // indirect comment on a requirement "indicates that no package from the required module is directly imported by any package in the main module".2

How it works

The dependencies of a project form a directed graph: an edge goes from each package to each package that it needs. The package manager walks this graph from the project. Three shapes need care:

  • A diamond. Two packages need the same third package. In the examples below, cli and web both need log. The package manager installs log one time, and both packages use it.
  • Two versions. Two packages need versions of the same package that are not compatible. In the examples, cli needs json 0.9 and web needs json 1.1. Some package managers install both versions; others must choose one or fail. See Dependency resolution.
  • A cycle. A package can depend, through other packages, on itself. npm stops the loop because a package that is already installed in a parent folder is not installed again.3 For Maven, "A problem arises only if a cyclic dependency is discovered".1

npm shows how one tool handles all three in folders. When you install foo, npm unpacks it into ./node_modules/foo, and the dependencies of foo go into ./node_modules/foo/node_modules/....3 To save space, npm "hoists dependencies by default": it installs each dependency at the highest folder possible. If a package needs a version that is not compatible with the copy in a parent folder, npm "must install its own copy" in a nested folder.3

The examples below print the tree of a small project, mark each package that was already shown with (*), and then list the packages that more than one package needs and the packages that are present in more than one version.

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map<std::string, std::vector<std::string>> for the graph and a std::set for the shown packages. Alternative: The Java example.
JavaIdiom
CIdiomAn array of structs with child indexes, and an array of flags for the shown packages. Alternative: The Go example.
C#Idiom
JavaScriptIdiomAn object or a Map for the graph and a Set for the shown packages; npm ls prints the real tree of a project. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with the type Record<string, string[]> for the graph. Alternative: The Go example.
GoIdiom
RustIdiomA HashMap for the graph and a BTreeSet for the shown packages; cargo tree prints the real tree of a project. Alternative: The Go example.
KotlinIdiomMapOf for the graph, a sortedSetOf for the shown packages and groupBy for the versions. Alternative: The Java example.
SQLIdiomA recursive common table expression walks a table of dependency edges and finds all transitive dependencies. Alternative: The Python example.
BashIdiomThe tools print the tree, for example npm ls, cargo tree, go mod graph and mvn dependency:tree. Alternative: The Python example.
PowerShellIdiomHashtables for the graph and a recursive function, as in the C# example. Alternative: The C# example.
HTMLDoes not applyMarkup does not walk a graph.
CSSDoes not applyStyle rules do not walk a graph.
Regular expressionsDoes not applyA pattern does not walk a graph.

Each example stores the graph as a map from a package and its version to the list of packages that it needs. A recursive function prints the tree with a prefix of | or four spaces for each level, and keeps a set of the packages that it has shown. The direct dependencies are the children of app; the transitive dependencies are the other packages in the set.

PythonGitHub
# Print a dependency tree, then find the packages that are shared (a diamond) and the packages with two versions.
DEPS = {
    "app": ["cli 1.0", "web 2.0"],
    "cli 1.0": ["json 0.9", "log 1.2"],
    "web 2.0": ["http 1.4", "json 1.1", "log 1.2"],
    "http 1.4": ["log 1.2"],
    "json 0.9": [],
    "json 1.1": [],
    "log 1.2": [],
}
seen = set()


def show(package, prefix=""):
    children = DEPS[package]
    for i, child in enumerate(children):
        last = i == len(children) - 1
        mark = " (*)" if child in seen else ""
        print(prefix + ("`-- " if last else "+-- ") + child + mark)
        if not mark:
            seen.add(child)
            show(child, prefix + ("    " if last else "|   "))


print("app")
show("app")
transitive = sorted(seen - set(DEPS["app"]))
print("direct:", ", ".join(DEPS["app"]))
print("transitive:", ", ".join(transitive))

users, versions = {}, {}
for package, children in DEPS.items():
    for child in children:
        users.setdefault(child, []).append(package)
for package in sorted(seen):
    name, version = package.split()
    versions.setdefault(name, []).append(version)
print("needed by more than one package:")
for package in sorted(users):
    if len(users[package]) > 1:
        print(f"  {package}: {', '.join(sorted(users[package]))}")
print("more than one version:")
for name in sorted(versions):
    if len(versions[name]) > 1:
        print(f"  {name}: {', '.join(versions[name])}")
Output
app
+-- cli 1.0
|   +-- json 0.9
|   `-- log 1.2
`-- web 2.0
    +-- http 1.4
    |   `-- log 1.2 (*)
    +-- json 1.1
    `-- log 1.2 (*)
direct: cli 1.0, web 2.0
transitive: http 1.4, json 0.9, json 1.1, log 1.2
needed by more than one package:
  log 1.2: cli 1.0, http 1.4, web 2.0
more than one version:
  json: 0.9, 1.1
  • Verdict: idiom. A dict maps each package to a list of the packages that it needs, and a set records the packages that show has printed.
  • The set difference seen - set(DEPS["app"]) gives the transitive dependencies.
  • setdefault builds the maps from a package to its users and from a name to its versions in one pass each.
JavaGitHub
// Print a dependency tree, then find the packages that are shared (a diamond) and the packages with two versions.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {
    static final Map<String, List<String>> DEPS = Map.of(
            "app", List.of("cli 1.0", "web 2.0"),
            "cli 1.0", List.of("json 0.9", "log 1.2"),
            "web 2.0", List.of("http 1.4", "json 1.1", "log 1.2"),
            "http 1.4", List.of("log 1.2"),
            "json 0.9", List.of(),
            "json 1.1", List.of(),
            "log 1.2", List.of());
    static final Set<String> SEEN = new TreeSet<>();

    static void show(String pkg, String prefix) {
        List<String> children = DEPS.get(pkg);
        for (int i = 0; i < children.size(); i++) {
            String child = children.get(i);
            boolean last = i == children.size() - 1;
            String branch = last ? "`-- " : "+-- ";
            if (SEEN.contains(child)) {
                System.out.println(prefix + branch + child + " (*)");
                continue;
            }
            System.out.println(prefix + branch + child);
            SEEN.add(child);
            show(child, prefix + (last ? "    " : "|   "));
        }
    }

    public static void main(String[] args) {
        System.out.println("app");
        show("app", "");
        Set<String> transitive = new TreeSet<>(SEEN);
        transitive.removeAll(DEPS.get("app"));
        System.out.println("direct: " + String.join(", ", DEPS.get("app")));
        System.out.println("transitive: " + String.join(", ", transitive));

        Map<String, Set<String>> users = new TreeMap<>();
        DEPS.forEach((pkg, children) -> children.forEach(
                child -> users.computeIfAbsent(child, c -> new TreeSet<>()).add(pkg)));
        Map<String, List<String>> versions = new TreeMap<>();
        for (String p : SEEN) {
            String[] parts = p.split(" ");
            versions.computeIfAbsent(parts[0], n -> new ArrayList<>()).add(parts[1]);
        }
        System.out.println("needed by more than one package:");
        users.forEach((p, who) -> {
            if (who.size() > 1) {
                System.out.println("  " + p + ": " + String.join(", ", who));
            }
        });
        System.out.println("more than one version:");
        versions.forEach((name, list) -> {
            if (list.size() > 1) {
                System.out.println("  " + name + ": " + String.join(", ", list));
            }
        });
    }
}
Output
app
+-- cli 1.0
|   +-- json 0.9
|   `-- log 1.2
`-- web 2.0
    +-- http 1.4
    |   `-- log 1.2 (*)
    +-- json 1.1
    `-- log 1.2 (*)
direct: cli 1.0, web 2.0
transitive: http 1.4, json 0.9, json 1.1, log 1.2
needed by more than one package:
  log 1.2: cli 1.0, http 1.4, web 2.0
more than one version:
  json: 0.9, 1.1
  • Verdict: idiom. Map.of holds the graph, and a TreeSet keeps the shown packages in order.
  • removeAll on a copy of the set gives the transitive dependencies.
  • computeIfAbsent builds the map from a package to its users, and a TreeMap keeps the output in order.
// Print a dependency tree, then find the packages that are shared (a diamond) and the packages with two versions.
var deps = new Dictionary<string, string[]>
{
    ["app"] = ["cli 1.0", "web 2.0"],
    ["cli 1.0"] = ["json 0.9", "log 1.2"],
    ["web 2.0"] = ["http 1.4", "json 1.1", "log 1.2"],
    ["http 1.4"] = ["log 1.2"],
    ["json 0.9"] = [],
    ["json 1.1"] = [],
    ["log 1.2"] = [],
};
var seen = new SortedSet<string>(StringComparer.Ordinal);

void Show(string package, string prefix)
{
    var children = deps[package];
    for (var i = 0; i < children.Length; i++)
    {
        var child = children[i];
        var last = i == children.Length - 1;
        var branch = last ? "`-- " : "+-- ";
        if (seen.Contains(child))
        {
            Console.WriteLine(prefix + branch + child + " (*)");
            continue;
        }
        Console.WriteLine(prefix + branch + child);
        seen.Add(child);
        Show(child, prefix + (last ? "    " : "|   "));
    }
}

Console.WriteLine("app");
Show("app", "");
Console.WriteLine("direct: " + string.Join(", ", deps["app"]));
Console.WriteLine("transitive: " + string.Join(", ", seen.Except(deps["app"])));

var users = deps
    .SelectMany(d => d.Value.Select(child => (Child: child, User: d.Key)))
    .GroupBy(x => x.Child)
    .OrderBy(g => g.Key, StringComparer.Ordinal);
Console.WriteLine("needed by more than one package:");
foreach (var g in users.Where(g => g.Count() > 1))
{
    Console.WriteLine($"  {g.Key}: {string.Join(", ", g.Select(x => x.User).Order(StringComparer.Ordinal))}");
}
Console.WriteLine("more than one version:");
foreach (var g in seen.GroupBy(p => p.Split(' ')[0]).Where(g => g.Count() > 1))
{
    Console.WriteLine($"  {g.Key}: {string.Join(", ", g.Select(p => p.Split(' ')[1]))}");
}
Output
app
+-- cli 1.0
|   +-- json 0.9
|   `-- log 1.2
`-- web 2.0
    +-- http 1.4
    |   `-- log 1.2 (*)
    +-- json 1.1
    `-- log 1.2 (*)
direct: cli 1.0, web 2.0
transitive: http 1.4, json 0.9, json 1.1, log 1.2
needed by more than one package:
  log 1.2: cli 1.0, http 1.4, web 2.0
more than one version:
  json: 0.9, 1.1
  • Verdict: idiom. A dictionary of arrays holds the graph, and a SortedSet with StringComparer.Ordinal keeps the shown packages in order.
  • seen.Except(deps["app"]) gives the transitive dependencies.
  • LINQ SelectMany and GroupBy turn the graph into a map from each package to its users.
// Print a dependency tree, then find the packages that are shared (a diamond) and the packages with two versions.
package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

var deps = map[string][]string{
	"app":      {"cli 1.0", "web 2.0"},
	"cli 1.0":  {"json 0.9", "log 1.2"},
	"web 2.0":  {"http 1.4", "json 1.1", "log 1.2"},
	"http 1.4": {"log 1.2"},
	"json 0.9": {},
	"json 1.1": {},
	"log 1.2":  {},
}

var seen = map[string]bool{}

func show(pkg, prefix string) {
	children := deps[pkg]
	for i, child := range children {
		last := i == len(children)-1
		branch, indent := "+-- ", "|   "
		if last {
			branch, indent = "`-- ", "    "
		}
		if seen[child] {
			fmt.Println(prefix + branch + child + " (*)")
			continue
		}
		fmt.Println(prefix + branch + child)
		seen[child] = true
		show(child, prefix+indent)
	}
}

func main() {
	fmt.Println("app")
	show("app", "")
	var transitive []string
	for _, p := range slices.Sorted(maps.Keys(seen)) {
		if !slices.Contains(deps["app"], p) {
			transitive = append(transitive, p)
		}
	}
	fmt.Println("direct:", strings.Join(deps["app"], ", "))
	fmt.Println("transitive:", strings.Join(transitive, ", "))

	users := map[string][]string{}
	for pkg, children := range deps {
		for _, child := range children {
			users[child] = append(users[child], pkg)
		}
	}
	versions := map[string][]string{}
	for _, p := range slices.Sorted(maps.Keys(seen)) {
		name, version, _ := strings.Cut(p, " ")
		versions[name] = append(versions[name], version)
	}
	fmt.Println("needed by more than one package:")
	for _, p := range slices.Sorted(maps.Keys(users)) {
		if len(users[p]) > 1 {
			slices.Sort(users[p])
			fmt.Printf("  %s: %s\n", p, strings.Join(users[p], ", "))
		}
	}
	fmt.Println("more than one version:")
	for _, name := range slices.Sorted(maps.Keys(versions)) {
		if len(versions[name]) > 1 {
			fmt.Printf("  %s: %s\n", name, strings.Join(versions[name], ", "))
		}
	}
}
Output
app
+-- cli 1.0
|   +-- json 0.9
|   `-- log 1.2
`-- web 2.0
    +-- http 1.4
    |   `-- log 1.2 (*)
    +-- json 1.1
    `-- log 1.2 (*)
direct: cli 1.0, web 2.0
transitive: http 1.4, json 0.9, json 1.1, log 1.2
needed by more than one package:
  log 1.2: cli 1.0, http 1.4, web 2.0
more than one version:
  json: 0.9, 1.1
  • Verdict: idiom. A map of slices holds the graph, and a map[string]bool is the set of shown packages.
  • Go map order is random, so slices.Sorted(maps.Keys(...)) sorts the keys before each loop that prints.
  • strings.Cut splits a package into its name and its version at the first space.
  • Nearest version wins. When the tree holds two versions of one artifact, Maven uses the one that is closest to the project. With A -> B -> C -> D 2.0 and A -> E -> D 1.0, Maven uses D 1.0, "because the path from A to D through E is shorter".1
  • A flat graph with rules. NuGet "adds references to a flat package graph" and resolves conflicts ahead of time, which it calls transitive restore.4 When different subgraphs need different versions of one package, NuGet uses "the lowest version that satisfies all version requirements".4
  • One version for each compatible range. Cargo unifies the requirements on a package when one version fits them all. Two exact requirements on different compatible versions, such as =0.4.11 and =0.4.8, are an error. When the requirements allow only versions that are not compatible, such as rand 0.6 and 0.7, "two different versions (e.g. 0.6.5 and 0.7.3) will be resolved and built". The command cargo tree -d shows "duplicate versions and where they come from".5
  • Control by the project. Maven lets a project take charge of transitive dependencies. The dependencyManagement section fixes the version of an artifact wherever it appears in the tree. An exclusion element removes a dependency of a dependency, and a library can mark a dependency as optional, so that its users do not get it.1
  • Every module in go.mod. At go 1.17 or higher, the file go.mod "includes an explicit require directive for each module that provides any package transitively imported by a package or test in the main module".2 This makes the indirect dependencies visible in the project's own file.

Pitfalls

  • Two copies of one type. When two versions of a crate are in the graph, the Rust compiler treats their types as different, "even if they have the same name". Cargo gives the example of a downcast that fails at run time because the value comes from version 1.0.0 and the target type from version 2.0.0.5 The same problem can occur in any language that loads two copies of a library.
  • A downgrade that you did not see. With nearest-wins rules, a deep dependency can get a lower version than it asked for. NuGet warns that its direct-dependency-wins rule "can result in a downgrade of the package version, thus potentially breaking other dependencies in the graph".4
  • Code that uses a transitive dependency directly. If your code imports a package that you get only through another package, the next update of that package can remove it. List each package that your code uses as a direct dependency.
  • Unknown code. Each transitive dependency is code that runs in your build. Look at the full tree, for example with npm ls, which gives "a graphical breakdown of what is installed where".3

Cost

The number of transitive dependencies grows with each level of the graph, and each one costs download time, disk space and review work. Duplicate versions cost more space and, in some languages, larger programs. npm 3 made installs "maximally flat", so that packages are nested only "when two (or more) modules have conflicting dependencies".6

History

npm 3.0.0, released on 26 June 2015, changed the folder layout: "Your dependencies will now be installed maximally flat", and installs are "deduped from the start".6 Maven, Cargo, NuGet and Go each have their own rule for the shared and duplicate packages that a flat graph creates.1542

References

  1. Maven, Introduction to the Dependency Mechanism, Transitive Dependencies
  2. Go Modules Reference, require directive; go directive
  3. npm Docs (v11), folders, More Information; Cycles, Conflicts, and Folder Parsimony; Example
  4. NuGet documentation, NuGet Package Dependency Resolution, Dependency resolution with PackageReference; Dependency resolution rules
  5. The Cargo Book, Dependency Resolution, Resolver algorithm; Version-incompatibility hazards
  6. npm, release v3.0.0, 26 June 2015, Flat, flat, flat!

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/RMVJ63/text.yaml