Skip to content
ImagineWorld

Dependency Knowledge Graphs

node_idnode-book_building-knowledge-graphs_chapter-11-dependency-knowledge-graphs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleDependency Knowledge Graphs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Dependency Knowledge Graphs

Section titled “Chapter 11 — Dependency Knowledge Graphs”

What do the following three scenarios have in common?

  • You are trying to come up with the best plan for your project, and you need to understand the dependencies between the different tasks involved. “Task B cannot start before A is completed” means B depends on A. “Task B and task C are both carried out by team member X” means that B and C both depend on X.

  • A vulnerability has been reported on a popular software library. To determine whether your projects are directly affected by the vulnerability, you will have to verify that your code doesn’t directly use that vulnerable library. You also have to check that your chosen libraries don’t use the compromised library themselves.

  • A company owns 25% of the shares in another company, which itself owns part of another and so on. Finding the ultimate beneficial owner (UBO) of a transaction carried out by an institution requires you to traverse the ownership chain. Financial institutions and regulators have to do this when implementing anti-money-laundering or antiterrorism checks or when they try to assess risk in general.

The common theme for each of these, and many more, is dependency modeling. The idea is quite intuitive: each individual direct dependency is modeled as a relationship between nodes that build out into networks of transitive dependencies. These dependency networks form a graph, and many dependency problems can be resolved with graph pattern matching and graph algorithms, as you will learn in this chapter.

Table 11-1 is a common representation of dependencies. Each entry represents an element that directly depends on some other element. These elements might be routers in a network, parts in a supply chain, or tasks in a project, but the way you process those dependencies is identical in all use cases.

Table 11-1. Tabular representation of a set of dependencies

ElementDepends On
AB
AC
AD
CH
DJ
EF
EG
FJ
GL
HI
JN
JM
LM

In this scenario, basic dependency analysis questions like “Is there a hidden dependency between A and F?” can be answered, albeit not entirely conveniently. If you follow the individual dependencies by exploring the table and taking some notes along the way, you will eventually come up with an answer, perhaps even in under a minute: there is no direct or indirect dependency that exists between A and F.

If such a query were based on Table 11-1, it would look something like Example 11-1. Note that the query only goes down two levels in the exploration—that’s why it contains an ellipsis—to indicate that the number of joins would need to be extended for as many levels of depth required in the exploration. In the pathological case of a negative answer like the absence of dependencies between A and F, a valid answer can only be provided when a complete exploration of all possible dependency chains has been carried out, but not before.

Example 11-1. SQL query template returning all recursive dependencies for a given element

SELECT count(*) > 0 dependency_exists
FROM dependencies d
INNER JOIN dependencies d1 ON d.depends_on = d1.elem
INNER JOIN dependencies d2 ON d1.depends_on = d2.elem
-- [...]
WHERE d.elem = 'A' AND d2.elem = 'F'

The approach in Example 11-1 doesn’t work well, even at small scales, because SQL and relational technology weren’t designed for recursive path analysis. But knowledge graphs are designed for arbitrary depth path analysis. The same dataset can be converted into a knowledge graph with the simple script in Example 11-2, where the input file contains a CSV serialization of the data in Table 11-1.

Example 11-2. Cypher script to import the dependencies

LOAD CSV WITH HEADERS FROM "file:///dependencies.csv" AS row
MERGE (a:Element { id: row.element })
MERGE (b:Element { id: row.depends_on})
MERGE (a)-[:DEPENDS_ON]->(b)

The resulting graph is shown in Figure 11-1. Now each entry in Table 11-1 becomes a directed relationship between nodes that indicates a dependency.

Figure 11-1. Dependencies as a graph

With a knowledge graph, answering the exact same question (“Is there a hidden dependency between A and F?”) becomes a trivial task because the dependencies are explicit. A human will need no more than a few seconds to correctly spot that there is no dependency between A and F. A graph database supporting such a knowledge graph does the same thing, just much more quickly and at much greater scale.

The Cypher query in Example 11-3 is a complete, runnable query, as opposed to the abbreviated template used in Example 11-1. It will work for any arbitrary depth in a dependency chain without changes because it’s natively a variable-length expression. The DEPENDS_ON* pattern tells the database to traverse DEPENDS_ON relationships to any depth in a path. In addition to the robustness that this introduces, the pattern-based query is significantly more intuitive and compact. In a software development context, this means lower cost of maintenance.

