Leiden Community Detection Algorithm for Architecture Mapping in Code-Review-Graph
The Code-Review-Graph repository implements architecture mapping using the Leiden community detection algorithm via the optional igraph library to cluster code entities into cohesive architectural communities.
This open-source tool analyzes repository structure by treating functions, classes, and modules as nodes in a knowledge graph, then applies advanced graph clustering to reveal architectural boundaries. Understanding which community detection algorithm powers this analysis helps developers interpret the resulting architecture maps and tune the detection parameters for their specific codebases.
How the Leiden Algorithm Powers Architecture Mapping
The architecture mapping pipeline in code_review_graph/communities.py centers on graph-based community detection. The system constructs an undirected graph where code entities (functions, classes, etc.) represent nodes and relationships (calls, imports, inheritance) form weighted edges defined in the EDGE_WEIGHTS configuration.
When the detect_communities function is called, it delegates to _detect_leiden (lines 53-66 in code_review_graph/communities.py), which instantiates an igraph graph and executes the Leiden algorithm with repository-specific parameters.
Deterministic Seeding and Reproducibility
The implementation guarantees reproducible results across builds through deterministic seeding. The source code defines CRG_LEIDEN_SEED = 42 as the default random seed, ensuring identical community IDs for identical graph inputs. Developers can override this behavior by setting the CRG_LEIDEN_SEED environment variable before execution, enabling controlled experiments with different clustering randomizations.
Dynamic Resolution Scaling
The algorithm adapts to repository size through an auto-scaling resolution parameter. Rather than using a fixed resolution value, the system calculates resolution as approximately 1 / log₁₀(N) where N represents the number of nodes. This logarithmic scaling prevents oversized communities in large monorepos while maintaining granularity in smaller projects. The implementation runs the Leiden optimizer for two fixed iterations, balancing computational cost against clustering optimization.
Post-Processing and Community Refinement
Raw Leiden output undergoes several refinement stages before final architecture reporting. The system first reassigns test nodes to their most relevant production communities, ensuring test suites don't fragment the architectural view. Oversized communities trigger recursive splitting via repeated Leiden applications with adjusted parameters, while name disambiguation logic resolves duplicate community identifiers.
If the igraph library is unavailable, the codebase gracefully falls back to file-system-based grouping, though this produces less semantically meaningful boundaries than the graph-based approach.
Generating Architecture Overviews
The get_architecture_overview function (lines 1020-1030 in code_review_graph/communities.py) orchestrates the complete analysis pipeline. After detecting communities, it calculates cross-community edge counts to identify high-coupling boundaries between architectural units. The function emits specific warnings when communities exhibit excessive interdependencies, excluding test-dominated communities from coupling analysis to focus on production code architecture.
Working with the Community Detection API
The repository exposes both high-level overview generation and low-level community detection APIs.
Detect communities for specific size thresholds:
from code_review_graph.communities import detect_communities
from code_review_graph.graph import GraphStore
store = GraphStore(...) # initialise with a repository
communities = detect_communities(store, min_size=5)
for comm in communities:
print(f"{comm['name']}: {comm['size']} nodes, cohesion={comm['cohesion']}")
Generate complete architecture reports with coupling analysis:
from code_review_graph.communities import get_architecture_overview
from code_review_graph.graph import GraphStore
store = GraphStore(...)
overview = get_architecture_overview(store)
print("Communities detected:", len(overview["communities"]))
for warn in overview["warnings"]:
print("⚠️", warn)
Execute the Leiden algorithm directly with custom parameters:
import igraph as ig
from code_review_graph.communities import _detect_leiden
# Assuming you already have `nodes` and `edges` as GraphNode / GraphEdge lists
communities = _detect_leiden(nodes, edges, min_size=10)
Summary
- The Leiden algorithm provides the primary clustering mechanism for architecture mapping in
code_review_graph/communities.py, accessed through the igraph Python library. - Deterministic clustering uses a fixed seed (
CRG_LEIDEN_SEED = 42) with environment variable override capability for reproducible builds. - Dynamic resolution scales inversely with the log of node count, automatically adjusting to repository size.
- Post-processing includes test node reassignment, recursive community splitting, and cross-community coupling analysis to produce actionable architectural views.
- Fallback behavior degrades to file-system grouping when igraph is unavailable, though graph-based detection yields superior architectural boundaries.
Frequently Asked Questions
What happens if igraph is not installed on my system?
When igraph is unavailable, the Code-Review-Graph system defaults to a simple file-system-based grouping strategy. While this fallback produces communities based on directory structure, it lacks the semantic awareness of the Leiden algorithm, which considers actual code relationships like function calls and inheritance. For production use, installing igraph (pip install igraph) is strongly recommended to enable graph-based architecture mapping.
How does the resolution parameter affect community detection results?
The resolution parameter controls the granularity of detected communities according to the formula resolution ≈ 1 / log₁₀(N), where N is the total node count. Higher resolution values produce smaller, more numerous communities, while lower values merge entities into larger architectural units. This auto-scaling approach prevents single massive communities in enterprise-scale repositories while preserving meaningful boundaries in microservice architectures.
Can I customize the random seed for community detection?
Yes. While the default implementation uses CRG_LEIDEN_SEED = 42 for deterministic results, you can override this by setting the CRG_LEIDEN_SEED environment variable to any integer value. This flexibility allows CI/CD pipelines to maintain stable community IDs across builds or researchers to perform sensitivity analysis by comparing architectures generated with different random seeds.
Where does the architecture mapping detect high coupling between communities?
The get_architecture_overview function analyzes cross-community edges after clustering to identify high-coupling boundaries. It specifically counts inter-community relationships and emits warnings when communities exhibit excessive connections, helping architects identify architectural bridges that may violate modularity principles. Test-dominated communities are excluded from this coupling analysis to focus warnings on production code dependencies.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →