Ancestors

Finds every vertex that can reach a vertex, such as all the courses one course needs first.

Time complexity O(V+E), gograph function dag.Ancestors.

How it works

Ancestors runs the same search backward. It follows edges in reverse from a vertex and collects every vertex that can reach it. With an edge from A to B read as B depending on A, these are everything the vertex depends on, directly or through others.

A gograph graph doesn't index incoming edges, so dag.Ancestors first reads every edge once to find them, then searches breadth first. It costs O(V+E) and returns the vertices nearest first. The vertex itself is in the result only when it's on a cycle.

Use it to find what has to finish before a job can start, which courses come before another, or why a module is in a build. In go mod graph, an edge goes from a module to one it requires, so the ancestors of a module are the modules that pull it in.

Build pipeline

The jobs of a CI pipeline for a web service, and how many minutes each one takes. Each edge points from a job to a job that waits for it.

A directed graph with 7 vertices and 9 edges.

Which jobs have to finish before the Docker image job can start?

3 vertices can reach Docker image: Checkout, Compile and Install.

Step by step

  1. The graph stores only the edges out of each vertex, so read every edge once, 9 in all, to find the edges into each one.
  2. Start at Docker image. It has edges from Checkout and Compile. Both are new, so they join the queue.
  3. Take Checkout from the queue. It has no edges in.
  4. Take Compile from the queue. It has an edge from Install, which is new, so it joins the queue.
  5. Take Install from the queue. It has an edge from Checkout, which was found before.
  6. Done. 3 vertices can reach Docker image.

Use it in Go

jobs, err := dag.Ancestors(g, "Docker image")
if err != nil {
	return err
}
for _, v := range jobs {
	fmt.Println(v.Label())
}

Example graphs

More in Dependencies

  • Descendants: Finds every vertex reachable from a vertex, such as all the jobs that wait for one step of a build.
  • Affected: Finds the changed vertices and every vertex reachable from them, such as all the cells a spreadsheet edit recomputes.
  • Transitive reduction: Drops every edge that a longer path already implies. Each vertex still reaches the same vertices.
  • Critical path: Finds the longest chain of tasks that wait on each other, which sets how long the whole run takes however many tasks run in parallel.
  • Diff: Compares two graphs and returns the vertices, edges, weights and edge labels that differ, matching vertices by label.

All algorithms