Example 11-3. Cypher query returning all recursive dependencies for a given element

MATCH path = ( :Element { id: 'A' }) -[ :DEPENDS_ON* ]-> ( :Element { id: 'F' })
RETURN path

Of course, Example 11-3 is a simple query. But the same benefits hold for even complex dependency graphs, as you will learn in the following sections.

Dependencies are sometimes simple. All you care about is whether a dependency exists or not, just like in Table 11-1. But more complex problems require more data, like how critical or expensive a dependency is or how multiple dependencies combine. From a data modeling point of view, the property graph model offers a natural way to represent qualified dependencies by using different types of relationship combined with properties in them.

The diagrams in Figure 11-2 show examples of much richer dependencies. In each, the relationship representing the dependency between two entities is qualified by an attribute that describes the strength of the dependency.

In the case of the company ownership graph, you need to know not only that one company owns a part of another company but also the percentage of ownership. Similarly, in the capacity utilization graph, if a service uses a portion of the capacity provided by another lower-level service, it will be necessary to know that percentage. This is what the capacity and part attributes of the CONSUMES and OWNS relationships encode. The property will typically be an absolute value or a percentage but always a numeric (or worst case, a value from an enumerated list) in a way that multiple values are composable. This is important, as you will see in the following sections, to calculate complex impact propagation or to be able to validate the correctness of a dependency model.

Figure 11-2. Graph with qualified dependencies

Another type of qualifier for a dependency is its temporal validity. This will indicate when the dependency is valid, and therefore, given a date/time, the dependency must be possible to determine whether or not it is active. This case is captured in Figure 11-3 and follows the same modeling approach used to capture the strength of the dependency: properties in the relationships indicating start and end of validity for each dependency.

Figure 11-3. Graph with temporal dependencies

Queries in a historized dependency graph like Figure 11-3 require a timestamp parameter t that will contextualize the query by exploring only the dependencies that were (or will be1) active at time t.

In the examples in Figures 11-2 and 11-3, all dependent entities (or services) have a dependency on a single other entity through a single outgoing relationship. But in the general case, multiple dependencies are commonplace—for example, when an investor spreads their investments around so that their exposure to any one type of asset is limited or when a supply chain creates multiple routes for the transportation of goods for resiliency. Both are shown in Figure 11-4.

Both examples include elements (nodes) that depend on multiple other nodes, but this multidependency can have different interpretations. Is the logic additive? Or is it an at least one type of dependency? These form the two basic interpretations of multidependencies: additive/aggregate or redundant/protection.

Additive dependencies are interpreted as simultaneously active, which means that the dependency is spread over the dependent entities. An element A depends on another element B weighted by B’s contribution to A. In the example on the left side of Figure 11-4, the portfolio is composed of a number of investments in different types of assets. The fact that one asset contributes to the total with a given percentage (say 30%) implies that the portfolio depends on it up to that percentage. In other words, the impact on the portfolio of something happening to that investment (positive or negative) would be weighted (say by 0.3).

In the case of a negative impact (often the main focus in dependency analysis problems), the damage propagated would be limited to that amount. There are other scenarios where this same logic would apply, such as the capacity of a logical communications link that is the result of bonding the capacity of multiple underlying physical links or a virtualized data storage drive backed by multiple underlying physical drives. Again, if any of the dependent elements (links or drives) were to fail, the result would be a degradation to the capacity of the parent element limited to the failing element’s contribution to the total capacity provided by the parent. There may even be a tipping point where the parent element’s provision fails entirely when enough of the capacity of the dependent elements fail.

Figure 11-4. Two examples of use of multidependencies: portfolio asset management and supply chain routing

Impact propagation in the dependency graph under this model is computed recursively following a simple expression at each step along the dependency path:

parent_impact = child1_impact * child1_weight + child2_impact * child2_weight ...

This is visualized in Figure 11-5. The impacts that are measured or detected are introduced in the graph as statements. You will recognize them in the diagram by the magnifying glass icons: a hard drive is down, the value of asset X has dropped by 50%, there is a loss of signal in link X. The derived impacts are shown with their arithmetic underpinnings and a calculator icon. Finally, the impact propagation paths are highlighted with the background shading.

Figure 11-5. Impact propagation in aggregate multidependencies

Redundant dependencies provide fault tolerance. Of all dependent entities in a redundant set, only one is active at any point in time, and the rest are held in reserve until needed. The dependent entity will not be affected as long as at least one of the dependees is available. The consequence is that certain failures will be absorbed by “protection nodes” (those with multiple redundant dependees) and will not be propagated further. These types of situations are common in highly available architectures for software systems where critical servers required to operate 24-7 are protected by other servers that will provide continuity of service if the first one fails.

Something similar happens in broadcast television and communication networks. To guarantee connectivity between two points, multiple alternative routes are created so that in case of failure, one of the remaining alternative pathways is used.

Supply chains work in a similar way with alternative routes used in case of disruption. In Figure 11-4, this is depicted in the diagram on the right-hand side. The preferred route between Singapore and Felixstowe goes through the Suez Canal, but there are alternatives, like the one over the Trans-Siberian Railway.

Energy networks and project plans are yet further examples of scenarios where redundant dependencies are used. These kinds of knowledge graphs have genuinely vast utility.

In all of these scenarios, impact propagation is the key characteristic. It is computed recursively using this expression along the dependency path:

parent_impact = min(child1_impact, child2_impact, ...)

This is visualized in Figure 11-6. Like in Figure 11-5, the stated impacts are highlighted with a magnifying glass icon, derived impacts with their underlying arithmetic and a calculator icon, and the impact propagation paths with background shading.

Figure 11-6. Impact propagation in redundant multidependencies

In more complicated systems, there may be a minimum number of dependent entities for a parent entity to operate. Beyond that threshold, guarantees fail. The underlying principle does not change, but the expression to compute the impact is generalized to reflect the presence of an arbitrary threshold:

parent_impact = 0 if sum((1 - child1_impact), (1 - child2_impact), ...) >= parent_threshold else 1

A good example of this could be a database cluster which, in order to be fully functional, requires a majority of the servers to be available provide a quorum for fault-tolerant udpates. The dependency model looks something like the diagram in Figure 11-7.

Figure 11-7. Multidependencies are required to model a highly available cluster of servers

In the dependency graph, you can see the database management system has a triple dependency on servers 1, 2, and 3, which themselves depend on underlying virtual machines. The threshold is stored in a property in the GraphDB node, which indicates that two out of the three primary servers need to be operational for it to remain available. In the graph, you also see two recommender APIs that depend directly on the GraphDB that provides functionality to the end user, if its underlying dependencies are transitively satisfied (that is, the database and therefore its infrastructure are available). The two interpretations of multidependencies described in this section are the two foundational cases, but you can often find them coexisting in the same dependency graph in real-life systems.

The next step is to be able to analyze a complete dependency graph that includes multidependencies with the two possible interpretations previously described. The dataset (of which an excerpt is shown in Example 11-4) consists of a single file in which every record describes a direct dependency between two elements, its type ('AGG' for aggregate and 'RED' for redundant), and an absolute qualifier.

Example 11-4. CSV file containing the individual direct dependencies forming the graph

elementdepends_onmodeabs
“A”“B”“AGG”“80”
“A”“C”“AGG”“10”
“A”“D”“AGG”“10”
“A”“E”“AGG”“10”
…
“Q”“H”“AGG”“30”

All dependencies are modeled with ()-[:DEPENDS_ON]->() relationships, and the properties mode and abs in them indicate, respectively, the type of relationship and the weight. The complete Cypher script to ingest the dataset from the CSV file in Example 11-4 is presented in Example 11-5.

Example 11-5. Cypher script to load the qualified dependency knowledge graph

WITH "file:///qualified-dependencies.csv" AS data
LOAD CSV WITH HEADERS FROM data AS row
MERGE (a:Element { id: row.element })
MERGE (b:Element { id: row.depends_on})
MERGE (a)-[do:DEPENDS_ON]->(b)
ON CREATE SET do.abs = toInteger(row.abs), do.mode=row.mode

Running Example 11-5 creates a knowledge graph like the one shown in Figure 11-8.

Figure 11-8. Graph combining additive and redundant multidependencies

A generic impact analysis query will take input parameters from the collection of known affected nodes and produce an extended list with the derived impacts (based on the dependency graph) as its result. The most basic type of impact propagation would be the computation of the potential collection of impacted nodes. This analysis is purely topological and returns the list of nodes in the graph for which there exists a direct or indirect dependency (a directed path), given the initial known list of affected nodes. This impact scope analysis is often a first step to detect the subset of nodes to which a more detailed analysis is to be applied. In other words, not all of them will ultimately be impacted, or they will be impacted only partially, given the redundant and aggregate dependencies in the graph. The Cypher for this analysis is shown in Example 11-6.

