77"""
88
99import logging
10- from typing import Dict , List , Set , Any
1110from collections import deque
11+ from typing import Any
1212
13- from codewiki .src .be .dependency_analyzer .models .core import Node
1413from codewiki .src .be .dependency_analyzer .leaf_selection import (
1514 LEAF_REDUCTION_THRESHOLD ,
1615 compute_valid_leaf_types ,
1716 filter_leaf_nodes ,
1817)
18+ from codewiki .src .be .dependency_analyzer .models .core import Node
1919
2020logger = logging .getLogger (__name__ )
2121
2222
23- def detect_cycles (graph : Dict [str , Set [str ]]) -> List [ List [str ]]:
23+ def detect_cycles (graph : dict [str , set [str ]]) -> list [ list [str ]]:
2424 """
2525 Detect cycles in a dependency graph using Tarjan's algorithm to find
2626 strongly connected components.
27-
27+
2828 Args:
2929 graph: A dependency graph represented as adjacency lists
3030 (node -> set of dependencies)
31-
31+
3232 Returns:
3333 A list of lists, where each inner list contains the nodes in a cycle
3434 """
@@ -39,15 +39,15 @@ def detect_cycles(graph: Dict[str, Set[str]]) -> List[List[str]]:
3939 onstack = set () # nodes currently on the stack
4040 stack = [] # stack of nodes
4141 result = [] # list of cycles (strongly connected components)
42-
42+
4343 def strongconnect (node ):
4444 # Set the depth index for node
4545 index [node ] = index_counter [0 ]
4646 lowlink [node ] = index_counter [0 ]
4747 index_counter [0 ] += 1
4848 stack .append (node )
4949 onstack .add (node )
50-
50+
5151 # Consider successors
5252 for successor in graph .get (node , set ()):
5353 if successor not in index :
@@ -57,7 +57,7 @@ def strongconnect(node):
5757 elif successor in onstack :
5858 # Successor is on the stack and hence in the current SCC
5959 lowlink [node ] = min (lowlink [node ], index [successor ])
60-
60+
6161 # If node is a root node, pop the stack and generate an SCC
6262 if lowlink [node ] == index [node ]:
6363 # Start a new strongly connected component
@@ -68,236 +68,240 @@ def strongconnect(node):
6868 scc .append (successor )
6969 if successor == node :
7070 break
71-
71+
7272 # Only include SCCs with more than one node (actual cycles)
7373 if len (scc ) > 1 :
7474 result .append (scc )
75-
75+
7676 # Visit each node
7777 for node in graph :
7878 if node not in index :
7979 strongconnect (node )
80-
80+
8181 return result
8282
83- def resolve_cycles (graph : Dict [str , Set [str ]]) -> Dict [str , Set [str ]]:
83+
84+ def resolve_cycles (graph : dict [str , set [str ]]) -> dict [str , set [str ]]:
8485 """
8586 Resolve cycles in a dependency graph by identifying strongly connected
8687 components and breaking cycles.
87-
88+
8889 Args:
8990 graph: A dependency graph represented as adjacency lists
9091 (node -> set of dependencies)
91-
92+
9293 Returns:
9394 A new acyclic graph with the same nodes but with cycles broken
9495 """
9596 # Detect cycles (SCCs)
9697 cycles = detect_cycles (graph )
97-
98+
9899 if not cycles :
99100 logger .debug ("No cycles detected in the dependency graph" )
100101 return graph
101-
102+
102103 logger .debug (f"Detected { len (cycles )} cycles in the dependency graph" )
103-
104+
104105 # Create a copy of the graph to modify
105106 new_graph = {node : deps .copy () for node , deps in graph .items ()}
106-
107+
107108 # Process each cycle
108109 for i , cycle in enumerate (cycles ):
109- logger .debug (f"Cycle { i + 1 } : { ' -> ' .join (cycle )} " )
110-
110+ logger .debug (f"Cycle { i + 1 } : { ' -> ' .join (cycle )} " )
111+
111112 # Strategy: Break the cycle by removing the "weakest" dependency
112113 # Here, we just arbitrarily remove the last edge to make the graph acyclic
113114 # In a real-world scenario, you might use heuristics to determine which edge to break
114115 # For example, removing edges between different modules before edges within the same module
115116 for j in range (len (cycle ) - 1 ):
116117 current = cycle [j ]
117118 next_node = cycle [j + 1 ]
118-
119+
119120 if next_node in new_graph [current ]:
120121 logger .debug (f"Breaking cycle by removing dependency: { current } -> { next_node } " )
121122 new_graph [current ].remove (next_node )
122123 break
123-
124+
124125 return new_graph
125126
126- def topological_sort (graph : Dict [str , Set [str ]]) -> List [str ]:
127+
128+ def topological_sort (graph : dict [str , set [str ]]) -> list [str ]:
127129 """
128130 Perform a topological sort on a dependency graph.
129-
131+
130132 Args:
131133 graph: A dependency graph represented as adjacency lists
132134 (node -> set of dependencies)
133-
135+
134136 Returns:
135137 A list of nodes in topological order (dependencies first)
136138 """
137139 # First, check for and resolve cycles
138140 acyclic_graph = resolve_cycles (graph )
139-
141+
140142 # Initialize in-degree counter for all nodes
141143 in_degree = {node : 0 for node in acyclic_graph }
142-
144+
143145 # Count in-degrees
144146 for node , dependencies in acyclic_graph .items ():
145147 for dep in dependencies :
146148 if dep in in_degree :
147149 in_degree [dep ] += 1
148-
150+
149151 # Queue of nodes with no dependencies (in-degree of 0)
150152 queue = deque ([node for node , degree in in_degree .items () if degree == 0 ])
151-
153+
152154 # Result list to store the topological order
153155 result = []
154-
156+
155157 # Process nodes in topological order
156158 while queue :
157159 node = queue .popleft ()
158160 result .append (node )
159-
161+
160162 # Reduce in-degree for each node that depends on the current node
161163 for dependent , deps in acyclic_graph .items ():
162164 if node in deps :
163165 in_degree [dependent ] -= 1
164166 if in_degree [dependent ] == 0 :
165167 queue .append (dependent )
166-
168+
167169 # Check if the sort was successful (all nodes included)
168170 if len (result ) != len (acyclic_graph ):
169171 logger .warning ("Topological sort failed: graph has cycles that weren't resolved" )
170172 # Return all nodes in some order to avoid breaking the process
171173 return list (acyclic_graph .keys ())
172-
174+
173175 # Reverse the result to get dependencies first
174176 return result [::- 1 ]
175177
176- def dependency_first_dfs (graph : Dict [str , Set [str ]]) -> List [str ]:
178+
179+ def dependency_first_dfs (graph : dict [str , set [str ]]) -> list [str ]:
177180 """
178181 Perform a depth-first traversal of the dependency graph, starting from root nodes
179182 that have no dependencies.
180-
183+
181184 The graph uses natural dependency direction:
182185 - If A depends on B, the graph has an edge A → B
183186 - This means an edge from X to Y represents "X depends on Y"
184187 - Root nodes (nodes with no incoming edges/dependencies) are processed first,
185188 followed by nodes that depend on them
186-
189+
187190 Args:
188191 graph: A dependency graph with natural direction (A→B if A depends on B)
189-
192+
190193 Returns:
191194 A list of nodes in an order where dependencies come before their dependents
192195 """
193196 # First, resolve cycles to ensure we have a DAG
194197 acyclic_graph = resolve_cycles (graph )
195-
198+
196199 # Find root nodes (nodes with no dependencies)
197200 root_nodes = []
198201 # Create a reverse graph to easily check if a node has incoming edges
199202 has_incoming_edge = {node : False for node in acyclic_graph }
200-
203+
201204 for node , deps in acyclic_graph .items ():
202205 for dep in deps :
203206 has_incoming_edge [dep ] = True
204-
207+
205208 # Nodes with no incoming edges are root nodes
206209 for node in acyclic_graph :
207210 if not has_incoming_edge .get (node , False ) and node in acyclic_graph :
208211 root_nodes .append (node )
209-
212+
210213 if not root_nodes :
211214 logger .warning ("No root nodes found in the graph, using arbitrary starting point" )
212215 root_nodes = list (acyclic_graph .keys ())[:1 ] # Use the first node as starting point
213-
216+
214217 # Track visited nodes
215218 visited = set ()
216219 result = []
217-
220+
218221 # DFS function that processes dependencies first
219222 def dfs (node ):
220223 if node in visited :
221224 return
222225 visited .add (node )
223-
226+
224227 # Visit all dependencies first
225228 for dep in sorted (acyclic_graph .get (node , set ())):
226229 dfs (dep )
227-
230+
228231 # Add this node to the result after all its dependencies
229232 result .append (node )
230-
233+
231234 # Start DFS from each root node
232235 for root in sorted (root_nodes ):
233236 dfs (root )
234-
237+
235238 # Check if all nodes were visited
236239 if len (result ) != len (acyclic_graph ):
237240 # Some nodes weren't visited - try to visit remaining nodes
238241 for node in sorted (acyclic_graph .keys ()):
239242 if node not in visited :
240243 dfs (node )
241-
244+
242245 return result
243246
244- def build_graph_from_components (components : Dict [str , Any ]) -> Dict [str , Set [str ]]:
247+
248+ def build_graph_from_components (components : dict [str , Any ]) -> dict [str , set [str ]]:
245249 """
246250 Build a dependency graph from a collection of code components.
247-
251+
248252 The graph uses the natural dependency direction:
249253 - If A depends on B, we create an edge A → B
250254 - This means an edge from node X to node Y represents "X depends on Y"
251255 - Root nodes (nodes with no dependencies) are components that don't depend on anything
252-
256+
253257 Args:
254258 components: A dictionary of code components, where each component
255259 has a 'depends_on' attribute
256-
260+
257261 Returns:
258262 A dependency graph with natural dependency direction
259263 """
260264 graph = {}
261-
265+
262266 for comp_id , component in components .items ():
263267 # Initialize the node's adjacency list
264268 if comp_id not in graph :
265269 graph [comp_id ] = set ()
266-
270+
267271 # Add dependencies
268272 for dep_id in component .depends_on :
269273 # Only include dependencies that are actual components in our repository
270274 if dep_id in components :
271275 graph [comp_id ].add (dep_id )
272-
273- return graph
276+
277+ return graph
274278
275279
276- def get_leaf_nodes (graph : Dict [str , Set [str ]], components : Dict [str , Node ]) -> List [str ]:
280+ def get_leaf_nodes (graph : dict [str , set [str ]], components : dict [str , Node ]) -> list [str ]:
277281 """
278282 Find leaf nodes (nodes that no other nodes depend on) and build dependency trees
279283 showing the full dependency chain from each leaf back to the ultimate dependencies.
280-
284+
281285 The graph uses natural dependency direction:
282286 - If A depends on B, the graph has an edge A → B
283287 - Leaf nodes are nodes that appear in no other node's dependency set
284288 - Each tree shows the dependency chain: leaf → its dependencies → their dependencies, etc.
285-
289+
286290 Args:
287291 graph: A dependency graph with natural direction (A→B if A depends on B)
288-
292+
289293 Returns:
290294 A list of leaf nodes
291295 """
292296 # First, resolve cycles to ensure we have a DAG
293297 acyclic_graph = resolve_cycles (graph )
294-
298+
295299 # Find leaf nodes (nodes that no other nodes depend on)
296300 leaf_nodes = set (acyclic_graph .keys ())
297301
298302 valid_types = compute_valid_leaf_types (components )
299303
300- def concise_node (leaf_nodes : Set [str ]) -> Set [str ]:
304+ def concise_node (leaf_nodes : set [str ]) -> set [str ]:
301305 concise_leaf_nodes = set ()
302306 for node in leaf_nodes :
303307 if node .endswith ("__init__" ):
@@ -310,16 +314,23 @@ def concise_node(leaf_nodes: Set[str]) -> Set[str]:
310314
311315 concise_leaf_nodes = concise_node (leaf_nodes )
312316 if len (concise_leaf_nodes ) >= LEAF_REDUCTION_THRESHOLD :
313- logger .debug (f"Leaf nodes are too many ({ len (concise_leaf_nodes )} ), removing dependencies of other nodes" )
317+ count_before = len (concise_leaf_nodes )
318+ logger .info (
319+ "Leaf nodes are too many (%d >= %d); reducing to components "
320+ "that nothing else depends on." ,
321+ count_before ,
322+ LEAF_REDUCTION_THRESHOLD ,
323+ )
314324 # Remove nodes that are dependencies of other nodes
315- for node , deps in acyclic_graph .items ():
325+ for deps in acyclic_graph .values ():
316326 for dep in deps :
317327 leaf_nodes .discard (dep )
318-
328+
319329 concise_leaf_nodes = concise_node (leaf_nodes )
320-
330+ logger .info ("Reduced from %d to %d leaf nodes." , count_before , len (concise_leaf_nodes ))
331+
321332 if not leaf_nodes :
322333 logger .warning ("No leaf nodes found in the graph" )
323334 return []
324-
325- return concise_leaf_nodes
335+
336+ return concise_leaf_nodes
0 commit comments