File size: 3,662 Bytes
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""Dependency graph algorithms with cycle handling."""

from __future__ import annotations

from collections import defaultdict
import heapq

from .repo_model import DependencyEdge


def strongly_connected_components(nodes: list[str], edges: list[DependencyEdge]) -> list[tuple[str, ...]]:
    """Return SCCs using iterative Kosaraju passes to handle very deep graphs."""
    node_set = set(nodes)
    outgoing: dict[str, set[str]] = defaultdict(set)
    incoming: dict[str, set[str]] = defaultdict(set)
    for edge in edges:
        if edge.status == "resolved" and edge.source in node_set and edge.target in node_set:
            outgoing[edge.source].add(edge.target)
            incoming[edge.target].add(edge.source)

    visited: set[str] = set()
    finish_order: list[str] = []
    for node in sorted(nodes):
        if node in visited:
            continue
        visited.add(node)
        stack: list[tuple[str, bool]] = [(node, False)]
        while stack:
            current, expanded = stack.pop()
            if expanded:
                finish_order.append(current)
                continue
            stack.append((current, True))
            for target in sorted(outgoing.get(current, ()), reverse=True):
                if target not in visited:
                    visited.add(target)
                    stack.append((target, False))

    result: list[tuple[str, ...]] = []
    visited.clear()
    for node in reversed(finish_order):
        if node in visited:
            continue
        visited.add(node)
        component: list[str] = []
        stack = [(node, False)]
        while stack:
            current, _ = stack.pop()
            component.append(current)
            for source in sorted(incoming.get(current, ()), reverse=True):
                if source not in visited:
                    visited.add(source)
                    stack.append((source, False))
        result.append(tuple(sorted(component)))
    return result


def dependency_first_order(nodes: list[str], edges: list[DependencyEdge]) -> tuple[str, ...]:
    """Return dependencies before dependents; stable path order breaks ties."""
    components = strongly_connected_components(nodes, edges)
    component_by_node = {
        node: component_index
        for component_index, component in enumerate(components)
        for node in component
    }
    outgoing: dict[int, set[int]] = {index: set() for index in range(len(components))}
    indegree: dict[int, int] = {index: 0 for index in range(len(components))}
    for edge in edges:
        if (
            edge.status != "resolved"
            or edge.target not in component_by_node
            or edge.source not in component_by_node
        ):
            continue
        # source depends on target, so target precedes source.
        dependency = component_by_node[edge.target]
        dependent = component_by_node[edge.source]
        if dependency != dependent and dependent not in outgoing[dependency]:
            outgoing[dependency].add(dependent)
            indegree[dependent] += 1

    # The component tuple is sorted, so it is also a deterministic tie breaker.
    ready = [(components[index], index) for index, degree in indegree.items() if degree == 0]
    heapq.heapify(ready)
    order: list[str] = []
    while ready:
        component, component_index = heapq.heappop(ready)
        order.extend(component)
        for dependent in sorted(outgoing[component_index], key=components.__getitem__):
            indegree[dependent] -= 1
            if indegree[dependent] == 0:
                heapq.heappush(ready, (components[dependent], dependent))
    return tuple(order)