• Stars
    star
    408
  • Rank 105,946 (Top 3 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 1 year ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PyRCA: A Python Machine Learning Library for Root Cause Analysis

PyRCA: A Python library for Root Cause Analysis

Table of Contents

  1. Introduction
  2. Installation
  3. Getting Started
  4. Documentation
  5. Tutorial
  6. Example
  7. Benchmarks
  8. How to Contribute

Introduction

The adoption of microservices architectures is growing at a rapid pace, making multi-service applications the standard paradigm in real-world IT applications. Typically, a multi-service application consists of hundreds of interacting services, making it increasingly challenging to detect service failures and identify their root causes. Root cause analysis (RCA) methods typically rely on KPI metrics, traces, or logs monitored on these services to determine the root causes when a system failure is detected. Such methods can aid engineers and SREs in the troubleshooting process.

PyRCA is a Python machine-learning library designed to facilitate root cause analysis by offering various state-of-the-art RCA algorithms and an end-to-end pipeline for building RCA solutions. At present, PyRCA primarily focuses on metric-based RCA, including two types of algorithms: (1) identifying anomalous metrics in parallel with the observed anomaly through metric data analysis, such as Ξ΅-diagnosis, and (2) identifying root causes based on a topology/causal graph representing the causal relationships between the observed metrics, such as Bayesian inference and Random Walk. PyRCA also provides a convenient tool for building causal graphs from the observed time series data and domain knowledge, enabling users to develop graph-based solutions quickly. Furthermore, PyRCA offers a benchmark for evaluating various RCA methods, which is valuable for industry and academic research.

The following list shows the supported RCA methods in our library:

  1. Ξ΅-Diagnosis
  2. Bayesian Inference-based RCA (BI)
  3. Random Walk-based RCA (RW)
  4. Root Cause Discovery method (RCD)
  5. Hypothesis Testing-based RCA (HT)

We will continue improving this library to make it more comprehensive in the future. In the future, PyRCA will support trace and log-based RCA methods as well.

Installation

You can install pyrca from PyPI by calling pip install sfr-pyrca. You may install from source by cloning the PyRCA repo, navigating to the root directory, and calling pip install ., or pip install -e . to install in editable mode. You may install additional dependencies:

  • For plotting & visualization: Calling pip install sfr-pyrca[plot], or pip install .[plot] from the root directory of the repo.
  • Install all the dependencies: Calling pip install sfr-pyrca[all], or pip install .[all] from the root directory of the repo.

Getting Started

PyRCA provides a unified interface for training RCA models and finding root causes. To apply a certain RCA method, you only need to specify:

  • The selected RCA method: e.g., BayesianNetwork, EpsilonDiagnosis.
  • The method configuration: e.g., BayesianNetworkConfig, EpsilonDiagnosisConfig.
  • Time series data for initialization/training: e.g., A time series data in a pandas dataframe.
  • Abnormal time series data in an incident window: The RCA methods require the anomalous KPI metrics in an incident window.

Let's take BayesianNetwork as an example. Suppose that graph_df is the pandas dataframe of a graph representing the causal relationships between metrics (how to construct such causal graph will be discussed later), and df is the pandas dataframe containing the historical observed time series data (e.g., the index is the timestamp and each column represents one monitored metric). To train a BayesianNetwork, you can simply run the following code:

from pyrca.analyzers.bayesian import BayesianNetwork
model = BayesianNetwork(config=BayesianNetwork.config_class(graph=graph_df))
model.train(df)
model.save("model_folder")

After the model is trained, you can use it to find root causes of an incident given a list of anomalous metrics detected by a certain anomaly detector (you can use the stats-based detector supported in PyRCA or other anomaly detection methods supported by our Merlion library), e.g.,

from pyrca.analyzers.bayesian import BayesianNetwork
model = BayesianNetwork.load("model_folder")
results = model.find_root_causes(["observed_anomalous_metric", ...])
print(results.to_dict())

For other RCA methods, you can write similar code as above for finding root causes. For example, if you want to try EpsilonDiagnosis, you can initalize EpsilonDiagnosis as follows:

from pyrca.analyzers.epsilon_diagnosis import EpsilonDiagnosis
model = EpsilonDiagnosis(config=EpsilonDiagnosis.config_class(alpha=0.01))
model.train(normal_data)

Here normal_data is the historically observed time series data without anomalies. To identify root causes, you can run:

results = model.find_root_causes(abnormal_data)
print(results.to_dict())

where abnormal_data is the time series data collected in an incident window.

As mentioned above, some RCA methods such as BayesianNetwork require causal graphs as their inputs. To construct such causal graphs from the observed time series data, you can utilize our tool by running python -m pyrca.tools. This command will launch a Dash app for time series data analysis and causal discovery. alt text

The dashboard enables users to experiment with different causal discovery methods, customize causal discovery parameters, add domain knowledge constraints (e.g., root/leaf nodes, forbidden/required links), and visualize the generated causal graphs. This feature simplifies the process of manually revising causal graphs based on domain knowledge. Users can download the graph generated by this tool if they are satisfied with it. The graph can then be used by the RCA methods supported in PyRCA.

Alternatively, users can write code to build such graphs instead of using the dashboard. The package pyrca.graphs.causal includes several popular causal discovery methods that users can leverage. All of these methods support domain knowledge constraints. For instance, if users wish to apply the PC algorithm for building causal graphs on the observed time series data df, the following code can be used:

from pyrca.graphs.causal.pc import PC
model = PC(PC.config_class())
graph_df = model.train(df)

If you have some domain knowledge constraints, you may run:

from pyrca.graphs.causal.pc import PC
model = PC(PC.config_class(domain_knowledge_file="file_path"))
graph_df = model.train(df)

The domain knowledge file has a YAML format, e.g.,

causal-graph:
  root-nodes: ["A", "B"]
  leaf-nodes: ["E", "F"]
  forbids:
    - ["A", "E"]
  requires: 
    - ["A", "C"]

This domain knowledge file states that:

  1. Metrics A and B must the root nodes,
  2. Metrics E and F must be the leaf nodes,
  3. There is no connection from A to E, and
  4. There is a connection from A to C.

You can write your domain knowledge file based on this template for generating more reliable causal graphs.

Application Example

Here is a real-world example of applying BayesianNetwork to build a solution for RCA, which is adapted from our internal use cases. The "config" folder includes the settings for the stats-based anomaly detector and the domain knowledge. The "models" folder stores the causal graph and the trained Bayesian network. The RCAEngine class in the "rca.py" file implements the methods for building causal graphs, training Bayesian networks and finding root causes by utilizing the modules provided by PyRCA. You can directly use this class if the stats-based anomaly detector and Bayesian inference are suitable for your problems. For example, given a time series dataframe df, you can build and train a Bayesian network via the following code:

from pyrca.applications.example.rca import RCAEngine
engine = RCAEngine()
engine.build_causal_graph(
    df=df,
    run_pdag2dag=True,
    max_num_points=5000000,
    verbose=True
)
bn = engine.train_bayesian_network(dfs=[df])
bn.print_probabilities()

After the Bayesian network is constructed, you can use it directly for finding root causes:

engine = RCAEngine()
result = engine.find_root_causes_bn(anomalies=["conn_pool", "apt"])
pprint.pprint(result)

The inputs of find_root_causes_bn is a list of the anomalous metrics detected by the stats-based anomaly detector. This method will estimate the probability of a node being a root cause and extract the paths from a potential root cause node to the leaf nodes.

Benchmarks

The following table summarizes the RCA performance of different methods on the simulated dataset. How to generate the simulated dataset can be found here, and how to test different RCA methods can be found here.

Recall@1 Recall@3 Recall@5
Ξ΅-Diagnosis 0.06 Β± 0.02 0.16 Β± 0.04 0.16 Β± 0.04
RCD 0.28 Β± 0.05 0.29 Β± 0.05 0.30 Β± 0.05
Local-RCD 0.44 Β± 0.05 0.70 Β± 0.05 0.70 Β± 0.05
Random Walk 0.07 Β± 0.03 0.20 Β± 0.04 0.24 Β± 0.04
Random Walk (PC) 0.06 Β± 0.02 0.17 Β± 0.04 0.21 Β± 0.04
Bayesian Inference 0.15 Β± 0.04 0.35 Β± 0.05 0.43 Β± 0.05
Bayesian Inference (PC) 0.11 Β± 0.03 0.30 Β± 0.05 0.40 Β± 0.05
Hypothesis-testing 1.00 Β± 0.00 1.00 Β± 0.00 1.00 Β± 0.00
Hypothesis-testing (PC) 0.95 Β± 0.02 1.00 Β± 0.00 1.00 Β± 0.00
Hypothesis-testing (ADJ) 0.95 Β± 0.02 1.00 Β± 0.00 1.00 Β± 0.00
Hypothesis-testing (ADJ-PC) 0.77 Β± 0.04 0.92 Β± 0.03 0.92 Β± 0.03

Ξ΅-Diagnosis and RCD are one-phase RCA methods, while the rest methods are two-phase RCA methods. Local-RCD denotes the RCD algorithm with localized learning. The Bayesian Inference algorithm computes the root cause scores by estimating each structural causal model. Hypothesis-testing (ADJ) denotes the hypothesis-testing algorithm with descendant adjustment. For the two-phase models, the algorithms without suffix indicate that the root cause localization algorithm use the true causal graph for model training. The algorithms with suffix "PC" indicate the causal graph is estimated via PC algorithm.

How to Contribute

We welcome the contribution from the open-source community to improve the library! Before you get started, clone this repo, run pip install pre-commit, and run pre-commit install from the root directory of the repo. This will ensure all files are formatted correctly and contain the appropriate license headers whenever you make a commit.

To add a new RCA method into the library, you may follow the steps below:

  1. Create a new python script file for this RCA method in the pyrca/analyzers folder.
  2. Create the configuration class inheriting from pyrca.base.BaseConfig.
  3. Create the method class inheriting from pyrca.analyzers.base.BaseRCA. The constructor for the new method takes the new configuration instance as its input.
  4. Implement the train function that trains or initializes the new method.
  5. Implement the find_root_causes function that returns a pyrca.analyzers.base.RCAResults instance for root cause analysis results.

To add a new causal discovery method, you may follow the following steps:

  1. Create a new python script file for this RCA method in the pyrca/graphs/causal folder.
  2. Create the configuration class that inherits from pyrca.graphs.causal.base.CausalModelConfig.
  3. Create the method class that inherits from pyrca.graphs.causal.base.CausalModel. The constructor for the new method takes the new configuration instance as its input.
  4. Implement the _train function that returns the discovered casual graph. The input parameters of _train are the time series dataframe, the lists of forbidden and required links, and other additional parameters.

Contact Us

If you have any questions, comments or suggestions, please do not hesitate to contact us at [email protected].

License

BSD 3-Clause License

More Repositories

1

LAVIS

LAVIS - A One-stop Library for Language-Vision Intelligence
Jupyter Notebook
9,587
star
2

CodeGen

CodeGen is a family of open-source model for program synthesis. Trained on TPU-v4. Competitive with OpenAI Codex.
Python
4,594
star
3

BLIP

PyTorch code for BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation
Jupyter Notebook
3,879
star
4

akita

πŸš€ State Management Tailored-Made for JS Applications
TypeScript
3,442
star
5

Merlion

Merlion: A Machine Learning Framework for Time Series Intelligence
Python
3,355
star
6

ja3

JA3 is a standard for creating SSL client fingerprints in an easy to produce and shareable way.
Python
2,666
star
7

CodeT5

Home of CodeT5: Open Code LLMs for Code Understanding and Generation
Python
2,437
star
8

decaNLP

The Natural Language Decathlon: A Multitask Challenge for NLP
Python
2,301
star
9

TransmogrifAI

TransmogrifAI (pronounced trΔƒns-mŏgˈrΙ™-fΔ«) is an AutoML library for building modular, reusable, strongly typed machine learning workflows on Apache Spark with minimal hand-tuning
Scala
2,234
star
10

policy_sentry

IAM Least Privilege Policy Generator
Python
1,986
star
11

cloudsplaining

Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report.
JavaScript
1,972
star
12

awd-lstm-lm

LSTM and QRNN Language Model Toolkit for PyTorch
Python
1,900
star
13

ctrl

Conditional Transformer Language Model for Controllable Generation
Python
1,766
star
14

lwc

⚑️ LWC - A Blazing Fast, Enterprise-Grade Web Components Foundation
JavaScript
1,619
star
15

WikiSQL

A large annotated semantic parsing corpus for developing natural language interfaces.
HTML
1,606
star
16

sloop

Kubernetes History Visualization
Go
1,457
star
17

CodeTF

CodeTF: One-stop Transformer Library for State-of-the-art Code LLM
Python
1,375
star
18

ALBEF

Code for ALBEF: a new vision-language pre-training method
Python
1,276
star
19

pytorch-qrnn

PyTorch implementation of the Quasi-Recurrent Neural Network - up to 16 times faster than NVIDIA's cuDNN LSTM
Python
1,255
star
20

ai-economist

Foundation is a flexible, modular, and composable framework to model socio-economic behaviors and dynamics with both agents and governments. This framework can be used in conjunction with reinforcement learning to learn optimal economic policies,Β as done by the AI Economist (https://www.einstein.ai/the-ai-economist).
Python
964
star
21

design-system-react

Salesforce Lightning Design System for React
JavaScript
919
star
22

jarm

Python
914
star
23

tough-cookie

RFC6265 Cookies and CookieJar for Node.js
TypeScript
858
star
24

OmniXAI

OmniXAI: A Library for eXplainable AI
Jupyter Notebook
853
star
25

reactive-grpc

Reactive stubs for gRPC
Java
826
star
26

xgen

Salesforce open-source LLMs with 8k sequence length.
Python
717
star
27

UniControl

Unified Controllable Visual Generation Model
Python
614
star
28

vulnreport

Open-source pentesting management and automation platform by Salesforce Product Security
HTML
593
star
29

hassh

HASSH is a network fingerprinting standard which can be used to identify specific Client and Server SSH implementations. The fingerprints can be easily stored, searched and shared in the form of a small MD5 fingerprint.
Python
529
star
30

progen

Official release of the ProGen models
Python
518
star
31

base-components-recipes

A collection of base component recipes for Lightning Web Components on Salesforce Platform
JavaScript
509
star
32

Argus

Time series monitoring and alerting platform.
Java
501
star
33

CodeRL

This is the official code for the paper CodeRL: Mastering Code Generation through Pretrained Models and Deep Reinforcement Learning (NeurIPS22).
Python
488
star
34

matchbox

Write PyTorch code at the level of individual examples, then run it efficiently on minibatches.
Python
488
star
35

PCL

PyTorch code for "Prototypical Contrastive Learning of Unsupervised Representations"
Python
483
star
36

DialogStudio

DialogStudio: Towards Richest and Most Diverse Unified Dataset Collection and Instruction-Aware Models for Conversational AI
Python
472
star
37

cove

Python
470
star
38

warp-drive

Extremely Fast End-to-End Deep Multi-Agent Reinforcement Learning Framework on a GPU (JMLR 2022)
Python
452
star
39

observable-membrane

A Javascript Membrane implementation using Proxies to observe mutation on an object graph
TypeScript
368
star
40

DeepTime

PyTorch code for Learning Deep Time-index Models for Time Series Forecasting (ICML 2023)
Python
351
star
41

ULIP

Python
316
star
42

MultiHopKG

Multi-hop knowledge graph reasoning learned via policy gradient with reward shaping and action dropout
Jupyter Notebook
300
star
43

logai

LogAI - An open-source library for log analytics and intelligence
Python
298
star
44

CodeGen2

CodeGen2 models for program synthesis
Python
272
star
45

provis

Official code repository of "BERTology Meets Biology: Interpreting Attention in Protein Language Models."
Python
269
star
46

causalai

Salesforce CausalAI Library: A Fast and Scalable framework for Causal Analysis of Time Series and Tabular Data
Jupyter Notebook
256
star
47

jaxformer

Minimal library to train LLMs on TPU in JAX with pjit().
Python
255
star
48

EDICT

Jupyter Notebook
247
star
49

rules_spring

Bazel rule for building Spring Boot apps as a deployable jar
Starlark
224
star
50

ETSformer

PyTorch code for ETSformer: Exponential Smoothing Transformers for Time-series Forecasting
Python
221
star
51

TabularSemanticParsing

Translating natural language questions to a structured query language
Jupyter Notebook
220
star
52

themify

πŸ‘¨β€πŸŽ¨ CSS Themes Made Easy. A robust, opinionated solution to manage themes in your web application
TypeScript
216
star
53

simpletod

Official repository for "SimpleTOD: A Simple Language Model for Task-Oriented Dialogue"
Python
212
star
54

grpc-java-contrib

Useful extensions for the grpc-java library
Java
208
star
55

GeDi

GeDi: Generative Discriminator Guided Sequence Generation
Python
207
star
56

aws-allowlister

Automatically compile an AWS Service Control Policy that ONLY allows AWS services that are compliant with your preferred compliance frameworks.
Python
207
star
57

generic-sidecar-injector

A generic framework for injecting sidecars and related configuration in Kubernetes using Mutating Webhook Admission Controllers
Go
203
star
58

mirus

Mirus is a cross data-center data replication tool for Apache Kafka
Java
201
star
59

CoST

PyTorch code for CoST: Contrastive Learning of Disentangled Seasonal-Trend Representations for Time Series Forecasting (ICLR 2022)
Python
196
star
60

factCC

Resources for the "Evaluating the Factual Consistency of Abstractive Text Summarization" paper
Python
192
star
61

runway-browser

Interactive visualization framework for Runway models of distributed systems
JavaScript
188
star
62

glad

Global-Locally Self-Attentive Dialogue State Tracker
Python
186
star
63

cloud-guardrails

Rapidly apply hundreds of security controls in Azure
HCL
181
star
64

ALPRO

Align and Prompt: Video-and-Language Pre-training with Entity Prompts
Python
177
star
65

densecap

Jupyter Notebook
176
star
66

kafka-junit

This library wraps Kafka's embedded test cluster, allowing you to more easily create and run integration tests using JUnit against a "real" kafka server running within the context of your tests. No need to stand up an external kafka cluster!
Java
167
star
67

booksum

Python
167
star
68

sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
JavaScript
162
star
69

hierarchicalContrastiveLearning

Python
149
star
70

ctrl-sum

Resources for the "CTRLsum: Towards Generic Controllable Text Summarization" paper
Python
146
star
71

cos-e

Commonsense Explanations Dataset and Code
Python
144
star
72

secure-filters

Anti-XSS Security Filters for EJS and More
JavaScript
138
star
73

metabadger

Prevent SSRF attacks on AWS EC2 via automated upgrades to the more secure Instance Metadata Service v2 (IMDSv2).
Python
129
star
74

dockerfile-image-update

A tool that helps you get security patches for Docker images into production as quickly as possible without breaking things
Java
127
star
75

Converse

Python
125
star
76

refocus

The Go-To Platform for Visualizing Service Health
JavaScript
125
star
77

CoMatch

Code for CoMatch: Semi-supervised Learning with Contrastive Graph Regularization
Python
117
star
78

BOLAA

Python
114
star
79

fsnet

Python
111
star
80

rng-kbqa

Python
110
star
81

near-membrane

JavaScript Near Membrane Library that powers Lightning Locker Service
TypeScript
110
star
82

botsim

BotSIM - a data-efficient end-to-end Bot SIMulation toolkit for evaluation, diagnosis, and improvement of commercial chatbots
Jupyter Notebook
108
star
83

bazel-eclipse

This repo holds two IDE projects. One is the Eclipse Feature for developing Bazel projects in Eclipse. The Bazel Eclipse Feature supports importing, building, and testing Java projects that are built using the Bazel build system. The other is the Bazel Java Language Server, which is a build integration for IDEs such as VS Code.
Java
108
star
84

MUST

PyTorch code for MUST
Python
103
star
85

bro-sysmon

How to Zeek Sysmon Logs!
Zeek
100
star
86

Timbermill

A better logging service
Java
99
star
87

AuditNLG

AuditNLG: Auditing Generative AI Language Modeling for Trustworthiness
Python
97
star
88

eslint-plugin-lwc

Official ESLint rules for LWC
JavaScript
96
star
89

best

πŸ† Delightful Benchmarking & Performance Testing
TypeScript
95
star
90

craft

CRAFT removes the language barrier to create Kubernetes Operators.
Go
93
star
91

eslint-config-lwc

Opinionated ESLint configurations for LWC projects
JavaScript
93
star
92

online_conformal

Methods for online conformal prediction.
Jupyter Notebook
90
star
93

lobster-pot

Scans every git push to your Github organisations to find unwanted secrets.
Go
88
star
94

ml4ir

Machine Learning for Information Retrieval
Jupyter Notebook
85
star
95

violet-conversations

Sophisticated Conversational Applications/Bots
JavaScript
84
star
96

apex-mockery

Lightweight mocking library in Apex
Apex
83
star
97

fast-influence-functions

Python
83
star
98

MoPro

MoPro: Webly Supervised Learning
Python
79
star
99

TaiChi

Open source library for few shot NLP
Python
79
star
100

helm-starter-istio

An Istio starter template for Helm
Shell
78
star