# How Knowledge Gap Analysis Identifies Structural Weaknesses in Code

> Discover how knowledge gap analysis in code-review-graph identifies structural weaknesses like isolated symbols and untested hotspots, revealing architectural fragility.

- Repository: [Tirth Kanani/code-review-graph](https://github.com/tirth8205/code-review-graph)
- Tags: deep-dive
- Published: 2026-08-09

---

**The knowledge gap analysis in `tirth8205/code-review-graph` uses graph topology metrics to flag isolated symbols, undersized communities, untested hotspots, and monolithic file structures that indicate architectural fragility.**

The `tirth8205/code-review-graph` project provides a static analysis framework that converts codebases into graph structures to reveal hidden architectural debt. Its **knowledge gap analysis** feature examines connectivity patterns and community structure to pinpoint exactly where code organization breaks down. By analyzing node degrees, cluster sizes, and test coverage edges in [`code_review_graph/analysis.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/analysis.py), the system surfaces four specific categories of structural weakness that traditional linters often miss.

## How Knowledge Gap Analysis Works

The analysis is implemented in [`code_review_graph/analysis.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/analysis.py) within the `find_knowledge_gaps(store: GraphStore) → dict[str, list[dict]]` function. This routine accepts a `GraphStore` instance—backed by SQLite via [`code_review_graph/graph.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/graph.py)—and returns a dictionary mapping weakness categories to lists of offending symbols or communities.

The function constructs a degree map by iterating over all edges in the graph, incrementing counters for both source and target nodes (`degree[e.source_qualified] += 1` and `degree[e.target_qualified] += 1`). It then combines this connectivity data with community detection results and test relationship edges to categorize structural problems.

## Four Structural Weaknesses Detected

### Isolated Nodes (Dead Code Indicators)

Nodes with a degree of one or fewer represent symbols that are rarely referenced within the codebase. The algorithm selects these by checking `if d <= 1:` after building the degree map at lines 28‑44. These **isolated nodes** often indicate dead code, dynamically loaded modules, or orphaned utilities that lack integration tests and may be safe to deprecate.

### Thin Communities (Missing Abstractions)

The analysis flags communities (clusters of tightly coupled symbols) containing fewer than three members. By counting community sizes (`comm_sizes[cid] += 1`) and filtering for `size < 3` at lines 59‑67, it reveals potential **missing abstractions** or duplicated logic that should be consolidated into shared libraries rather than scattered across small, disconnected clusters.

### Untested Hotspots (High-Risk Production Code)

High-degree nodes with five or more connections that lack `TESTED_BY` edges represent critical production code without test coverage. The detection logic at lines 72‑80 checks `if (d >= 5 and n.qualified_name not in tested_nodes and not n.is_test):` to identify these **untested hotspots**. These symbols act as central hubs in the dependency graph, making them high-impact failure points that require immediate testing attention.

### Single-File Communities (Modularity Violations)

When an entire community of three or more symbols resides within a single source file, it signals a **monolithic structure** violating separation of concerns. The analysis tracks file sets per community (`comm_files[cid].add(n.file_path)`) and reports cases where `len(files) == 1` and `size >= 3` at lines 91‑99, highlighting files that should be split to improve maintainability.

## Running Knowledge Gap Analysis

To execute the analysis on your own codebase, initialize a `GraphStore` and call the gap detection function:

```python
from code_review_graph.graph import GraphStore
from code_review_graph.analysis import find_knowledge_gaps

# Load an existing graph from SQLite

store = GraphStore("path/to/graph.db")

# Detect structural weaknesses

gaps = find_knowledge_gaps(store)

# Review isolated symbols

print("Isolated nodes:")
for n in gaps["isolated_nodes"]:
    print(f"- {n['qualified_name']} ({n['degree']} edge)")

# Examine community health

print("\nThin communities:")
for c in gaps["thin_communities"]:
    print(f"- Community {c['community_id']} ({c['size']} members)")

# Check for untested critical code

print("\nUntested hotspots:")
for h in gaps["untested_hotspots"]:
    print(f"- {h['qualified_name']} ({h['degree']} connections, no tests)")

# Identify monolithic files

print("\nSingle‑file communities:")
for sf in gaps["single_file_communities"]:
    print(f"- Community {sf['community_id']} lives in {sf['file']} ({sf['size']} symbols)")

```

The function returns results capped at practical limits (e.g., the first 50 isolated nodes, first 20 untested hotspots) to ensure actionable output without overwhelming developers with noise.

## Summary

- **Knowledge gap analysis** in `tirth8205/code-review-graph` scans graph topology to detect architectural fragility through four specific weakness categories.
- The `find_knowledge_gaps()` function in [`code_review_graph/analysis.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/analysis.py) analyzes node degrees, community structures, and test coverage relationships.
- **Isolated nodes** (degree ≤ 1) flag potentially dead code or hidden dependencies.
- **Thin communities** (size < 3) suggest missing abstractions or duplicated logic.
- **Untested hotspots** (degree ≥ 5, no test edges) identify high-impact production code lacking coverage.
- **Single-file communities** reveal monolithic files that violate modularity principles and should be refactored.

## Frequently Asked Questions

### What is the entry point for knowledge gap analysis?

The primary entry point is the `find_knowledge_gaps()` function defined in [`code_review_graph/analysis.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/analysis.py). It accepts a `GraphStore` instance containing the parsed codebase graph and returns a dictionary with four lists of structural weaknesses: `isolated_nodes`, `thin_communities`, `untested_hotspots`, and `single_file_communities`.

### How does the analysis distinguish between test and production code?

The algorithm checks the `is_test` boolean property on graph nodes to exclude test symbols from certain validations. When identifying untested hotspots, it specifically filters out nodes where `n.is_test` is true, ensuring only production code symbols are flagged for lacking test coverage while ignoring the test files themselves.

### What graph metrics determine code isolation?

Isolation is determined by **node degree**, calculated by counting incoming and outgoing edges for each symbol. The analysis builds a degree map by iterating over all edges and incrementing counters for both source and target qualified names, then selects nodes with `degree <= 1` as isolated indicators of potential dead code.

### Can knowledge gap analysis automatically detect dead code?

While the analysis identifies **isolated nodes** with minimal connectivity (degree ≤ 1) that often indicate dead code, it cannot definitively confirm deletion safety without runtime analysis. These nodes may also represent dynamically loaded modules, plugin entry points, or framework callbacks, requiring manual review before removal.