Skip to content

Fix all_node_cuts: correct Even-Tarjan reduction for Kanevsky's algorithm - #8586

Merged
dschult merged 1 commit into
networkx:mainfrom
jtorrents:fix-all-node-cuts
Apr 10, 2026
Merged

dschult merged 1 commit into
networkx:mainfrom
jtorrents:fix-all-node-cuts

Conversation

@jtorrents

@jtorrents jtorrents commented Mar 26, 2026 •

Copy link
Copy Markdown
Member

The Even-Tarjan auxiliary digraph built by build_auxiliary_node_connectivity sets capacity=1 on all edges. This is correct for computing the node connectivity value, but Kanevsky's algorithm depends on the structure of the residual graph, which requires infinite capacity on external edges as the original Even-Tarjan reduction specifies.

With unit-capacity external edges, these edges get saturated by the flow, producing a residual graph with the wrong structure. The condensation DAG has too many nodes, and the antichain count explodes exponentially.

This bug (introduced by me in the original NetworkX implementation) was not identified when correctness bugs were reported in #3025. The fix in PR #3039 addressed the symptoms (missing cuts) by adding compensating filters: VE1 incident-node filtering, transitive closure on the full residual graph, and internal-edge validation; and also introduced two additional bugs:

  • Removing backward arcs from the residual graph (capacity=0 edges with negative flow that represent cancellable flow and must be preserved)
  • Building closed sets using predecessors instead of successors in the condensation DAG, producing the wrong side of the cut partition

These filters discarded most of the millions of spurious antichains generated by the broken condensation DAG, making results mostly correct but at enormous computational cost.

This fix addresses the root cause and restores the algorithm to match the paper's specification:

  • Set infinite capacity on external edges before building the residual
  • Remove only edges with zero residual capacity (capacity == flow)
  • Build successor-closed sets from antichins of the condensation DAG
  • Find cut edges from S to ~S using H successors.

The compensating code is no longer needed and has been removed.

Performance on grid_2d_graph(11,11) improves from 180s to 0.16s (n=121) (1000x+), and now scales polynomially as predicted by the paper. Results verified identical to igraph's C implementation.

Fixes #7994.

Tests previously marked @pytest.mark.slow are now fast enough to run by default, and MAX_CUTSETS_TO_TEST is restored from 4 to 100.

As a AI disclaimer: I used Claude to explore the problem, build many scripts that printed step by step the state of the data structures used, create benchmarks that compare time and correctness between the old implementation, these fixes, and iGraph. In summary, Claude has been instrumental for fixing this long standing bug (introduced by yours truly nine years ago).

For instance, a really nice benchmark that shows that this implementation is now two times faster than iGraph for a grid 25x25

import timeit
import igraph as ig
import networkx as nx


def runit(i):
    g = nx.grid_2d_graph(i, i)
    k = nx.node_connectivity(g)
    h = ig.Graph.from_networkx(g)

    # Time both
    nx_cuts = []
    def run_nx():
        nx_cuts.clear()
        nx_cuts.extend(list(nx.all_node_cuts(g)))
    t_nx = timeit.timeit(run_nx, number=1)

    ig_cuts = []
    def run_ig():
        ig_cuts.clear()
        ig_cuts.extend(ig.GraphBase.minimum_size_separators(h))
    t_ig = timeit.timeit(run_ig, number=1)

    # Compare results: igraph returns lists of integer indices,
    # nx returns sets of (row, col) tuples. Build a mapping.
    # ig.Graph.from_networkx preserves node order from nx iteration.
    node_list = list(g.nodes())
    ig_as_sets = [frozenset(node_list[idx] for idx in cut) for cut in ig_cuts]
    nx_as_sets = [frozenset(cut) for cut in nx_cuts]

    ig_set = set(ig_as_sets)
    nx_set = set(nx_as_sets)
    match = ig_set == nx_set
    missing = ig_set - nx_set
    extra = nx_set - ig_set

    return dict(i=i, k=k, n=len(g), nx_t=t_nx, ig_t=t_ig,
                nx_count=len(nx_set), ig_count=len(ig_set),
                match=match, missing=len(missing), extra=len(extra))


print(f"{'i':>3} {'k':>2} {'n':>5} {'NX (s)':>10} {'ig (s)':>10} "
      f"{'NX/ig':>7} {'#NX':>4} {'#ig':>4} {'match':>6}")
