TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Connectivity in Dynamic Streams: The AGM Sketch

Connectivity in Dynamic Streams: The AGM Sketch

Union-find computes connectivity in one pass, but only if edges are never deleted: once two components are merged, a later deletion of the edge that merged them cannot be undone without knowing which other edges connect them. For years it was open whether connectivity of a dynamic graph stream, with insertions and deletions, could be computed in semi-streaming space at all. Ahn, Guha and McGregor (2012) showed that it can, with a beautifully simple idea: a linear sketch of each vertex's neighbourhood, built so that adding the sketches of a set of vertices cancels the edges inside the set and leaves exactly the edges leaving it. An ℓ0\ell_0-sampler then finds one such edge, and Borůvka's algorithm does the rest.

Signed incidence vectors

Index the possible edges {u,v}\{u, v\}, u<vu < v, by the pairs of vertices, so a vector over edges has (n2)\binom{n}{2} coordinates. For each vertex vv define the signed incidence vector ava_v:

av[{u,w}]={+1if {u,w}∈E, v=u<w,−1if {u,w}∈E, u<w=v,0otherwise.a_v[\{u, w\}] = \begin{cases} +1 & \text{if } \{u, w\} \in E,\ v = u < w, \\ -1 & \text{if } \{u, w\} \in E,\ u < w = v, \\ 0 & \text{otherwise.} \end{cases}

Each edge appears in exactly two incidence vectors, with opposite signs.

Lemma. For every set SS of vertices, the support of ∑v∈Sav\sum_{v \in S} a_v is exactly the set of edges with one end in SS and the other outside, E(S,V∖S)E(S, V \setminus S).

Proof. An edge with both ends in SS contributes +1+1 and −1-1, which cancel. An edge with one end in SS contributes ±1\pm 1 once. An edge with no end in SS contributes nothing. □\square

Now the streaming part: an edge insertion (u,v,+1)(u, v, +1) adds +1+1 to one coordinate of aua_u and −1-1 to one coordinate of ava_v; a deletion subtracts the same. So ava_v is a turnstile vector, and an ℓ0\ell_0-sampler sketch S(av)\mathcal{S}(a_v) of it can be maintained, using the same random hash functions for all vertices. Because the sketch is linear, ∑v∈SS(av)=S(∑v∈Sav)\sum_{v \in S}\mathcal{S}(a_v) = \mathcal{S}(\sum_{v \in S} a_v): from the stored per-vertex sketches, one can sample an edge leaving any set SS, chosen after the stream has ended.

Borůvka on sketches

Borůvka's algorithm (1926) builds a spanning forest in rounds: in each round, every current component picks one edge leaving it, and all picked edges are added, merging components. Each round at least halves the number of components that are not yet complete, so O(log⁡n)O(\log n) rounds suffice.

text
AGM connectivity (Ahn, Guha and McGregor, 2012)
stream:  for each vertex v and round r = 1..R, keep an ℓ0-sampler sketch S_r(a_v)   (R = O(log n))
         an update (u, v, ±1) changes S_r(a_u) and S_r(a_v) in every round r
query:   C ← the singletons {v}
         for r = 1..R:
             for each component C in C:  sample an edge from  Σ_{v ∈ C} S_r(a_v)   (an edge leaving C)
             merge the components along the sampled edges
         return C

Each round uses fresh sketches: the components of round rr depend on the samples of earlier rounds, and a sketch whose randomness the algorithm has already looked at would no longer be independent of the sets it is queried on. With R=O(log⁡n)R = O(\log n) rounds, each sketch of O(log⁡2n)O(\log^2 n) bits for constant failure probability (boosted to 1/poly⁡(n)1/\operatorname{poly}(n) with O(log⁡n)O(\log n) repetitions), the total is:

Theorem (Ahn, Guha and McGregor, 2012). In the dynamic graph stream model, the connected components (and a spanning forest) of an nn-vertex graph can be computed with high probability from a linear sketch of O(nlog⁡3n)O(n \log^3 n) bits, in one pass.

The program runs the whole pipeline on a 48-vertex graph of three clusters joined by three bridges: 191 edge insertions, then 97 deletions, including two of the bridges. Each vertex keeps 7 rounds of 4 independent samplers with 12 subsampling levels each.

python · try it yourself
import random

P = (1 << 61) - 1
MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

n = 48
ROUNDS, REPS, LEVELS = 7, 4, 12              # rounds of Boruvka, samplers per round, subsampling levels
rng = random.Random(2012)
salt = [[rng.getrandbits(64) for _ in range(REPS)] for _ in range(ROUNDS)]   # shared by all vertices
fsalt = rng.getrandbits(64)

def edge_id(u, v):
    return u * n + v                         # u < v

def new_sketch():                            # [round][rep][level] -> [s0, s1, s2]
    return [[[[0, 0, 0] for _ in range(LEVELS)] for _ in range(REPS)] for _ in range(ROUNDS)]

sk = [new_sketch() for _ in range(n)]

def add_to(S, e, d):
    r_e = mix64(e ^ fsalt) % P
    for r in range(ROUNDS):
        for q in range(REPS):
            h = mix64(e ^ salt[r][q])
            for j in range(LEVELS):
                c = S[r][q][j]
                c[0] += d; c[1] += d * e; c[2] = (c[2] + d * r_e) % P
                if h >> j & 1:
                    break

def update(u, v, d):                         # edge (u, v) inserted (d = +1) or deleted (d = -1)
    u, v = min(u, v), max(u, v)
    add_to(sk[u], edge_id(u, v), +d)         # the incidence vector of u gets +1 on the edge ...
    add_to(sk[v], edge_id(u, v), -d)         # ... and that of v gets -1, so it cancels inside a set

def sample_cut_edge(vertices, r):
    """Add the round-r sketches of a vertex set; any recovered edge leaves the set."""
    for q in range(REPS):
        for j in range(LEVELS):
            s0 = sum(sk[v][r][q][j][0] for v in vertices)
            s1 = sum(sk[v][r][q][j][1] for v in vertices)
            s2 = sum(sk[v][r][q][j][2] for v in vertices) % P
            if s0 in (1, -1) and s2 == s0 * (mix64(s1 * s0 ^ fsalt) % P) % P:
                e = s1 * s0
                return divmod(e, n)
    return None

# a dynamic stream: three dense clusters plus bridges, then most edges and two bridges deleted
clusters = [range(0, 16), range(16, 32), range(32, 48)]
edges = set()
for C in clusters:
    for _ in range(90):
        u, v = rng.sample(list(C), 2)
        edges.add((min(u, v), max(u, v)))
bridges = {(5, 20), (12, 40), (30, 33)}
edges |= bridges
for u, v in edges:
    update(u, v, +1)
deleted = set(rng.sample(sorted(edges - bridges), len(edges) // 2)) | {(5, 20), (12, 40)}
for u, v in deleted:
    update(u, v, -1)
final = edges - deleted

# Boruvka on the sketches: each round, every component samples an edge leaving it
comp = {v: v for v in range(n)}
for r in range(ROUNDS):
    groups = {}
    for v in range(n):
        groups.setdefault(comp[v], []).append(v)
    merged = 0
    for leader, verts in groups.items():
        e = sample_cut_edge(verts, r)
        if e:
            a, b = comp[e[0]], comp[e[1]]
            if a != b:
                for v in range(n):
                    if comp[v] == b:
                        comp[v] = a
                merged += 1
    print(f"round {r}: {len(groups)} components before, {merged} merges")
# exact answer from the final edge set
exact = {v: v for v in range(n)}
def find(x):
    while exact[x] != x:
        x = exact[x]
    return x
for u, v in final:
    exact[find(u)] = find(v)
sketch_parts = sorted(sorted(v for v in range(n) if comp[v] == c) for c in set(comp.values()))
exact_parts = sorted(sorted(v for v in range(n) if find(v) == c) for c in {find(v) for v in range(n)})
print(f"{len(edges)} edges inserted, {len(deleted)} deleted, {len(final)} remain")
print("components from the sketches == exact components:", sketch_parts == exact_parts,
      f"({len(sketch_parts)} components, sizes {[len(p) for p in sketch_parts]})")
words = n * ROUNDS * REPS * LEVELS * 3
print(f"sketch size: {words} numbers in total, {words // n} per vertex; the graph has up to {n * (n - 1) // 2} edges")
round 0: 48 components before, 36 merges
round 1: 12 components before, 9 merges
round 2: 3 components before, 1 merges
round 3: 2 components before, 0 merges
round 4: 2 components before, 0 merges
round 5: 2 components before, 0 merges
round 6: 2 components before, 0 merges
191 edges inserted, 97 deleted, 94 remain
components from the sketches == exact components: True (2 components, sizes [16, 32])
sketch size: 48384 numbers in total, 1008 per vertex; the graph has up to 1128 edges

The sketches found the right two components, though no edge list was ever stored and half of the edges, including two bridges, were deleted after insertion. At this tiny size the sketches are not smaller than the graph (1008 numbers per vertex against at most 47 possible edges), because the log⁡3n\log^3 n factor with its constants dominates; the point is the scaling, O(log⁡3n)O(\log^3 n) per vertex against up to n−1n - 1 edges per vertex.

In C++

The same sketch for 300 vertices, 9 rounds of 4 samplers with 16 levels: random edges are inserted and then 80% of them deleted, and the components recovered from the sketches are compared with the exact ones.

cpp · try it yourself
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <numeric>
#include <random>
#include <set>
#include <utility>
#include <vector>

std::uint64_t mix64(std::uint64_t x) {
    x += 0x9E3779B97F4A7C15ULL;
    x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
    x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
    return x ^ (x >> 31);
}
constexpr std::uint64_t P = (1ULL << 61) - 1;
constexpr int ROUNDS = 9, REPS = 4, LEVELS = 16;

struct Cell { std::int64_t s0 = 0, s1 = 0; std::uint64_t s2 = 0; };
using Sketch = std::vector<Cell>;                            // ROUNDS * REPS * LEVELS cells
int idx(int r, int q, int j) { return (r * REPS + q) * LEVELS + j; }

struct AGM {
    int n;
    std::uint64_t salt[ROUNDS][REPS], fsalt;
    std::vector<Sketch> sk;
    AGM(int n, std::mt19937_64& rng) : n(n), sk(n, Sketch(ROUNDS * REPS * LEVELS)) {
        for (auto& row : salt) for (auto& s : row) s = rng();
        fsalt = rng();
    }
    void add(Sketch& S, std::int64_t e, std::int64_t d) {
        std::uint64_t re = mix64(e ^ fsalt) % P;
        for (int r = 0; r < ROUNDS; ++r)
            for (int q = 0; q < REPS; ++q) {
                std::uint64_t h = mix64(e ^ salt[r][q]);
                for (int j = 0; j < LEVELS; ++j) {
                    Cell& c = S[idx(r, q, j)];
                    c.s0 += d; c.s1 += d * e;
                    c.s2 = (c.s2 + (d > 0 ? re : P - re)) % P;
                    if (h >> j & 1) break;
                }
            }
    }
    void update(int u, int v, int d) {                       // +1 insert, -1 delete
        if (u > v) std::swap(u, v);
        std::int64_t e = (std::int64_t)u * n + v;
        add(sk[u], e, d);
        add(sk[v], e, -d);                                    // opposite sign: cancels inside a set
    }
    std::vector<int> components() {
        std::vector<int> comp(n);
        std::iota(comp.begin(), comp.end(), 0);
        for (int r = 0; r < ROUNDS; ++r) {
            std::vector<Sketch> sum(n, Sketch(REPS * LEVELS));   // round-r part, summed per component
            for (int v = 0; v < n; ++v)
                for (int k = 0; k < REPS * LEVELS; ++k) {
                    Cell& a = sum[comp[v]][k]; const Cell& b = sk[v][r * REPS * LEVELS + k];
                    a.s0 += b.s0; a.s1 += b.s1; a.s2 = (a.s2 + b.s2) % P;
                }
            std::vector<int> leaders(comp.begin(), comp.end());
            std::sort(leaders.begin(), leaders.end());
            leaders.erase(std::unique(leaders.begin(), leaders.end()), leaders.end());
            for (int L : leaders)
                for (const Cell& c : sum[L]) {
                    if (c.s0 != 1 && c.s0 != -1) continue;
                    std::int64_t e = c.s1 * c.s0;
                    std::uint64_t re = mix64(e ^ fsalt) % P;
                    if (c.s2 != (c.s0 == 1 ? re : P - re)) continue;
                    int a = comp[e / n], b = comp[e % n];       // a cut edge: merge the two components
                    if (a != b) for (int& x : comp) if (x == b) x = a;
                    break;
                }
        }
        return comp;
    }
};

int main() {
    const int n = 300;
    std::mt19937_64 rng(2012), gen(7);   // sketch randomness, graph generator
    AGM agm(n, rng);
    std::set<std::pair<int, int>> edges;
    for (int t = 0; t < 3000; ++t) {                          // random insertions ...
        int u = gen() % n, v = gen() % n;
        if (u == v) continue;
        auto e = std::minmax(u, v);
        if (edges.insert(e).second) agm.update(e.first, e.second, +1);
    }
    std::vector<std::pair<int, int>> all(edges.begin(), edges.end());
    for (std::size_t i = all.size() - 1; i > 0; --i) std::swap(all[i], all[gen() % (i + 1)]);   // Fisher-Yates
    for (std::size_t i = 0; i < all.size() * 4 / 5; ++i) {   // ... then 80% of them deleted
        agm.update(all[i].first, all[i].second, -1);
        edges.erase(all[i]);
    }
    std::vector<int> uf(n);                                   // exact components of what remains
    std::iota(uf.begin(), uf.end(), 0);
    auto find = [&](int x) { while (uf[x] != x) x = uf[x] = uf[uf[x]]; return x; };
    for (auto [u, v] : edges) uf[find(u)] = find(v);
    auto comp = agm.components();
    bool same = true;
    for (int u = 0; u < n; ++u)
        for (int v = 0; v < n; ++v) same &= (find(u) == find(v)) == (comp[u] == comp[v]);
    std::set<int> cs(comp.begin(), comp.end());
    std::printf("%zu edges remain after deletions; sketch components: %zu; equal to exact: %s\n",
        edges.size(), cs.size(), same ? "yes" : "no");
}
579 edges remain after deletions; sketch components: 9; equal to exact: yes

Beyond connectivity

The signed-incidence trick extends to many problems, all in O(npolylog⁡n)O(n \operatorname{polylog} n) space in dynamic streams (Ahn, Guha and McGregor, 2012, and follow-up papers):

  • Bipartiteness: GG is bipartite exactly when its bipartite double cover (two copies v1,v2v_1, v_2 of each vertex, an edge {u,v}\{u, v\} becoming {u1,v2}\{u_1, v_2\} and {u2,v1}\{u_2, v_1\}) has twice as many components as GG. Run AGM on both graphs.
  • kk-edge-connectivity: repeat kk times, each time sampling a spanning forest of the edges not yet used (the sketch of the used forest is subtracted, by linearity). The union of kk such forests certifies kk-connectivity (a construction of Nagamochi and Ibaraki).
  • Minimum spanning tree within 1+ε1 + \varepsilon: group edges by weight into powers of 1+ε1 + \varepsilon and count components of the graphs of the lighter classes.
  • Cut and spectral sparsifiers in dynamic streams, by sampling edges according to their connectivity at several scales (Cut Sparsifiers).

The lower bound of Ω(nlog⁡n)\Omega(n \log n) bits for connectivity (Sun and Woodruff, 2015) shows that the nn factor is unavoidable even for insertion-only streams.

Test yourself

Why do the edges inside a vertex set SS disappear from ∑v∈Sav\sum_{v \in S} a_v?

  1. They are deleted from the stream
  2. Each edge appears in the incidence vectors of its two ends with opposite signs, +1+1 and −1-1, which cancel when both ends are in SS
  3. The sampler ignores them
  4. Because SS is a component

Why does the AGM algorithm use fresh sketches in every Borůvka round?

  1. To save memory
  2. Because the components of a round depend on earlier samples, and a sketch must be independent of the sets it is queried on for its guarantee to hold
  3. Because sketches expire
  4. Because the graph changes between rounds

How much space does the AGM connectivity sketch use?

  1. O(log⁡n)O(\log n) bits
  2. O(nlog⁡3n)O(n \log^3 n) bits: O(log⁡n)O(\log n) rounds of ℓ0\ell_0-samplers of O(log⁡2n)O(\log^2 n) bits per vertex
  3. O(n2)O(n^2) bits
  4. O(m)O(m) bits