Example 11-6. Cypher query calculating impact propagation ignoring the semantics and qualifiers of individual dependencies

:param declared => [ "I", "K", "J" ];
MATCH (e:Element)-[:DEPENDS_ON*]->(impacted)
WHERE impacted.id IN $declared
RETURN collect(distinct e.id) AS max_impact_list

The query in Example 11-6 returns the results in Example 11-7, which are depicted visually in Figure 11-9.

Example 11-7. Results returned by the Cypher query calculating the maximum potential impact of a list of failing nodes

{
"max_impact_list": ["H","Q","P","O","N","G","B","A","F"]
}

Once the analysis space has been restricted with the previous query, the semantics of the dependencies (qualifiers, multidependencies, and so on) can be taken into account to provide a detailed impact assessment. The query in Example 11-8 shows the Cypher syntax for impact propagation on dependencies in redundant mode. For practical reasons, the assumption is that the threshold for nodes with redundant multidependencies is 1 and that impact is binary—that is, a node is affected (1) or not affected (0). The parameter $declared contains the input list of impacted nodes.

Example 11-8. Cypher query calculating impact propagation in cases of multiple redundant dependencies

:param declared => [ "I", "K", "J" ];
:param current => "F";
MATCH (e:Element { id: $current})-[d:DEPENDS_ON {mode:"RED"}]->(dependee)
WITH e.id AS element, dependee.id AS dependee,
CASE WHEN dependee.id IN $declared THEN 1 ELSE 0 END AS child_impact
RETURN element, min(child_impact) AS derived_impact

Example 11-9. Results of Cypher query calculating impact propagation in cases of multiple redundant dependencies

elementderived_impact
“F”1

The query in Example 11-10 shows the Cypher syntax for impact propagation on dependencies in aggregate mode. In this case, the impact is augmented with numeric values representing the severity in the input parameters. The data structure used is a map with the ID of the element as key and the numeric representation of the impact to the element between 0 (no impact) and 1 (total impact).

Example 11-10. Cypher query calculating impact propagation in cases of multiple aggregate dependencies

:param declared => { "I": 0.5, "K": 1, "J": 0.33 };
:param current => "G";
MATCH (e:Element { id: $current })-[d:DEPENDS_ON {mode:"AGG"}]->(dependee)
WITH e.id AS element, coalesce($declared[dependee.id], 0) * d.abs AS partial_impact
RETURN element, sum(partial_impact) AS derived_impact

The query returns data like that shown in Example 11-11 as its result.

Example 11-11. Results of Cypher query calculating impact propagation in cases of multiple aggregate dependencies

elementderived_impact
“G”6.600000000000005

These implementations in Cypher of the generic dependency propagation rules can give you a solid foundation for any kind of dependency analysis. They are extensible to the particulars of virtually any dependency modeling scenario.

An important characteristic of a dependency graph model is that it can be easily validated for correctness. A well-formed dependency graph will have to verify a number of conditions that are scenario specific. However, there are three conditions that are generic enough to be commonly used as the foundation atop which specific conditions can be built.

Technically, a dependency graph is a directed acyclic graph (DAG). The presence of a cycle means some component ultimately depends on itself. That is obviously undesirable from a computation point of view but also reflects a bug in the knowledge graph or in the domain itself. The good news is that graphs make structures explicit, and the detection of cycles/loops (and any other shape in your data) is generally as easy as drawing that shape in a query pattern. Example 11-12 is the Cypher query that will detect cycles in a dependency graph. Since a cycle is a path that starts and ends in the same node, the pattern captures any directed path that starts and ends at the same node.

Example 11-12. Cypher query checking correctness of aggregate multidependencies (relative weights)

MATCH cycle = (e:Element)-[d:DEPENDS_ON*]->(e)
RETURN cycle

It’s worth noting that in a large graph this can be an expensive query. That is why you will normally want to:

  • Reduce its scope by restricting it to a portion of the graph, maybe providing a set of nodes as input to run the cycle detection around them (just need to add a filter to the path where e.id in $node_subset).
  • Control the depth of the exploration. The asterisk indicates “path of any arbitrary length” but it is possible to specify a minimum and a maximum with the following notation: ()-[d:DEPENDS_ON*3..45]->().