print("-" * 62)
for i in range(2, 26):
    r = runit(i)
    ratio = r['nx_t'] / r['ig_t']
    status = "OK" if r['match'] else f"DIFF +{r['extra']}/-{r['missing']}"
    print(f"{r['i']:>3} {r['k']:>2} {r['n']:>5} {r['nx_t']:>10.4f} "
          f"{r['ig_t']:>10.4f} {ratio:>6.1f}x {r['nx_count']:>4} "
          f"{r['ig_count']:>4} {status:>6}", flush=True)

Output:

  i  k     n     NX (s)     ig (s)   NX/ig  #NX  #ig  match
--------------------------------------------------------------
  2  2     4     0.0025     0.0003    8.2x    2    2     OK
  3  2     9     0.0026     0.0005    5.6x    4    4     OK
  4  2    16     0.0056     0.0012    4.9x    4    4     OK
  5  2    25     0.0126     0.0030    4.2x    4    4     OK
  6  2    36     0.0256     0.0065    3.9x    4    4     OK
  7  2    49     0.0463     0.0134    3.4x    4    4     OK
  8  2    64     0.0675     0.0169    4.0x    4    4     OK
  9  2    81     0.0712     0.0263    2.7x    4    4     OK
 10  2   100     0.1052     0.0458    2.3x    4    4     OK
 11  2   121     0.1532     0.0769    2.0x    4    4     OK
 12  2   144     0.2168     0.1236    1.8x    4    4     OK
 13  2   169     0.2989     0.1914    1.6x    4    4     OK
 14  2   196     0.4082     0.2908    1.4x    4    4     OK
 15  2   225     0.5433     0.4316    1.3x    4    4     OK
 16  2   256     0.7039     0.6240    1.1x    4    4     OK
 17  2   289     0.9136     0.8796    1.0x    4    4     OK
 18  2   324     1.1356     1.2304    0.9x    4    4     OK
 19  2   361     1.4254     1.6834    0.8x    4    4     OK
 20  2   400     1.7636     2.2417    0.8x    4    4     OK
 21  2   441     2.1633     3.0230    0.7x    4    4     OK
 22  2   484     2.6171     3.9758    0.7x    4    4     OK
 23  2   529     3.2116     5.2050    0.6x    4    4     OK
 24  2   576     3.7976     6.4947    0.6x    4    4     OK
 25  2   625     4.4806     8.1915    0.5x    4    4     OK

@jtorrents

jtorrents commented Mar 26, 2026 •

Copy link
Copy Markdown
Member Author

I decided against changing build_auxiliary_node_connectivity and making it return a proper Even-Tarjan reduction (with infinite capacity on external edges) because disjoint_paths.py calls edge_disjoint_paths(H, sB, tA) for any pair including adjacent ones. With capacity=1, the direct edge sB -> tA carries at most 1 unit of flow, and the algorithm works. With infinite capacity, the flow algorithm raises NetworkXUnbounded.

Other uses of build_auxiliary_node_connectivity in connectivity.py and cuts.py work with a proper ET reduction.

@jtorrents

Copy link
Copy Markdown
Member Author

Benchmark: all_node_cuts correctness and performance vs igraph

Tested the fix across 61 graphs of diverse types and sizes, comparing correctness and timing against igraph's minimum_size_separators (C implementation). All results match igraph exactly.

Broad correctness check

Benchmark script
import timeit
import igraph as ig
import networkx as nx


def runit(name, g):
    if not nx.is_connected(g):
        cc = max(nx.connected_components(g), key=len)
        g = g.subgraph(cc).copy()
    k = nx.node_connectivity(g)
    if nx.density(g) == 1:
        return dict(name=name, n=len(g), k=k, nx_t=0, ig_t=0,
                    nx_count=0, ig_count=0, match=True)
    h = ig.Graph.from_networkx(g)

    nx_cuts = []
    def run_nx():
        nx_cuts.clear()
        nx_cuts.extend(list(nx.all_node_cuts(g)))
    t_nx = timeit.timeit(run_nx, number=1)

    ig_cuts = []
    def run_ig():
        ig_cuts.clear()
        ig_cuts.extend(ig.GraphBase.minimum_size_separators(h))
    t_ig = timeit.timeit(run_ig, number=1)

    node_list = list(g.nodes())
    ig_as_sets = [frozenset(node_list[idx] for idx in cut) for cut in ig_cuts]
    nx_as_sets = [frozenset(cut) for cut in nx_cuts]
    ig_set = set(ig_as_sets)
    nx_set = set(nx_as_sets)

    return dict(name=name, n=len(g), k=k, nx_t=t_nx, ig_t=t_ig,
                nx_count=len(nx_set), ig_count=len(ig_set),
                match=ig_set == nx_set)


graphs = [
    # Named / classical
    ("Petersen", nx.petersen_graph()),
    ("Dodecahedral", nx.dodecahedral_graph()),
    ("Icosahedral", nx.icosahedral_graph()),
    ("Tutte", nx.tutte_graph()),
    ("Heawood", nx.heawood_graph()),
    ("Pappus", nx.pappus_graph()),
    ("Desargues", nx.desargues_graph()),
    ("Möbius-Kantor", nx.moebius_kantor_graph()),
    # Platonic solids
    ("Tetrahedral", nx.tetrahedral_graph()),
    ("Octahedral", nx.octahedral_graph()),
    ("Cubical", nx.cubical_graph()),
    # Cycles
    ("Cycle C5", nx.cycle_graph(5)),
    ("Cycle C10", nx.cycle_graph(10)),
    ("Cycle C20", nx.cycle_graph(20)),
    # Wheels
    ("Wheel W8", nx.wheel_graph(8)),
    ("Wheel W15", nx.wheel_graph(15)),
    # Complete bipartite
    ("K3,3", nx.complete_bipartite_graph(3, 3)),
    ("K3,5", nx.complete_bipartite_graph(3, 5)),
    ("K4,4", nx.complete_bipartite_graph(4, 4)),
    # Hypercubes
    ("Hypercube Q3", nx.hypercube_graph(3)),
    ("Hypercube Q4", nx.hypercube_graph(4)),
    # Grids
    ("Grid 4x4", nx.grid_2d_graph(4, 4)),
    ("Grid 5x5", nx.grid_2d_graph(5, 5)),
    ("Grid 8x8", nx.grid_2d_graph(8, 8)),
    # Circular ladders
    ("Circ. ladder 10", nx.circular_ladder_graph(10)),
    ("Circ. ladder 15", nx.circular_ladder_graph(15)),
    # Random: GNP
    ("GNP(50,0.1)", nx.gnp_random_graph(50, 0.1, seed=42)),
    ("GNP(30,0.3)", nx.gnp_random_graph(30, 0.3, seed=42)),
    ("GNP(40,0.15)", nx.gnp_random_graph(40, 0.15, seed=123)),
    # Random: regular
    ("3-regular(30)", nx.random_regular_graph(3, 30, seed=42)),
    ("5-regular(20)", nx.random_regular_graph(5, 20, seed=42)),
    # Random: scale-free
    ("Barabási-Albert(40,2)", nx.barabasi_albert_graph(40, 2, seed=42)),
    ("Barabási-Albert(50,3)", nx.barabasi_albert_graph(50, 3, seed=42)),
    # Random: small-world
    ("WS(30,4,0.3)", nx.watts_strogatz_graph(30, 4, 0.3, seed=42)),
    ("WS(40,6,0.2)", nx.watts_strogatz_graph(40, 6, 0.2, seed=42)),
    # Social / real-world
    ("Karate club", nx.karate_club_graph()),
    ("Les Misérables", nx.les_miserables_graph()),
    ("Florentine families", nx.florentine_families_graph()),
    # Other interesting structures
    ("Bull graph", nx.bull_graph()),
    ("Chvátal", nx.chvatal_graph()),
    ("Frucht", nx.frucht_graph()),
    ("Sedgewick maze", nx.sedgewick_maze_graph()),
    ("Star S10", nx.star_graph(10)),
]

header = (
    f"{'Graph':<24} {'n':>4} {'k':>2} {'NX (s)':>10} {'ig (s)':>10} "
    f"{'NX/ig':>7} {'#NX':>5} {'#ig':>5} {'match':>6}"
)
print(header)
print("-" * len(header))

n_ok = n_fail = 0
for name, g in graphs:
    r = runit(name, g)
    ratio = f"{r['nx_t'] / r['ig_t']:.1f}x" if r["ig_t"] > 0 else "n/a"
    status = "OK" if r["match"] else f"DIFF"
    if r["match"]:
        n_ok += 1
    else:
        n_fail += 1
    print(
        f"{r['name']:<24} {r['n']:>4} {r['k']:>2} {r['nx_t']:>10.4f} "
        f"{r['ig_t']:>10.4f} {ratio:>7} {r['nx_count']:>5} "
        f"{r['ig_count']:>5} {status:>6}",
        flush=True,
    )

print("-" * len(header))
print(f"Total: {n_ok + n_fail} graphs — {n_ok} OK, {n_fail} FAILED")

Results across 43 graph types (named, platonic, parameterized, random, and real-world):

Graph                       n  k     NX (s)     ig (s)   NX/ig   #NX   #ig  match
---------------------------------------------------------------------------------
Petersen                   10  3     0.0055     0.0008    6.7x    10    10     OK
Dodecahedral               20  3     0.0124     0.0020    6.1x    20    20     OK
Icosahedral                12  5     0.0065     0.0008    8.3x    12    12     OK
Tutte                      46  3     0.0604     0.0104    5.8x    70    70     OK
Heawood                    14  3     0.0062     0.0013    4.7x    14    14     OK
Pappus                     18  3     0.0098     0.0014    6.9x    18    18     OK
Desargues                  20  3     0.0114     0.0017    6.6x    20    20     OK
Möbius-Kantor              16  3     0.0074     0.0010    7.3x    16    16     OK
Tetrahedral                 4  3     0.0000     0.0000     n/a     0     0     OK
Octahedral                  6  4     0.0009     0.0001    8.7x     3     3     OK
Cubical                     8  3     0.0021     0.0003    6.9x     8     8     OK
Cycle C5                    5  2     0.0008     0.0001    5.3x     5     5     OK
Cycle C10                  10  2     0.0039     0.0009    4.4x    35    35     OK
Cycle C20                  20  2     0.0186     0.0022    8.5x   170   170     OK
Wheel W8                    8  3     0.0021     0.0003    6.5x    14    14     OK
Wheel W15                  15  3     0.0096     0.0010    9.3x    77    77     OK
K3,3                        6  3     0.0009     0.0001    9.8x     2     2     OK
K3,5                        8  3     0.0009     0.0001   14.2x     1     1     OK
K4,4                        8  4     0.0020     0.0001   14.5x     2     2     OK
Hypercube Q3                8  3     0.0020     0.0002    8.8x     8     8     OK
Hypercube Q4               16  4     0.0097     0.0039    2.5x    16    16     OK
Grid 4x4                   16  2     0.0040     0.0009    4.7x     4     4     OK
Grid 5x5                   25  2     0.0084     0.0019    4.5x     4     4     OK
Grid 8x8                   64  2     0.0607     0.0174    3.5x     4     4     OK
Circ. ladder 10            20  3     0.0126     0.0018    6.9x    20    20     OK
Circ. ladder 15            30  3     0.0299     0.0041    7.3x    30    30     OK
GNP(50,0.1)                50  2     0.0334     0.0110    3.0x     5     5     OK
GNP(30,0.3)                30  5     0.0382     0.0048    8.0x     2     2     OK
GNP(40,0.15)               40  2     0.0280     0.0071    4.0x     1     1     OK
3-regular(30)              30  3     0.0262     0.0043    6.1x    34    34     OK
5-regular(20)              20  5     0.0220     0.0025    8.8x    20    20     OK
Barabási-Albert(40,2)      40  2     0.0225     0.0060    3.8x    15    15     OK
Barabási-Albert(50,3)      50  3     0.0464     0.0174    2.7x    24    24     OK
WS(30,4,0.3)               30  2     0.0117     0.0029    4.1x     1     1     OK
WS(40,6,0.2)               40  4     0.0490     0.0115    4.3x     2     2     OK
Karate club                34  1     0.0093     0.0000  571.7x     1     1     OK
Les Misérables             77  1     0.2091     0.0001 1905.4x     8     8     OK
Florentine families        15  1     0.0022     0.0000  105.4x     4     4     OK
Bull graph                  5  1     0.0004     0.0000   39.9x     2     2     OK
Chvátal                    12  4     0.0058     0.0025    2.3x    12    12     OK
Frucht                     12  3     0.0050     0.0008    6.3x    30    30     OK
Sedgewick maze              8  1     0.0007     0.0000   84.4x     1     1     OK
Star S10                   11  1     0.0007     0.0000  108.7x     1     1     OK
---------------------------------------------------------------------------------
Total: 43 graphs — 43 OK, 0 FAILED

Connectivity ranges from 1 to 5, cut counts from 0 to 170, graph sizes from 4 to 77 nodes. All correct.

Performance scaling and crossover with igraph

