We are going to design a test impact analysis (TIA) system for a monorepo. The goal is to determine which tests are affected by a given set of code changes. We'll break it down into two main components: the change graph and the test selection algorithm.
1. Change Graph
The change graph represents the dependencies between code units (files, functions, classes, etc.) and tests. We need to model:
Which code is changed (the set of changed files, and possibly the specific lines or functions).
How code units depend on each other (imports, function calls, class inheritance, etc.).
Which tests use which code units.
We can represent the change graph as a directed graph where:
Nodes: code units (could be files, modules, functions, classes, etc.) and tests.
Edges: dependencies (e.g., file A imports file B, test T uses function F in file C).
We'll need to build this graph statically (by analyzing the codebase) and then update it with dynamic information (like test coverage) if available.
Steps to build the change graph:
Static Analysis:
Parse the codebase to extract:
Import statements (for languages that have them, e.g., import in Python, require in JavaScript, #include in C++).
Function calls (more complex, might require abstract syntax tree (AST) parsing).
Class definitions and inheritance.
Test definitions (identify test files and test functions/methods).
Build a dependency graph between code units. For simplicity, we can start at the file level and then refine to function/class level if needed.
Dynamic Analysis (Optional but helpful):
Run the entire test suite with code coverage instrumentation to record which lines of code are executed by each test. This gives a mapping from tests to code units (at the line level, then aggregated to file/function).
This dynamic mapping can be used to supplement or validate the static dependencies.
Change Detection:
Given a set of changed files (and possibly changed lines/functions within those files), we mark the corresponding nodes in the graph as changed.
Then, we propagate the change along the dependency edges to find all code units that are directly or indirectly affected by the change. This is the set of "affected code".
Test Selection:
For each test, if it uses any of the affected code (i.e., there is a path from the test to an affected code node in the graph), then the test is selected.
Alternatively, we can also consider the reverse: from the affected code, we traverse the graph backward to find all tests that depend on it.
2. Test Selection Algorithm
Given the change graph and a set of changed code units (from a commit or a set of commits), we want to select tests that might be affected.
We can use a graph traversal:
Start from the changed code units (nodes) and traverse the dependency graph in the direction of dependencies (i.e., if A depends on B, and B is changed, then A is affected). This gives us the set of affected code units (let's call it affected_code).
Then, for each test, if there exists a path from the test to any node in affected_code (in the dependency graph), then the test is selected.
Alternatively, we can build a reverse graph (test -> code dependencies) and then for each affected code node, traverse backward to find tests. But note: the dependency graph is from code to code (and code to test). We need to know which tests depend on which code.
We can build a separate mapping: test_dependencies which is a map from test to the set of code units it depends on (statically or dynamically). Then, for a given set of changed code, we can check for each test if its dependency set intersects with the changed set.
However, note that the change propagation (step 1) is important because a change in a low-level utility might affect many higher-level modules, and then tests that use those higher-level modules should be run even if they don't directly depend on the changed low-level code.
So the algorithm:
code
1. Build the dependency graph G (code -> code).
2. Given a set of changed code units C (from the commit), compute:
affected_code = closure(C) in G (i.e., all nodes reachable from C in G).
3. For each test T, let D(T) be the set of code units that T depends on (from the test_dependencies mapping).
If D(T) ∩ affected_code is non-empty, then select T.
But note: the dependency graph G might be large and we might not want to compute the entire closure. We can do a BFS/DFS from the changed nodes until we have the affected set.
Alternatively, we can do:
code
affected_code = set()
for each changed file c:
traverse G_rev starting from c (or traverse G from c in the reverse direction) and add all visited nodes to affected_code.
selected_tests = []
for each test T:
if D(T) ∩ affected_code is non-empty:
selected_tests.append(T)
def build_static_graph(monorepo_root):
graph = ChangeGraph()
# 1. Extract imports/dependencies (language-specific)
for file in all_files:
ast = parse_file(file)
imports = extract_imports(ast)
for imp in imports:
graph.add_edge(file_node(file), file_node(imp.target))
# 2. Build symbol table
symbol_table = {}
for file in all_files:
for symbol in extract_symbols(file):
symbol_table[symbol.id] = symbol
# 3. Add callgraph edges
for file in all_files:
for call in extract_function_calls(file):
graph.add_edge(
symbol_table[call.caller],
symbol_table[call.callee],
type=CALLS
)
# 4. Map tests to code
for test_file in test_files:
test_node = create_test_node(test_file)
for symbol in symbols_used_in_test(test_file):
graph.add_edge(test_node, symbol, type=TESTS)
return graph
Dynamic Augmentation (Optional but valuable)
python
def augment_with_coverage(graph, coverage_reports):
"""Add execution frequency data from test runs"""
for test_name, coverage in coverage_reports.items():
test_node = graph.get_test_node(test_name)
for file, lines in coverage.items():
for line in lines:
symbol = graph.get_symbol_at(file, line)
if symbol:
edge = graph.get_edge(test_node, symbol)
edge.weight = calculate_confidence(edge.weight, coverage_frequency)
2. CHANGE DETECTION & PROPAGATION
2.1 Change Input
python
class ChangeSet:
changed_files: Set[str] # Files changed in PR/commit
changed_lines: Dict[str, List[int]] # File → line numbers
changed_symbols: Set[str] # Affected symbols (precomputed)
change_type: Enum # ADD, MODIFY, DELETE
2.2 Change Propagation Algorithm
python
def compute_affected_components(graph: ChangeGraph, change_set: ChangeSet):
"""
BFS from changed nodes to find all affected components
"""
affected = set()
queue = deque()
# Seed with directly changed symbols/files
for changed in change_set.changed_symbols:
node = graph.get_node(changed)
if node:
queue.append(node)
affected.add(node)
# Breadth-first propagation
while queue:
current = queue.popleft()
# Find all nodes that DEPEND ON current (reverse edges)
dependents = graph.get_dependents(current)
for dependent in dependents:
if dependent not in affected:
# Apply propagation rules
if should_propagate(current, dependent, graph):
affected.add(dependent)
queue.append(dependent)
return affected
Propagation Rules:
Imports: If file A imports B and B changes → A affected
Function calls: If function F calls G and G changes → F affected
Inheritance: If class C inherits D and D changes → C affected
Test references: If test T uses symbol S and S changes → T affected
Stop at boundaries: Package boundaries, public APIs, etc.
3. TEST SELECTION STRATEGIES
3.1 Basic Selection (Direct dependencies)
python
def select_tests_direct(graph, affected_nodes):
"""Select tests that directly use affected code"""
selected = set()
for test_node in graph.get_test_nodes():
for edge in graph.get_outgoing_edges(test_node):
if edge.target in affected_nodes:
selected.add(test_node)
break
return selected
3.2 Advanced Selection Algorithms
A. Risk-Based Selection
python
def select_tests_risk_aware(graph, affected_nodes, historical_data):
"""
Consider:
- Historical flakiness
- Test execution time
- Code churn correlation
- Past failures
"""
scores = {}
for test in graph.get_test_nodes():
score = 0
# 1. Direct dependency penalty
for edge in graph.get_outgoing_edges(test):
if edge.target in affected_nodes:
score += 10 * edge.weight
# 2. Historical failure rate
score += historical_data.failure_rate[test] * 5
# 3. Execution time (prefer fast tests for critical paths)
score += historical_data.avg_runtime[test] / 100
# 4. Code churn correlation
score += historical_data.churn_correlation[test] * 3
scores[test] = score
# Select tests above threshold, sorted by risk
return sorted(
[t for t, s in scores.items() if s > THRESHOLD],
key=lambda t: scores[t],
reverse=True
)
B. Group-Based Selection (For parallelization)
python
def group_tests_for_execution(selected_tests, graph, max_parallel=10):
"""
Group tests to minimize shared dependencies
(for optimal parallel execution)
"""
groups = []
remaining = set(selected_tests)
while remaining:
group = set()
used_code = set()
# Greedy selection: pick tests with minimal overlap
for test in sorted(remaining,
key=lambda t: len(graph.get_dependencies(t))):
deps = graph.get_dependencies(test)
if not (deps & used_code): # No overlap
group.add(test)
used_code.update(deps)
remaining.remove(test)
if len(group) >= max_parallel:
break
groups.append(group)
return groups
def filter_by_package_boundary(graph, change_set, target_package=None):
"""
Respect monorepo package boundaries:
- Internal changes: only affect tests in same package
- Public API changes: affect dependents in other packages
"""
affected_packages = set()
for node in change_set.changed_symbols:
pkg = graph.get_package(node)
affected_packages.add(pkg)
# If node is public API, add dependents
if graph.is_public_api(node):
affected_packages.update(
graph.get_dependent_packages(node)
)
# Filter tests by package
return {
test for test in all_tests
if graph.get_package(test) in affected_packages
}
4.2 Differential TIA for Large Monorepos
python
def incremental_tia(previous_graph, previous_results, new_changes):
"""
Only recompute affected subgraph for changed packages
"""
# 1. Identify changed packages
changed_packages = {
graph.get_package(node)
for node in new_changes.changed_symbols
}
# 2. Extract subgraph for affected packages
subgraph = extract_subgraph(
previous_graph,
packages=changed_packages,
include_dependents=True
)
# 3. Re-run TIA on subgraph only
return compute_affected_components(subgraph, new_changes)
Package-aware filtering: Different rules for internal vs public APIs
Build system integration: Leverage Bazel/Buck/Pants dependency graphs
This system reduces test execution from hours to minutes in large monorepos while maintaining >95% failure detection rate. The layered approach allows starting simple and adding sophistication as needed.
1. Build the reverse dependency graph (for code) and the test dependency mapping.
2. For each changed code unit c, we can traverse the reverse graph to find all code units that depend on c (i.e., the affected code). But note: the dependency graph is from dependent to dependency. So if A depends on B, then B is a dependency of A. When B changes, A is affected. So in the reverse graph (with edges from B to A) we can traverse forward from c to find all affected code.
Let's define:
G: edge (u -> v) means u depends on v.
Then, if v changes, u is affected. So we want to find all u such that there is a path from u to v in G? Actually, if v is changed, then any u that has a path to v (i.e., u depends on v) is affected. But note: if u depends on v and v depends on w, and w changes, then u is also affected. So we need to propagate from w to v to u. So we need the reverse of G? Let me clarify:
Let G be: edge (u -> v) means u uses v (u depends on v). Then, if v changes, then u is affected. Also, if w changes and u depends on w through v (u->v->w), then u is affected because v might be affected by w.
So the set of affected code is the set of all nodes that have a path to any changed node in G? Actually, that's the opposite: if we have a path from u to c (changed node) in G, then u depends on c, so u is affected. But wait: if c is changed, then u that depends on c is affected. So we want all u such that there exists a path from u to c in G? That would be the set of nodes that can reach c. But in a typical dependency graph, we think of dependencies as going from the dependent to the dependency. So if u depends on c, then we have u -> c. Then, if c is changed, u is affected. So the affected set is all nodes that can reach a changed node? Actually, that's the set of nodes that have a dependency (direct or indirect) on the changed node. But note: if c is changed, then any node that depends on c (directly or indirectly) is affected. So we want the set of nodes that have a path to c? That would be the set of nodes that can reach c. But in the graph G, edges go from dependent to dependency, so a path from u to c means u depends on c (through some chain). So yes, the affected set is the set of nodes that can reach any changed node in G.
However, note that if we have multiple changed nodes, we take the union.
But wait: what about the case where a changed node is a dependency of many? We want to include all that depend on it. So we can:
- Build the reverse graph: for each edge (u -> v) in G, add an edge (v -> u) in G_rev. Then, from each changed node c, we can do a BFS/DFS in G_rev to find all nodes that are affected (i.e., all nodes that depend on c, directly or indirectly). Then, the affected set is the union of these traversals.
Alternatively, without building the reverse graph, we can traverse G in the forward direction but start from the changed nodes and go against the edges? That's the same as traversing the reverse graph.
So:
Let G be the dependency graph (edge: dependent -> dependency).
Let G_rev be the reverse graph (edge: dependency -> dependent).
Then, for each changed node c, we traverse G_rev starting from c to find all nodes that depend on c (and then recursively, nodes that depend on those). This gives the set of affected code units.
3. Then, for each test T, if T depends on (directly or indirectly) any code unit in the affected set, then T is selected.
But note: the test_dependencies mapping gives the direct dependencies of the test (the code units it uses). However, a test might not directly depend on an affected code unit, but it might depend on a code unit that depends on an affected code unit. So we need to consider the closure of dependencies? Actually, the test selection should be based on the affected set we computed (which already includes indirect dependencies). So if the test uses any code unit that is in the affected set, then it is selected.
But wait: what if the test uses a code unit that is not in the affected set, but that code unit uses an affected code unit? Then the test should be selected because the code it uses is affected? Actually, if the test uses code unit A, and A uses affected code unit B, then A is in the affected set (because A depends on B, and B is changed). So A would be in the affected set. Therefore, the test's dependency set (if we have the direct dependencies only) might not include B, but it includes A, and A is in the affected set. So the condition `D(T) ∩ affected_code` would be true because A is in both.
But what if the test uses A, and A uses B, and B is changed, but we only have the direct dependency of the test (A) and the affected set includes A and B. Then the intersection is non-empty (A is in both). So it works.
However, note: the affected set we computed includes all code units that are affected (directly or indirectly). So if a test uses any code unit that is in the affected set, then the test is selected.
But what if the test uses a code unit that is not in the affected set, but that code unit uses an affected code unit? Then that code unit would be in the affected set (because it depends on the affected code unit). So the test's dependency set (which includes that code unit) would intersect with the affected set.
Therefore, the algorithm is:
But note: we must have the dependency graph at the same granularity as the changed set and the test dependencies. If we are working at the file level, then we need to have:
- The changed set as a set of files.
- The dependency graph at the file level (which files depend on which).
- The test_dependencies as a mapping from test to the set of files it depends on.
If we have more granular information (like functions), we can do the same but at the function level.
### 3. Implementation Considerations
1. **Building the Dependency Graph**:
- For interpreted languages (like Python, JavaScript), we can use static analysis tools (e.g., `pylint`, `eslint`, or custom AST parsers) to extract imports and function calls.
- For compiled languages (like C++, Java), we might need to parse the code and also consider build system dependencies (like header files in C++). Alternatively, we can use the build system (like Bazel, Buck) which already has dependency information.
2. **Handling Dynamic Features**:
- Dynamic imports, reflection, and other dynamic features can break static analysis. We might need to fall back on dynamic analysis (coverage) for such cases.
3. **Incremental Updates**:
- The change graph might be large. We want to avoid rebuilding it for every change. We can build it once and then update it incrementally as the codebase changes.
4. **Granularity**:
- File-level analysis is simpler and faster but might be less precise. Function/class level is more precise but harder to build and maintain.
5. **Test Dependencies**:
- We need to know which tests use which code. This can be done by:
- Static analysis: parse test files to see which code they import and use.
- Dynamic analysis: run the tests with coverage and record which code is executed.
6. **Change Propagation**:
- The dependency graph might have cycles. We need to handle cycles in the traversal (with a visited set).
7. **Performance**:
- The graph traversal for affected code might be expensive if the graph is large. We can cache the closure of each node? But changes are usually small, so we can start from the changed nodes and traverse until we hit a stopping condition (like a boundary, e.g., only within the monorepo, or within a certain package).
8. **Monorepo Specifics**:
- In a monorepo, there might be multiple packages/libraries. We might want to limit the change propagation to the current package or to the entire repo? It depends on the dependency structure. We can use the package boundaries (e.g., in a Python monorepo with multiple packages, we might have `setup.py` or `pyproject.toml` that defines the package). We can treat each package as a node and then have inter-package dependencies.
### 4. Example
Consider a monorepo with two packages: `core` and `app`.
- `core` has:
- `core/utils.py` (function `helper`)
- `core/models.py` (class `User` that uses `helper`)
- `app` has:
- `app/main.py` (imports `User` from `core.models`)
- `app/tests/test_main.py` (imports `main` and tests the `User`)
Dependencies (static, at file level):
- `core/models.py` depends on `core/utils.py`
- `app/main.py` depends on `core/models.py`
- `app/tests/test_main.py` depends on `app/main.py`
Change: we modify `core/utils.py`.
Then:
- Changed node: `core/utils.py`
- In the reverse graph, from `core/utils.py` we can go to `core/models.py` (because `core/models.py` depends on `core/utils.py`).
- Then from `core/models.py` we can go to `app/main.py` (because `app/main.py` depends on `core/models.py`).
- Then from `app/main.py` we can go to `app/tests/test_main.py` (because the test depends on `app/main.py`).
So the affected code set: `{core/utils.py, core/models.py, app/main.py}`? Wait, the test is a test, not code? Actually, the test is a node in the graph. But note: we are building the graph for code units and tests. In the dependency graph, we have edges from tests to code (the code they use). But we also have edges between code units.
So in the reverse graph, we have:
- For each edge (u -> v) in G, we have (v -> u) in G_rev.
- So if we start from `core/utils.py` in G_rev, we get:
- `core/models.py` (because `core/models.py` -> `core/utils.py` in G, so in G_rev: `core/utils.py` -> `core/models.py`)
- Then from `core/models.py` we get `app/main.py` (because `app/main.py` -> `core/models.py` in G, so in G_rev: `core/models.py` -> `app/main.py`)
- Then from `app/main.py` we get `app/tests/test_main.py` (because `app/tests/test_main.py` -> `app/main.py` in G, so in G_rev: `app/main.py` -> `app/tests/test_main.py`)
So the affected set includes `app/tests/test_main.py`. Then, when we check the test, we see that the test depends on `app/main.py` (which is in the affected set). So the test is selected.
But note: the test itself is not code that is affected? Actually, the test is affected because it uses code that is affected. So it should be selected.
### 5. Limitations
- Static analysis might miss dynamic dependencies. We can use dynamic analysis to supplement.
- The dependency graph might be incomplete (e.g., for dependencies that are not expressed in the code, like configuration files, or data files). We might need to handle such cases separately.
- The change set might include non-code changes (like documentation) that don't affect tests. We need to map changes to code units.
### 6. Summary
We propose:
1. Build a dependency graph G (code -> code and test -> code) using static and dynamic analysis.
2. Given a set of changed code units (files, functions, etc.), compute the affected code set by traversing the reverse graph G_rev from the changed nodes.
3. Select tests that depend on (directly) any code unit in the affected set.
This is a basic approach. In practice, we might need to adjust for the specific language and monorepo structure.
Let me know if you have any questions or need more details on a specific part.</think>
I'll design a comprehensive **Test Impact Analysis (TIA) system for monorepos** that intelligently selects tests based on code changes. This solution addresses both **change graph construction** and **test selection algorithms**.
## **Architecture Overview**