Validation 2: Aggregate Multidependencies Add Up to the Expected Total

Section titled “Validation 2: Aggregate Multidependencies Add Up to the Expected Total”

This type of validation is important to make sure that the model does not describe anomalous situations. It should ensure, for example, that combined, shareholders comprise exactly 100% of an organization, or a link in an optical transmission network with five 20 Gbps bonded lines is reported as 100 Gbps.

The logic is simple: if the weight of each of the component dependencies in an aggregate set is described in relative terms, then the sum of the weights should be 1 (or 100%). This is what the Cypher query in Example 11-13 captures. If the weight is expressed in absolute terms, then probably the model will include each node’s total aggregate as an attribute, and in that case, the query shown in Example 11-14 applies.

Example 11-13. Cypher query checking correctness of aggregate multidependencies (aggregate weights)

MATCH (e:Element)-[d:DEPENDS_ON { mode:'AGG' }]->()
WITH e, sum(d.rel) AS agg_sum
RETURN e.id AS element_id, agg_sum = 1 AS valid

The query in Example 11-13 simply matches on every generic Element node and returns true if the sum of the rel property in all outgoing DEPENDS_ON relationships is 1.

Example 11-14. Cypher query checking correctness of aggregate multidependencies (absolute weights)

MATCH (e:Element)-[d:DEPENDS_ON { mode:'AGG' }]->()
WITH e, sum(d.abs) AS agg_sum
RETURN e.id AS element_id, agg_sum = e.total AS valid

The query in Example 11-14 applies an identical pattern to the query in Example 11-13, but the sum is calculated on the abs property in all outgoing DEPENDS_ON relationships, and the total is compared against the total property in the element. If these two values match, then the dependencies are well-formed for that node.

Validation 3: Consumption Does Not Exceed Production

Section titled “Validation 3: Consumption Does Not Exceed Production”

Some scenarios are highly dynamic, and dependencies are added and removed frequently. In these situations, maintaining a property with the current aggregate can be costly and a potential source of inconsistencies if the addition or removal of relationships and the update of the capacity are done in separate transactions. When there is no property to store the capacity, the only way to check that the dependency graph is well-formed at any point in time is by checking if incoming and outgoing dependencies are balanced. This is what the Cypher query in Example 11-15 does.

Example 11-15. Cypher query to check the graph has balanced producers and consumers

MATCH (e:Element)
OPTIONAL MATCH ()<-[dependee_agg:DEPENDS_ON { mode:'AGG' }]- (e)
WITH e, sum(dependee_agg.abs) AS agg_sum
OPTIONAL MATCH ()<-[dependee_red:DEPENDS_ON { mode:'RED' }]- (e)
WITH e, agg_sum, coalesce(min(dependee_red.abs),0) AS red_sum
WITH e, agg_sum, red_sum, agg_sum + red_sum AS total_cap WHERE total_cap > 0
MATCH (e)<-[dependent:DEPENDS_ON]-()
WITH e.id AS elem, agg_sum, red_sum, total_cap, sum(dependent.abs) AS used
RETURN elem, agg_sum, red_sum, total_cap, used,
used * 100.0 / total_cap AS percentage_used

When applied to the graph in Figure 11-8, the results shown in Example 11-16 are produced. For each element in the dependency knowledge graph, the incoming and outgoing dependencies will be well-formed if the percentage_used does not go beyond 100%. In addition to the validation for correctness, the report provides business-level guidance to optimize resource utilization.

Example 11-16. Summary of balanced producers and consumers in the dependency graph

elemagg_sumred_sumtotal_capusedpercentage_used
“B”0808080100.0
“H”1200120120100.0
“F”018018016088.888888888889
“G”8008080100.0

Validation 4: Redundant Dependency Configuration Aligns with Threshold Definitions

Section titled “Validation 4: Redundant Dependency Configuration Aligns with Threshold Definitions”

In multidependency scenarios that use redundant dependencies and where thresholds are defined, the number of members in a redundant set has to be, at a minimum, equal to the threshold; otherwise, the dependency would never be satisfied. This is what the query in Example 11-17 verifies.

A good example of this would be a database cluster like the one described by Figure 11-7 where only one PrimaryServer is found. By definition, the threshold of 2 would be impossible to meet, and the GraphDB node would be impacted, and that impact would propagate over the dependency network.