To understand where pure-Python NetworkX catches up with igraph's C implementation, we ran scaling benchmarks across seven graph families, varying size systematically.

Scaling benchmark script
import timeit
import igraph as ig
import networkx as nx


def runit(name, g):
    if not nx.is_connected(g):
        cc = max(nx.connected_components(g), key=len)
        g = g.subgraph(cc).copy()
    k = nx.node_connectivity(g)
    if nx.density(g) == 1:
        return dict(name=name, n=len(g), k=k, nx_t=0, ig_t=0,
                    nx_count=0, ig_count=0, match=True)
    h = ig.Graph.from_networkx(g)

    nx_cuts = []
    def run_nx():
        nx_cuts.clear()
        nx_cuts.extend(list(nx.all_node_cuts(g)))
    t_nx = timeit.timeit(run_nx, number=1)

    ig_cuts = []
    def run_ig():
        ig_cuts.clear()
        ig_cuts.extend(ig.GraphBase.minimum_size_separators(h))
    t_ig = timeit.timeit(run_ig, number=1)

    node_list = list(g.nodes())
    ig_set = set(frozenset(node_list[idx] for idx in cut) for cut in ig_cuts)
    nx_set = set(frozenset(cut) for cut in nx_cuts)

    return dict(name=name, n=len(g), k=k, nx_t=t_nx, ig_t=t_ig,
                nx_count=len(nx_set), ig_count=len(ig_set),
                match=ig_set == nx_set)


def run_family(label, gen_func, sizes):
    print(f"\n=== {label} ===")
    print(f"{'size':>6} {'n':>5} {'k':>2} {'NX(s)':>9} {'ig(s)':>9} "
          f"{'ratio':>7} {'#cuts':>6} {'ok':>4}")
    print("-" * 52)
    for s in sizes:
        g = gen_func(s)
        r = runit(label, g)
        ratio = r["nx_t"] / r["ig_t"] if r["ig_t"] > 0 else float("inf")
        marker = ("<--" if 0.95 < ratio < 1.05
                  else ("*** NX WINS" if ratio < 1.0 else ""))
        print(f"{s:>6} {r['n']:>5} {r['k']:>2} {r['nx_t']:>9.4f} "
              f"{r['ig_t']:>9.4f} {ratio:>6.2f}x {r['nx_count']:>6} "
              f"{'OK' if r['match'] else 'FAIL':>4} {marker}", flush=True)


run_family("Grid NxN (k=2, 4 cuts)",
           lambda s: nx.grid_2d_graph(s, s),
           [5, 8, 10, 12, 14, 15, 16, 17, 18, 20, 22, 25])

run_family("3-regular (k=3)",
           lambda s: nx.random_regular_graph(3, s, seed=42),
           [20, 40, 60, 80, 100, 130, 160, 200])

run_family("BA(n,2) (k=2)",
           lambda s: nx.barabasi_albert_graph(s, 2, seed=42),
           [20, 40, 60, 80, 100, 130, 160, 200])

run_family("BA(n,3) (k=3)",
           lambda s: nx.barabasi_albert_graph(s, 3, seed=42),
           [20, 40, 60, 80, 100, 130, 160])

run_family("Circ. ladder (k=3, #cuts=n)",
           lambda s: nx.circular_ladder_graph(s),
           [10, 20, 30, 50, 70, 100, 130, 160])

run_family("Cycle (k=2, many cuts)",
           lambda s: nx.cycle_graph(s),
           [10, 20, 30, 40, 50, 70, 100])

run_family("WS(n,4,0.3) (k~2)",
           lambda s: nx.watts_strogatz_graph(s, 4, 0.3, seed=42),
           [20, 40, 60, 80, 100, 130, 160, 200])

Grid NxN (k=2, 4 cuts)

Few minimum cuts, cost dominated by flow computations. NX overtakes igraph at ~300 nodes.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
     5    25  2    0.0194    0.0040   4.82x      4   OK
     8    64  2    0.1122    0.0409   2.74x      4   OK
    10   100  2    0.2793    0.0963   2.90x      4   OK
    12   144  2    0.2794    0.1630   1.71x      4   OK
    14   196  2    0.5403    0.3826   1.41x      4   OK
    15   225  2    0.7246    0.5700   1.27x      4   OK
    16   256  2    0.8919    0.7738   1.15x      4   OK
    17   289  2    1.1621    1.0826   1.07x      4   OK
    18   324  2    1.4433    1.5444   0.93x      4   OK *** NX WINS
    20   400  2    2.4203    2.8882   0.84x      4   OK *** NX WINS
    22   484  2    3.5083    4.9749   0.71x      4   OK *** NX WINS
    25   625  2    5.6041   10.6416   0.53x      4   OK *** NX WINS

