0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

依存グラフのトポロジカルソート CLI を Python で — Kahn 法と「サイクルを名指しする」DFS

0
Posted at

make のターゲットや npm の依存、タスクの前後関係——「A の前に B と C を済ませる」という依存グラフを正しい順序に並べるのがトポロジカルソート。それを CLI にした。実装の hinge は 2 つ: (1) Kahn のアルゴリズム (入次数 + キュー) で、しかも出力を安定 (辞書順) にする、(2) 循環があったとき「循環がある」で終わらせず、DFS で『どのノードがサイクルを作っているか』を auth -> cache -> db -> auth の形で名指しする。前 2 回が Rust / Go だったので、今回は Python の CLI で。

📦 GitHub: https://github.com/sen-ltd/topo-sort-cli

(CLI なのでライブデモは無し。python3 main.py か Docker で動かせます。)

スクリーンショット

入力フォーマット

1 行 1 宣言。A: B C は「A は B と C に依存する」(B・C が先)。# コメントと空行は無視:

deploy: build test
build: compile
test: compile
compile:

内部では「前提 → それを必要とするもの」の辺として持つ。A: B なら辺 B -> A。こうすると prerequisites-first のトポロジカルソートがそのままビルド順になる。

hinge 1: Kahn 法 + 安定な出力

トポロジカルソートには大きく DFS 版と Kahn 版がある。Kahn 法は直感的で、入次数 (in-degree, そのノードが依存している前提の数) が 0 のものから順に取り出す:

  1. 各ノードの入次数を数える
  2. 入次数 0 のノード (前提なし = 最初に置ける) をキューに入れる
  3. キューから 1 つ取り出して出力、その「依存先」の入次数を 1 減らす
  4. 0 になったらキューに追加。繰り返す

素朴に実装するとキューの取り出し順が不定で、出力がブレる。heapq (最小ヒープ) で「準備できたノードのうち辞書順最小」を常に取ることで、同じ入力には常に同じ出力を返す:

import heapq

def topo_sort(g):
    indeg = g.indegrees()
    ready = [n for n, d in indeg.items() if d == 0]
    heapq.heapify(ready)                       # 準備完了ノードを最小ヒープに

    order = []
    while ready:
        n = heapq.heappop(ready)               # 辞書順最小 → 安定な順序
        order.append(n)
        for v in sorted(g.adj[n]):
            indeg[v] -= 1
            if indeg[v] == 0:
                heapq.heappush(ready, v)

    if len(order) == len(g.nodes):
        return SortResult(order=order, cycle=None)
    return SortResult(order=None, cycle=_find_cycle(g))  # 全部出せない = 循環

最後の len(order) != len(g.nodes) が肝。入次数が 0 にならないノードが残る = 循環があることの判定そのもの。CI のテストで安定性を固定:

def test_deterministic_tiebreak():
    # 独立した 3 ノード → 辞書順
    assert order_of("b:\na:\nc:\n") == ["a", "b", "c"]

hinge 2: サイクルを「名指し」する

Kahn 法は「循環がある」ことは分かるが、どこにあるかは教えてくれない。error: cycle detected だけ出すツールは多いが、それだと利用者は自分でグラフを睨むはめになる。

そこで 2 パス目に DFS の 3 色塗り分け (white / gray / black) で具体的なサイクルを 1 本取り出す:

  • white = 未訪問、gray = 現在の再帰スタック上、black = 訪問完了
  • DFS 中に gray のノードに再到達 = 後退辺 (back-edge) = 循環
  • そのとき再帰スタックの「該当ノードから先」がサイクルそのもの
def _find_cycle(g):
    WHITE, GRAY, BLACK = 0, 1, 2
    color = {n: WHITE for n in g.nodes}
    stack = []

    def dfs(u):
        color[u] = GRAY
        stack.append(u)
        for v in sorted(g.adj[u]):
            if color[v] == GRAY:               # 後退辺を発見 → サイクル
                idx = stack.index(v)
                return stack[idx:] + [v]       # スタックの該当区間 + 戻り先
            if color[v] == WHITE:
                found = dfs(v)
                if found is not None:
                    return found
        stack.pop()
        color[u] = BLACK
        return None

    for n in sorted(g.nodes):
        if color[n] == WHITE:
            found = dfs(n)
            if found is not None:
                return found
    return []

これで「循環があります」ではなく:

error: graph has a cycle:
  auth -> cache -> db -> auth

と実際の循環経路を出せる。利用者はこの 3 ノードの依存だけ直せばいい。終了コードも 1 にして、シェルスクリプトから検知可能にする。

サイクルが「無実の枝」の裏に隠れていても見つける

DFS は全ノードを起点に回すので、循環と無関係な部分グラフがあっても循環を取り逃さない。テストで固定:

def test_cycle_with_innocent_tail():
    # x -> y は健全。a <-> b が循環。それでも検出できること
    res = topo_sort(parse_graph("x: y\ny:\na: b\nb: a\n"))
    assert res.order is None
    assert set(res.cycle) <= {"a", "b"}
    assert res.cycle[0] == res.cycle[-1]   # 経路は始点に戻る

自己ループ (a: a)、2 ノード循環、3 ノード循環もそれぞれテスト。

CLI

# file 引数があれば読む、無ければ stdin
text = open(args.file).read() if args.file else sys.stdin.read()
graph = parse_graph(text)
result = topo_sort(graph)
if result.cycle is not None:
    print("error: graph has a cycle:", file=sys.stderr)
    print("  " + " -> ".join(result.cycle), file=sys.stderr)
    return 1
for node in (reversed(result.order) if args.reverse else result.order):
    print(node)
return 0

--reverse で依存先優先、--numbered で番号付き。stdin 対応なので cat deps.txt | toposort もできる。

設計

src/graph.py — parse + Kahn 法 + DFS サイクル抽出 (標準ライブラリのみ)
src/cli.py   — argparse、file/stdin、終了コード
main.py      — エントリポイント

外部依存ゼロ。テスト 21 個 (pytest): パース、順序の妥当性、辞書順安定、自己ループ・2/3 ノード循環、無実の枝に隠れた循環。Docker は python:3.12-alpine ビルド → alpine ランタイム、非 root。

動かす

python3 main.py examples/build.deps
python3 -m pytest          # 21 tests
docker build -t toposort . && docker run --rm -i toposort < examples/build.deps

まとめ

  • トポロジカルソートの Kahn 法は「入次数 0 から取り出す」。heapq で辞書順最小を取れば出力が安定する。
  • len(order) != ノード数 が循環の検出条件そのもの。
  • 「循環がある」で終わらせず、DFS の gray ノード再到達で実際のサイクル経路を名指しする (auth -> cache -> db -> auth)。
  • DFS は全ノードを起点に回すので、無関係な枝の裏に隠れた循環も拾える。
  • 終了コードを分ける (正常 0 / 循環 1) とシェルから使える。

これは SEN 合同会社の OSS ポートフォリオ #268 です。https://sen.ltd/portfolio/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?