The problems uncovered by the validations can be the result of an actual issue in the environment, like the cluster being incorrectly provisioned, or a problem in the data ingestion and dependency graph construction pipeline. Identifying whether it’s one or the other is required in order to determine subsequent actions.

Example 11-17. Cypher query checking correctness of redundant multidependencies and threshold definitions

MATCH (e:Element)-[d:DEPENDS_ON { mode:'RED'}]->()
WITH e, count(d) AS available_redundant_elements
RETURN e.id AS element_id, available_redundant_elements >= e.threshold AS valid

Multiple additional validations can be run on a dependency knowledge graph. As you have seen, the combination of the graph representation and the expressivity of Cypher makes it straightforward to write pattern-based expressions to detect them.

The impact propagation rules described in “Impact Propagation with Cypher” are combined algorithmically to produce a detailed impact assessment of one or several failing nodes. This is often computed as events are being streamed to the graph for real-time event enrichment. It is useful for filtering and prioritization of large volumes of events over a complex system. But the question arises: which results should be looked at first, and which can be ignored? For example, something has happened in your IT infrastructure, and you want to understand if it’s low priority because you’re protected against it or if it’s high priority because it’s impacting critical services. A dependency knowledge graph can help to solve problems like single-point-of-failure detection for planning purposes and root cause analysis for postmortem improvements. The next two sections look at these in detail.

A single point of failure (SPOF) is a single element on which a whole system depends, and failure of that element results in failure of the system. The principle can be generalized to parts of a dependency knowledge graph. The diagram in Figure 11-7 shows a simple example. In it you can see how two PrimaryServer nodes (Primary2 and Primary3) depend directly on the same CloudVM node (VM2). The obvious consequence is that the GraphDB node (recommender DB) actually has a strong dependency on VM2. This is a common mistake in real life.

If you deploy multiple instances of a fault-tolerant software system on the same hardware, you will be exposed to a major failure if there is a hardware failure. In real life this isn’t limited to virtual machines but can affect all infrastructure, including networks, cooling, power, and even entire data centers. In other words, the level of fault tolerance is superficial because of an underlying SPOF dependency. While this kind of scenario may go unnoticed (and it often does) when systems are designed or when investments are placed, it will not go unnoticed using knowledge graphs.

In topological terms, a SPOF is nothing but another pattern in the graph. As such, you can describe it with a Cypher pattern and surface any instance of it in the dependency knowledge graph.

Example 11-18 shows a generic Cypher expression to detect SPOF situations. Given an element (selected_node_id) in the dependency graph, a SPOF is defined as multiple variable-length dependency chains (paths) that converge on any given element spof.

Example 11-18. Cypher query checking for SPOF patterns

MATCH alertPath = (e:Element)-[:DEPENDS_ON*]->(spof)<-[:DEPENDS_ON*]-(e)
WHERE e.id = $selected_node_id
RETURN alertPath

Not all SPOFs will be fatal. Detailed analysis that takes into account aggregate and redundant multidependencies will be required to determine the ultimate impact in case of failure (and partial failures of a system may be deemed acceptable). But it’s fair to say that SPOFs are generally undesirable patterns that, if not worth solving, should at least be monitored. Think, for example, of an energy network where the geography imposes a particular topology that includes a bottleneck (an SPOF). Even if it’s an unsolvable geographic feature, it’s worth understanding how it impacts the whole network in order to have the right reactive measures in place, like backup diesel generation for critical facilities such as hospitals.

Root cause analysis is the inverse of the impact propagation problem. Given a collection of impacts, the objective is to try to find whether or not they all depend on a single element. If that is proved, the consequence would be that this common ancestor is the root cause of the observable impacts.

A common scenario where this type of analysis is quite prominent is service assurance systems. They normally are built to monitor complex systems and receive continuous alarms/events/metrics from the components in the system. In a complex system (like communications networks, supply chains, IT infrastructure, and so on), components will depend on others in some complex way, as you have seen several times in this chapter. The alarms indicate some kind of malfunctioning in an element. Sometimes the malfunction is inherent to the element, but it can be caused by some dependent element failing and that failure impacting the others. The monitoring system needs to reduce the volume of alarms so that it is high signal/low noise and can direct interventions accurately. One way to do this is to group all derived alarms with their root cause and only present the root causes. This is often referred to as alarm correlation or event correlation, and you can intuit how it involves discovering an alarm’s direct and indirect dependencies.