Barabasi-Albert m=2 (k=2)

Scale-free graphs with moderate cut counts. Crossover at ~200 nodes.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    20    20  2    0.0066    0.0016   4.05x      8   OK
    40    40  2    0.0228    0.0062   3.67x     15   OK
    60    60  2    0.0475    0.0195   2.43x     26   OK
    80    80  2    0.0877    0.0400   2.19x     34   OK
   100   100  2    0.1223    0.0740   1.65x     46   OK
   130   130  2    0.2117    0.1586   1.33x     63   OK
   160   160  2    0.3159    0.2953   1.07x     78   OK
   200   200  2    0.5070    0.5491   0.92x     96   OK *** NX WINS

Watts-Strogatz (k~2, few cuts)

Small-world graphs with very few cuts. Crossover at ~160 nodes.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    20    20  2    0.0051    0.0012   4.40x      1   OK
    40    40  2    0.0197    0.0060   3.28x      1   OK
    60    60  2    0.0425    0.0176   2.42x      2   OK
    80    80  2    0.0782    0.0400   1.95x      5   OK
   100   100  2    0.1122    0.0779   1.44x      8   OK
   130   130  2    0.1823    0.1549   1.18x     11   OK
   160   160  2    0.2766    0.2837   0.98x      6   OK <-- ~parity
   200   200  2    0.4283    0.5270   0.81x     11   OK *** NX WINS

Barabasi-Albert m=3 (k=3)

Denser scale-free, approaching crossover at ~200 nodes.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    20    20  3    0.0079    0.0016   5.02x      9   OK
    40    40  3    0.0293    0.0080   3.65x     17   OK
    60    60  3    0.0648    0.0247   2.62x     29   OK
    80    80  3    0.1153    0.0542   2.13x     36   OK
   100   100  3    0.1735    0.0993   1.75x     42   OK
   130   130  3    0.3033    0.2048   1.48x     56   OK
   160   160  3    0.4367    0.3782   1.15x     65   OK

3-regular (k=3)

Regular graphs with many cuts. Ratio improving but crossover beyond n=200.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    20    20  3    0.0132    0.0022   6.05x     52   OK
    40    40  3    0.0408    0.0074   5.51x     40   OK
    60    60  3    0.0871    0.0190   4.58x     60   OK
    80    80  3    0.1485    0.0407   3.65x     92   OK
   100   100  3    0.2316    0.0700   3.31x    112   OK
   130   130  2    0.1541    0.1245   1.24x      4   OK
   160   160  3    0.6244    0.2645   2.36x    160   OK
   200   200  3    0.9314    0.4778   1.95x    208   OK

Circular ladder (k=3, #cuts = n)

Number of cuts grows linearly with size. Crossover projected around n=400.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    10    20  3    0.0125    0.0018   7.02x     20   OK
    20    40  3    0.0469    0.0073   6.42x     40   OK
    30    60  3    0.1068    0.0211   5.08x     60   OK
    50   100  3    0.2876    0.0905   3.18x    100   OK
    70   140  3    0.5595    0.2146   2.61x    140   OK
   100   200  3    1.3074    0.6339   2.06x    200   OK
   130   260  3    2.1129    1.3559   1.56x    260   OK
   160   320  3    3.3399    2.6468   1.26x    320   OK

Cycle (k=2, many cuts)

Number of cuts grows quadratically (~n^2/4). igraph's C based implementation dominates.

  size     n  k     NX(s)     ig(s)   ratio  #cuts   ok
----------------------------------------------------
    10    10  2    0.0046    0.0010   4.75x     35   OK
    20    20  2    0.0197    0.0024   8.13x    170   OK
    30    30  2    0.0504    0.0056   8.99x    405   OK
    40    40  2    0.1118    0.0105  10.63x    740   OK
    50    50  2    0.1913    0.0186  10.26x   1175   OK
    70    70  2    0.4641    0.0499   9.29x   2345   OK
   100   100  2    1.2954    0.1550   8.36x   4850   OK

Summary

Graph family Crossover (NX ~ igraph) Determining factor
Grid NxN ~300 nodes (18x18) Few cuts (4), flow-dominated
Watts-Strogatz ~160 nodes Few cuts, sparse
Barabasi-Albert m=2 ~200 nodes Moderate cuts, sparse
Barabasi-Albert m=3 ~200+ nodes Approaching at n=160
3-regular >200 nodes High cut count slows convergence
Circular ladder ~400+ nodes Cuts grow linearly with n
Cycles No crossover Cuts grow quadratically (~n^2/4)

The pattern: NX overtakes igraph when the number of minimum cuts is small relative to graph size. For sparse, real-world-like graphs (grids, scale-free, small-world) with few cuts, NX wins at 150-300 nodes. When cuts grow with n (circular ladders) the crossover moves higher. When cuts grow quadratically (cycles), igraph's C based implementation keeps the advantage.

All 61 graphs tested: 100% correctness match with igraph.

@dschult

dschult commented Mar 27, 2026

Copy link
Copy Markdown
Member

Hello @jtorrents !!!! Welcome Back!
Hope all is well with you!

Your explanations make good sense -- and the outcome looks promising.
I will try to dive into it more next week.

Thanks!!

@jtorrents

Copy link
Copy Markdown
Member Author

Hi @dschult !! Very nice to talk to you after such a long time. All is well! Thanks.

Glad to to be back and be able to contribute a bit again, at least help squashing my own bugs ;)

