1. Understand the Goal: The user wants to build a "Test Impact Analysis" (TIA) system specifically designed for "monorepos" that utilize "change graphs".
Monorepo: A single repository containing multiple distinct projects (libraries, services, apps) with interdependencies.
Change Graph: A representation of the dependency relationships (files/packages/modules) within the codebase.
Test Impact Analysis (TIA): The process of identifying which tests need to run based on specific code changes to optimize the testing pipeline (avoid running the whole suite every time).
2. Key Components of a TIA System:
Input: The Git Diff (what changed?).
The Graph: The structure representing dependencies (A depends on B). This needs to handle both static dependencies (imports) and dynamic dependencies (test coverage data).
The Algorithm: Traversing the graph to find impacted nodes and mapping those nodes to specific tests.
The Output: A list of test targets (e.g., specific test files, Jest test patterns, Bazel targets).
Implementation/Tools: How to actually build this (languages, CI integration).
3. Structuring the Solution:
I should organize this as a comprehensive guide or blueprint for building such a system.
Phase 1: Conceptual Model (The "Why" and "What")
Define the Graph (Nodes = Files/Modules, Edges = Dependencies).
Distinguish between Build Dependency Graph (static imports) and Test Coverage Graph (runtime execution). Self-correction: For a robust system, you usually need both. Static for "safe" approximation, Coverage for precise optimization.
Phase 2: The Architecture (The "How")
Dependency Extraction: How to get the graph? (AST parsing, Language Server Protocol, Build system artifacts like Bazel/Nx/Turborepo).
Change Detection: Git diffing.
Graph Traversal: The core logic.
Test Selection: Mapping impacted code to tests.
Phase 3: The Algorithm (Step-by-Step Logic)
Step 1: Get changed files.
Step 2: Find consumers (reverse traversal).
Step 3: Find associated tests.
Phase 4: Implementation Example (Pseudo-code/Python)
Create a simple graph class.
Simulate the traversal.
This makes it concrete.
Phase 5: Advanced Considerations (The "Gotchas")
Dynamic analysis (code coverage).
Hermetic builds.
Flaky tests.
Language support (Polyglot monorepos).
Phase 6: Existing Tools vs. Custom Build
Mention Nx, Turborepo, Bazel, Gradle as alternatives to building from scratch.
4. Deep Dive into Specifics:
The "Change Graph" aspect:
If file A changes, and file B imports A, B is impacted.
If Test T tests B, does T need to run? Yes.
Crucial distinction:Reverse Dependency Traversal. We don't care what we depend on (downstream); we care who depends on us (upstream/consumers).
Static vs. Dynamic:
Static: "Safe but slow." If I change a utils file, I run tests for everything that imports it. This often leads to running too many tests.
Dynamic (Coverage): "Fast but risky." I only run tests that actually executed the lines I changed. This requires collecting coverage data continuously.
Recommendation: Start with Static (Reverse Dependency) as it's safer and easier to implement. Mention Dynamic as an optimization.
5. Drafting the Content (Iterative refinement):
Intro: Define TIA in the context of monorepos.
The Graph: Explain the Directed Acyclic Graph (DAG).
Logic:
Changed Files -> Reverse Deps -> Test Targets.
The Python Example: I'll create a DependencyGraph class with methods add_edge and get_reverse_deps.
CI Integration: How does this fit into GitHub Actions/Jenkins?
Compute diff.
Run TIA script.
Output list of tests.
Run those tests.
6. Refinement on "Change Graphs":
The prompt specifically mentions "change graphs". This usually implies a persistent graph structure that is updated incrementally, rather than regenerated every time.
Idea: Store the graph in a database (Neo4j, RedisGraph, or just JSON) and update it on every merge to main.
7. Final Polish:
Ensure the tone is technical and architectural. Use formatting (bolding, code blocks) for readability. Add a section on "Why build vs. buy" because this is a hard problem to get right from scratch.
(Self-Correction during drafting): I initially thought about focusing heavily on Code Coverage, but for a "monorepo change graph" request, the structural dependency (Build Graph) is usually the foundation. I will focus on the Reverse Dependency (Reverse Topological Order) approach as the primary solution, then add Code Coverage as "Level 2" optimization.
8. Output Structure:
High-Level Architecture: The flow.
The Graph Data Model: Nodes and Edges.
The Algorithm: Reverse Traversal.
Implementation (Python Example): Concrete code.
Dynamic Analysis (Coverage): The "Smart" layer.
CI/CD Integration: Practical application.
Existing Ecosystem: Tools.
Let's generate the response based on this plan.
Building a Test Impact Analysis (TIA) system for a monorepo requires shifting from "run everything" to "run the minimum necessary."
In a monorepo, dependencies form a complex Directed Acyclic Graph (DAG). A change in a low-level library might ripple up through dozens of applications. A robust TIA system uses this graph to determine exactly which tests are affected by a code change.
Here is a comprehensive blueprint for building this system.
1. The High-Level Architecture
The system consists of three main components:
The Dependency Graph: A map of how files/packages relate to one another (Build-time).
The Change Set: The list of files modified in the current commit (Git diff).
The Traversal Engine: The logic that walks the graph to find impacted nodes.
2. The Data Model (The Graph)
You must construct a graph where nodes represent units of code and edges represent dependencies. You have two choices for granularity: File-level or Package-level.
File-level: High precision. Good for languages with first-class module systems (Go, Rust, Java, TypeScript).
Package-level: Easier to maintain. Good for loosely coupled polyglot repos.
The Node Structure
Every node needs metadata:
ID: Path (libs/auth/login.ts) or Package Name (@org/auth).
Type:library, application, or test.
Tags: For filtering (e.g., tech:react, tier:backend).
The Edges
Static Dependency:A imports B.
Implicit Dependency:Dockerfile builds App A (The Dockerfile depends on the App).
Test Association:Test File T covers Source File S.
3. The Algorithm
The core logic relies on Reverse Graph Traversal.
If you change a file X, you must find all files that depend on X (Consumers), and then find all tests associated with those Consumers.
The 4-Step Logic Flow
Identify Changed Files: Use Git to find the diff.
Resolve Graph Nodes: Map file paths to Graph IDs.
Find Impacted Consumers (Reverse Traversal):
If lib/A changes...
And app/B imports lib/A...
Then app/B is impacted.
Select Tests:
Find tests directly touching the changed files.
Find tests touching the impacted consumers.
4. Implementation Guide (Python Prototype)
Here is a simplified implementation using Python and the networkx library to demonstrate the graph traversal logic.
python
import networkx as nx
class MonorepoGraph:
def __init__(self):
# Directed Graph: An edge A -> B means "A depends on B"
self.graph = nx.DiGraph()
# A mapping of which test file covers which source file
# Format: { source_file: [test_file_1, test_file_2] }
self.test_coverage_map = {}
def add_dependency(self, dependent, dependency):
"""
dependent: The file doing the importing (Child)
dependency: The file being imported (Parent)
"""
self.graph.add_edge(dependent, dependency)
def map_test(self, test_file, source_file):
if source_file not in self.test_coverage_map:
self.test_coverage_map[source_file] = []
self.test_coverage_map[source_file].append(test_file)
def get_impacted_tests(self, changed_files):
"""
The core TIA algorithm.
"""
impacted_tests = set()
for file in changed_files:
# 1. Direct Tests: Find tests that cover this specific file
if file in self.test_coverage_map:
for test in self.test_coverage_map[file]:
impacted_tests.add(test)
# 2. Dependent Tests: Find files that depend on this file
# Note: In networkx, descendants are "downstream" (dependents)
# if edge direction is (Child -> Parent).
# We use predecessors if edge is (Parent -> Child).
# Let's assume edge direction: (Child -> Parent)
# We need to find all nodes that have 'file' as a dependency.
# This is effectively a Reverse BFS (Breadth-First Search).
try:
# Get all nodes that depend on 'file' (directly or indirectly)
dependents = nx.descendants(self.graph, file)
for dependent in dependents:
# Find tests for these dependents
if dependent in self.test_coverage_map:
for test in self.test_coverage_map[dependent]:
impacted_tests.add(test)
except nx.NetworkXError:
# Node not in graph
continue
return list(impacted_tests)
# --- Usage Example ---
tia = MonorepoGraph()
# Define Structure: App -> Lib -> Util
tia.add_dependency("apps/web/app.ts", "libs/auth/lib.ts")
tia.add_dependency("libs/auth/lib.ts", "libs/utils/hash.ts")
# Define Tests
tia.map_test("apps/web/app.test.ts", "apps/web/app.ts")
tia.map_test("libs/auth/lib.test.ts", "libs/auth/lib.ts")
tia.map_test("libs/utils/hash.test.ts", "libs/utils/hash.ts")
# Scenario: A developer changes 'libs/utils/hash.ts'
changed_files = ["libs/utils/hash.ts"]
tests_to_run = tia.get_impacted_tests(changed_files)
print(f"Tests to run: {tests_to_run}")
# Output should include tests for hash.ts, auth/lib.ts, AND web/app.ts
# Because the change bubbled up from the bottom of the tree.
5. Levels of Sophistication
There are two levels of TIA you can implement. The example above is Static Analysis.
Level 1: Static Analysis (Safe & Standard)
How it works: Parses import statements (AST) or build manifests (package.json, BUILD.bazel, go.mod).
Pros: Deterministic, runs fast locally, no runtime overhead.
Cons: Conservative. It assumes that if you import a file, you might be broken by a change, even if you only use one function that didn't change.
Level 2: Dynamic Analysis (Runtime Coverage)
How it works: You run your tests with a coverage agent (Istanbul, JaCoCo, gcov). You store a database mapping specific lines of code executed by specific tests.
Pros: Extremely precise. If you change a logging utility function, you only run the tests for the logging utility, not the entire app that imports it.
Cons: Complex infrastructure. You must merge coverage reports from CI runs to build the "coverage matrix."
6. CI/CD Integration Strategy
To make this useful, it must integrate into your pipeline.
The "Base Commit" Problem
In a Monorepo, you usually compare against origin/main. However, if you have long-running branches, you might need to compare against the "merge base" (the common ancestor).
bash
# Get files changed compared to main
git diff --name-only origin/main...HEAD
The Fallback Mechanism
If the graph calculation fails or returns 0 tests (e.g., a config file change that affects everything), the system must default to running relevant test suites or a "smoke test" suite.
Tooling Recommendations (Build vs. Buy)
Building this from scratch is educational, but production-grade graph management is hard. Consider using existing tools if possible:
Nx (JavaScript/TS): Has a built-in graph affected command (nx affected --target=test).