To create a pattern for root cause analysis, the first step is to identify the candidates. This is what the Cypher query in Example 11-19 does. Given a collection of impacted nodes (the symptoms), the exploration of the dependencies in the graph will identify the leaf nodes that could potentially explain groups within the collection of symptoms. This will uncover disjoint groups. It is possible and often the case that simultaneous although independent faults are detected. This exploration will immediately group independent symptoms in separate clusters.

Example 11-19. Clustering symptoms around potential root causes using Cypher

:param symptoms => ["N", "O", "P", "H", "I", "A", "E"];
MATCH (e:Element)-[:DEPENDS_ON*0..]->(x)
WHERE e.id IN $symptoms
AND NOT (x)-[:DEPENDS_ON]->()
WITH x, collect(distinct e.id) AS explains_faults
WHERE size(explains_faults) > 1
RETURN x.id AS candidate_root, explains_faults
ORDER BY size(explains_faults) DESC

The query in Example 11-19 looks for leaf nodes—those that don’t depend on others, NOT (x)-[:DEPENDS_ON]->(), and can therefore be root causes—in the dependency chain of all symptom nodes. For each of them, the aggregate step collect(distinct e.id) identifies which of the symptoms would be explained by the candidate root cause in question. When run on the graph in Figure 11-8, the query produces the results shown in Example 11-20.

Example 11-20. Result of clustering symptoms around potential root causes using Cypher

candidate_rootcluster
“I”[“H”, “N”, “O”, “P”, “I”]
“K”[“H”, “N”, “O”, “P”, “A”]
“J”[“H”, “N”, “O”, “P”, “A”]
“E”[“E”, “A”]

You can immediately see that there are two independent clusters: the one potentially explained by E and the one potentially explained by I, K, or J.

In a second step, common information retrieval metrics (precision, recall, and F-score) are used to rank and determine which are the more likely ones. The idea is quite intuitive: for each candidate root cause produced in the previous step, three metrics will be calculated:

Precision What portion of the elements in the symptom list does this candidate root cause explain?

Recall Should this be the actual root cause of the problem, what would have been its maximum impact? How does it compare to the actual observation (the initial list of failing nodes)?