NetworkX is better than ever. You and the rest of NetworkX maintainers are doing a terrific job!

…ithm.

The Even-Tarjan auxiliary digraph built by
build_auxiliary_node_connectivity sets capacity=1 on all edges. This is
correct for computing the node connectivity value, but Kanevsky's
algorithm depends on the structure of the residual graph, which requires
infinite capacity on external edges as the original Even-Tarjan
reduction specifies.

With unit-capacity external edges, these edges get saturated by the flow,
producing a residual graph with the wrong structure. The condensation DAG
has too many nodes, and the antichain count explodes exponentially.

This bug (introduced by me in the original NetworkX implementation) was
not identified when correctness bugs were reported in networkx#3025. The fix in
PR networkx#3039 addressed the symptoms (missing cuts) by adding compensating
filters: VE1 incident-node filtering, transitive closure on the full
residual graph, and internal-edge validation; and also introduced two
additional bugs:

- Removing backward arcs from the residual graph (capacity=0 edges with
  negative flow that represent cancellable flow and must be preserved)
- Building closed sets using predecessors instead of successors in the
  condensation DAG, producing the wrong side of the cut partition

These filters discarded most of the millions of spurious antichains
generated by the broken condensation DAG, making results mostly correct
but at enormous computational cost.

This fix addresses the root cause and restores the algorithm to match the
paper's specification:
- Set infinite capacity on external edges before building the residual
- Remove only edges with zero residual capacity (capacity == flow)
- Build successor-closed sets from antichins of the condensation DAG
- Find cut edges from S to ~S using H successors.

The compensating code is no longer needed and has been removed.

Performance on grid_2d_graph(11,11) improves from 180s to 0.16s (n=121)
(1000x+), and now scales polynomially as predicted by the paper. Results
verified identical to igraph's C implementation at all tested sizes.

Fixes networkx#7994.

Tests previously marked @pytest.mark.slow are now fast enough to run by
default, and MAX_CUTSETS_TO_TEST is restored from 4 to 100.
@jtorrents
jtorrents force-pushed the fix-all-node-cuts branch from 9ba9555 to 7c46600 Compare April 1, 2026 17:48
@jtorrents

Copy link
Copy Markdown
Member Author

I squashed the two commits into one and force-pushed to my branch because I inadvertently used my work email in the author field for the two original commits.

@rossbar rossbar left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is excellent @jtorrents , thanks so much for putting in all the effort to clearly and concretely summarize the underlying problem (a very interesting read) and how it is addressed directly by these changes.

With unit-capacity external edges, these edges get saturated by the flow, producing a residual graph with the wrong structure. The condensation DAG has too many nodes, and the antichain count explodes exponentially.

It's not often that issues can be cleanly traced back to so concise an algorithmic detail, which then can be fixed up so neatly. This is a very satisfying outcome! The subsequent analysis (and removal) of the ad-hoc patches that were added to try to address the symptoms of the underlying issue is similarly very interesting - thanks for including in the writeup!

Tests previously marked @pytest.mark.slow are now fast enough to run by default, and MAX_CUTSETS_TO_TEST is restored from 4 to 100.