F-score (https://oreil.ly/c0y6N) Performance metric calculated from the precision and recall.

These metrics are described in Figure 11-10.

Figure 11-10. Standard information retrieval metrics used in root cause analysis computation

A Cypher implementation using retrieval metrics to refine potential root causes is shown in Example 11-21.

Example 11-21. Complete root cause analysis using Cypher

MATCH (e:Element)-[:DEPENDS_ON*0..]->(x)
WHERE e.id IN $symptoms
AND NOT (x)-[:DEPENDS_ON]->()
WITH x, collect(distinct e.id) AS explains_faults
WHERE size(explains_faults) > 1
WITH x AS candidate_root, explains_faults
MATCH (candidate_root)<-[:DEPENDS_ON*0..]-(x)
WITH candidate_root, explains_faults, collect(distinct x.id) AS potential_max_impact
WITH candidate_root, toFloat(size(explains_faults))/size($symptoms) AS precision,
toFloat(size([x IN potential_max_impact WHERE x IN $symptoms])) / size(potential_max_impact) AS recall
RETURN candidate_root.id, precision, recall,
(2 * precision * recall) / (precision + recall) AS fscore
ORDER BY fscore DESC

The Example 11-21 query extends the code in Example 11-19 by computing the three metrics and produces the results shown in Example 11-22.

Example 11-22. Complete root cause analysis results using Cypher

candidate_root.idprecisionrecallfscore
“I”0.71428571428571430.83333333333333340.7692307692307692
“K”0.71428571428571430.55555555555555560.6250000000000001
“J”0.71428571428571430.50.588235294117647
“E”0.28571428571428571.00.4444444444444445

From Example 11-22, you can infer that the most likely root cause is I based on the collected symptoms. Candidates like I, J, and K have very similar precision, or in other words, they could be the cause of a good portion of the symptoms detected.

However, if J was the root cause, then a significantly higher number of failing nodes should be in the symptom list because they indirectly depend on J and would therefore be affected. The fact that they are not in the input list reduces the likelihood of J being the actual root cause. The same applies to K. Only I has a more balanced combination of precision and recall, which is reflected in its F-score.

You can see that the approach depends on the quality of the observed symptoms. The more complete the list, the more accurate the results. In real-life scenarios, it is uncommon to have a complete picture of the current status of the environment, and the consequence is that the results of these kinds of analysis will always produce a list of most likely candidates rather than a single answer. But those results can be combined with other elements like time or any other domain-specific heuristics to improve your chances of making a correct diagnosis.

Vanguard Group Migrating Monoliths to Microservices

The Vanguard Group is one of the world’s largest investment management companies. It is the largest provider of mutual funds and the second largest provider of exchange-traded funds.

Vanguard was facing the challenge of refactoring its existing monolithic Java-based system into a microservices architecture. For that, the company required visibility into all components in the monolith and, most importantly, the interdependencies between those components. Some of Vanguard’s legacy Java code modules contained up to four million lines of code, making the task absolutely unmanageable without software support. Furthermore, as part of the process, Vanguard wanted to prune dead code to reduce technical debt.

The team understood that they were facing a graph problem, and the scale and complexity of their analytic requirements lent itself to knowledge graphs. They automated the construction of the knowledge graph as part of their build process, adding all their existing code artifacts, along with their dependencies. In addition to the “discovered graph” from the build process, they added information from their architecture diagrams to detect misalignments.

Using graph analytics and visual exploration of the graph, the team now evaluates their code against best practices, and derives key metrics to enforce best practices such as constraining the number of service-to-service calls to reduce risk and latency. Also based on metrics derived from the knowledge graph, a code quality scorecard has been produced, which enables collaboration across the business.

If you are building an embedded system in Rust and using petgraph to manage your dependency knowledge graph, you can implement high-performance impact and root cause analysis natively.

Because petgraph stores nodes and edges in contiguous arrays, recursive path traversals are extremely fast.

Validation 1 (No Cycles) is a critical step for dependency graphs. In petgraph, you can use the petgraph::algo::is_cyclic_directed function to instantly validate your graph.

Example 11-23. Validating a DAG in Rust

use petgraph::graph::DiGraph;
use petgraph::algo::is_cyclic_directed;
pub fn validate_no_cycles(graph: &DiGraph<String, ()>) -> bool {
!is_cyclic_directed(graph)
}

To perform Root Cause Analysis in Rust, you need to traverse from your symptom nodes down to the leaf nodes (nodes with no outgoing dependencies).

Example 11-24. Finding candidate root causes in petgraph

use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::Direction;
use petgraph::visit::Dfs;
use std::collections::{HashSet, HashMap};
pub fn find_root_causes(
graph: &DiGraph<String, ()>,
symptoms: Vec<NodeIndex>
) -> HashMap<NodeIndex, HashSet<NodeIndex>> {
// Maps a candidate root cause to the symptoms it explains
let mut candidate_roots: HashMap<NodeIndex, HashSet<NodeIndex>> = HashMap::new();
for symptom in symptoms {
let mut dfs = Dfs::new(graph, symptom);
while let Some(nx) = dfs.next(graph) {
// A node is a leaf (potential root cause) if it has no OUTGOING dependencies
let has_dependencies = graph.neighbors_directed(nx, Direction::Outgoing).count() > 0;
if !has_dependencies {
candidate_roots
.entry(nx)
.or_insert_with(HashSet::new)
.insert(symptom);
}
}
}
// Filter out candidates that only explain 1 symptom, matching the Cypher logic
candidate_roots.retain(|_, explained_symptoms| explains_symptoms.len() > 1);
candidate_roots
}

This Rust implementation mirrors the MATCH (e:Element)-[:DEPENDS_ON*0..]->(x) WHERE NOT (x)-[:DEPENDS_ON]->() logic from Cypher. By running this over an in-memory petgraph, you can process thousands of incoming alarms per second, grouping them by root cause before alerting a human operator.

Capturing and exploiting dependencies is a common and important capability. The natural way to represent and process dependencies is to use dependency-centric knowledge graphs because of their expressive power, intuitiveness, and efficiency.

The ideas in this chapter show the basic principles of building dependency-centric knowledge graphs to solve complex problems like impact analysis and root cause analysis. The examples provided also give you an idea of broad applicability of these graphs and will help you extrapolate these principles to your own use cases. From here, you can readily apply and extend these techniques to meet your own needs.


  1. Nothing stops you from capturing how the future will look in the dependency knowledge graph. Think of a reservation application where users can book resources in advance. ↩