IMO this is more than sufficient to test the fact that the scaling issue has been fixed, even though it's only indirect.

As a AI disclaimer: I used Claude to explore the problem, build many scripts that printed step by step the state of the data structures used, create benchmarks that compare time and correctness between the old implementation, these fixes, and iGraph. In summary, Claude has been instrumental for fixing this long standing bug (introduced by yours truly nine years ago).

I just wanted to take the opportunity to highlight that this PR is perfectly in-line with NetworkX's ai policy and is an obvious example of a positive outcome. IMO as a reviewer, the thing that makes this PR great is not the code that was written but how well the underlying issue and solution were communicated. The work done in this PR to highlight not only the root-cause of the issue, but also the development history surrounding attempts at patching the symptoms of the original bug, really helps drive home that the problem has been wholistically understood, digested, and addressed in an effective way. It provides excellent context that really helps in reviewing and building confidence that this is a (if not the) correct way of addressing the issue.


I can't claim to be an expert in Kanevsky's algorithm, but the code changes are consistent with the description of the underlying issue and the outcomes (both in the test suite and in the PR description) are quite compelling that this does indeed fix the reported algorithm scaling issues. Thanks again @jtorrents for putting so much thought/effort into communication in this great PR!

@jtorrents

Copy link
Copy Markdown
Member Author

Thanks for the kind words @rossbar ! It's been a tough bug to squash, and getting to the bottom of it was not easy. The key was looking at the internal state of data structures at each step of the algorithm.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks very much for this @jtorrents !!

The speed up makes these methods usable. And the correctness is of course the fundamental goal. So tracing through the patches made for correctness to find the underlying issue is really impressive and appreciated.

We should make a splash about this improvement in the release notes, too when the time comes for that.. :)

@dschult
dschult merged commit 9150d1e into networkx:main Apr 10, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone Apr 10, 2026
dschult pushed a commit that referenced this pull request Jul 24, 2026
…s the private helpers (#8753)

* Drop nested components in reconstruction, add doctest

A single _consolidate pass merges on pairwise overlaps of its input
sets, so a level can still end up containing a component that is a
strict subset of a merged one: a propagated (k+1)-level component
sharing fewer than k nodes with each of two level-k candidates is not
merged with their union. Drop such nested sets at each level; every
emitted set is k-connected, so a nested one is never maximal. This
completes the more permissive propagation introduced by #8734 (which
is preserved verbatim) and turns the never-observed redundant-subset
scenario into a structural impossibility. No known construction
reaches it; validated with the full suite plus differential and
brute-force fuzzing.

Also turn the k_components docstring example into a real doctest.

* Add unit tests for private k-components helpers

Follow-up to the #8734 review discussion: both bugs fixed there lived
in private helpers whose contracts were only implicit, and neither was
reachable by end-to-end tests on the small classic graphs alone. State
the contracts explicitly and test the helpers directly:

- _reconstruct_k_components propagates a (k+1)-level component that
  spans several k-level candidates (the #8734 fix), drops a component
  nested inside a consolidated merge (the fix in this branch; the test
  synthesizes the input that graph-level fuzzing never produced and
  fails without the fix), and never emits a component that is a strict
  subset of another at the same level.
- _generate_partition never loses a node, yields only strict subsets of
  the input, and every part induces a connected subgraph.

* Remove slow markers from k_components tests

The three pytest.mark.slow markers predate the all_node_cuts fix
(#8586), which is what made these tests slow. The whole file now runs
in under 2 seconds with --runslow and the slowest single test
(test_random_gnp[50-0.2]) takes under a second, so run the complete
k_components suite by default.

* Use the Davis Southern Women graph in the partition test

Replace the parametrized contract test for _generate_partition with a
single explicit example, as suggested in review. The Davis Southern
Women graph is biconnected, so no bicomponent loop or conditionals are
needed, and every expected value is stated explicitly: the node
connectivity, the two minimum cutsets, and the exact four parts. The
pre-gh-8734 code silently dropped the three women that attended only
cutset events. Also drop a redundant comment block above the
private-helper unit tests.

* Restore the slow markers on the k_components tests

This reverts commit ae5d6af, as agreed
in review: keep the slow marks for now, and revisit removing them in a
separate PR once the k_components work has been merged, so that the
effect on CI test balance can be evaluated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

all_node_cuts() performance degrades much faster than predicted by Kanevsky's minimum cut algorithm

3 participants