Algorithm Search⌘K

Algorithmresearch

Schism workload-driven partitioning

Also called Schism.

Partition and replicate tuples by a balanced min cut of a graph that joins tuples used by one transaction, then explain the cut as range predicates. A heuristic for few distributed transactions.

Time
O(m d + m k) worst
Space
O(m d) extra
Where
d = the largest number of tuples in one transaction; k = the number of parts; m = the number of accesses in the workload, the sum of the sizes of the transactions
Properties
deterministicnot exactnot in placeofflineiterative
Origin
Carlo Curino, Evan Jones, Yang Zhang, Sam Madden, 2010

Schism chooses where each tuple of an OLTP database lives on a shared-nothing cluster, so that few transactions need more than one node. It reads a trace of the workload and builds a graph with a node for each tuple and an edge for each pair of tuples that a transaction uses together. A balanced min cut of this graph, found with METIS, gives a fine-grained placement, and a star for each tuple lets the cut decide which tuples to copy. A decision tree then explains the placement as a few range predicates on the attributes, and a last check keeps whichever of the candidates causes the fewest distributed transactions. Every step after the graph is a heuristic.

In plain words

A bank spreads its accounts over several servers. A transfer that touches two accounts on two servers is slow, because the servers must agree before they commit. Schism looks at a log of real transactions and draws a line between every two records that one transaction used. Records that are used together a lot get thick lines. It then cuts the drawing into equal pieces while it cuts as few thick lines as it can, and each piece goes to one server. A record that many transactions read but few change can be copied to several servers. Last, Schism looks for a simple rule, such as "accounts 1 to 1000 go to server 1", that gives about the same pieces, because a short rule is easier to keep than a list of every record.

The problem

The input is a database of tuples, a workload of mm accesses grouped into transactions, and a number of parts kk. Transaction xx reads a set R(x)R(x) and writes a set W(x)W(x) of tuples. A placement PP gives each tuple a nonempty set P(t)P(t) of parts that hold a copy. Transaction xx is local if one part pp holds a copy of every tuple of xx and every tuple that xx writes has the single copy {p}\{p\}, because a write must update every copy. Otherwise xx is distributed and needs a protocol such as two-phase commit.

The goal is a placement with few distributed transactions and parts of about equal load. The cost is a count of transactions, not of tuples or bytes; the network cost of a distributed transaction is not modelled. When every transaction touches two tuples and there is no replication, the cost is exactly the cut weight of the graph below, so the problem is close to the balanced graph partitioning problem, which is NP-hard. Schism uses heuristics and makes no claim of optimality. It is a case of horizontal fragmentation at the level of single tuples, chosen from the workload rather than from predicates written by a designer.

The algorithm

  1. SCHISM(D, workload, k)
  2. 1G ← a node for each touched tuple, weighted by its accesses; an edge {t, t'} weighted by the number of transactions that touch both
  3. 2if replication is allowed then replace each tuple t by a star: a center and a replica per transaction that touches t; the star edges weigh the number of writes of t; the edges of each transaction join its replicas
  4. 3π ← a balanced k-way partition of G with a small cut weight ▷ METIS in the paper
  5. 4lookup(t) ← the set of parts of the nodes of t in π
  6. 5tree ← a decision tree that predicts lookup(t) from the attributes of t
  7. 6for each candidate P in (hash, full replication, tree, lookup) do cost(P) ← the number of distributed transactions under P
  8. 7return the candidate with the smallest cost, the simplest one on a tie

The graph. Without replication, a cut edge {t,t′}\{t, t'\} means that its transactions touch two parts. With replication, tuple tt becomes a center ctc_t and one replica rt,xr_{t,x} for each transaction xx that touches it. The transaction edges join the replicas of one transaction. A star edge {ct,rt,x}\{c_t, r_{t,x}\} weighs u(t)u(t), the number of transactions that write tt. If the cut puts a replica in another part than its center, the tuple gets a second copy, and the cut pays u(t)u(t) for it: a copy is cheap for a tuple that is seldom written, and free for a tuple that is only read.

The partitioner. Line L3 is the graph partitioning problem with a balance bound: every part may weigh at most (1+ϵ)(1 + \epsilon) times the mean. The paper uses METIS, a multilevel partitioner. The implementation on this page does the same in a small form: heavy edge matching to coarsen the graph, a greedy start on the smallest graph, and a local search with moves and swaps in the style of Kernighan-Lin at each level on the way back.

The explanation. A lookup table with one entry per tuple is exact for the trace, but it is large, and it says nothing about tuples that the trace did not touch. Line L5 learns a decision tree on the attributes that the queries use in their predicates. Each leaf of the tree is a conjunction of range predicates, so the tree is a range partitioning that a router can store in a few lines.

The validation. Line L6 counts distributed transactions for each candidate on the workload, and line L7 keeps the best. If no candidate beats hash partitioning or full replication, Schism returns the simple scheme.

Example

A database has eight tuples. Tuples 1, 2 and 3 belong to warehouse 1, tuples 4, 5 and 6 to warehouse 2, and tuples 7 and 8 are items that nobody writes. There are k=2k = 2 parts and six transactions:

transaction reads writes
x1x_1 7 1, 2
x2x_2 8 2, 3
x3x_3 7 4, 5
x4x_4 8 5, 6
x5x_5 1, 3
x6x_6 4, 6

Without replication. The graph has 8 nodes and 14 edges of weight 1. The best balanced cut has weight 4: warehouse 1 with item 7 on one side and warehouse 2 with item 8 on the other, or a mirror of it. Both items do not fit on one side under the balance bound, so each item lives with one warehouse. The two transactions that read the item of the other warehouse, here x2x_2 and x3x_3, are distributed.

With replication. The graph has 24 nodes (8 centers and 16 replicas) and 26 edges of total weight 38. Each of the tuples 1 to 6 is written twice, so its two star edges weigh 2. The items are never written, so their stars have no edges. The partitioner finds a cut of weight 0: the two warehouses go to different parts, and each item gets a copy in both parts. Now no transaction is distributed.

Explanation and validation. The tree learned from the placement has three leaves: id≤3id \le 3 goes to the part of warehouse 1, 3<id≤63 < id \le 6 to the part of warehouse 2, and id>6id > 6 to both parts. The counts of distributed transactions are:

candidate without replication with replication
hash on id mod 2id \bmod 2 4 4
full replication 6 6
decision tree 2 0
lookup table 2 0

Full replication makes every transaction distributed, since every transaction writes. With replication, the tree ties with the lookup table and is simpler, so Schism returns the three range predicates. The tests of the implementation check every number in this example.

Correctness

Schism has no guarantee of optimality. What can be proved is the link between the cut and the cost, for any partition, on the proof page:

  • Theorem. Without replication, the number of distributed transactions is at most the cut weight, and the two are equal when every transaction touches at most two tuples.
  • Theorem. With the star graph, the number of distributed transactions under the placement of line L4 is again at most the cut weight. So a cut of weight 0 gives a placement where every transaction is local.
  • By construction. Line L7 never returns a placement that is worse on the trace than hash partitioning or full replication.

The cut can be much larger than the cost: a transaction with dd tuples split in two halves cuts up to d2/4d^2/4 of its own edges but counts once. This is why line L6 measures the real count.

Proof: The cut weight of the Schism graph is an upper bound on the number of distributed transactionsfull

We use the line numbers of the pseudocode on the page. A workload is a list of transactions x1,…,xmx_1, \dots, x_m. Transaction xx reads the set R(x)R(x) and writes the set W(x)W(x) of tuples, with R(x)∩W(x)=∅R(x) \cap W(x) = \emptyset, and touches T(x)=R(x)∪W(x)T(x) = R(x) \cup W(x). A placement PP maps each tuple tt to a nonempty set P(t)P(t) of parts. Transaction xx is local under PP if there is a part pp with p∈P(t)p \in P(t) for every t∈T(x)t \in T(x) and P(t)={p}P(t) = \{p\} for every t∈W(x)t \in W(x); otherwise xx is distributed. The definition says that a read can use any copy, and that a write must reach every copy.

For a partition π\pi of the nodes of a graph with edge weights ww, the cut weight is cut(π)=∑w(e)\mathrm{cut}(\pi) = \sum w(e) over the edges ee whose ends are in different parts. The statements below hold for every partition, so they hold for the partition of line L3 whatever partitioner computes it. They do not say that the partitioner finds a small cut: METIS, and the multilevel search of the implementation, are heuristics.

The graph without replication (line L1). It has a node for each touched tuple and, for two tuples t≠t′t \ne t', an edge of weight w(t,t′)=∣{x:t,t′∈T(x)}∣w(t, t') = |\{x : t, t' \in T(x)\}|. The placement of line L4 is P(t)={π(t)}P(t) = \{\pi(t)\}.

Theorem 1. For every partition π\pi of the graph of line L1, the number of distributed transactions under PP is at most cut(π)\mathrm{cut}(\pi). If every transaction touches at most two tuples, the two numbers are equal.

Proof. Every tuple has one copy, so xx is local exactly when all of T(x)T(x) lies in one part. Let xx be distributed. Then T(x)T(x) has two tuples in different parts, and we charge xx to the first such pair {t,t′}\{t, t'\} in a fixed order. The edge {t,t′}\{t, t'\} is cut. The transactions charged to it all touch both tt and t′t', so there are at most w(t,t′)w(t, t') of them. Summing over the cut edges gives the bound. If every transaction touches at most two tuples, a cut edge {t,t′}\{t, t'\} stands for exactly w(t,t′)w(t, t') transactions with T(x)={t,t′}T(x) = \{t, t'\}, and each of them is distributed; a transaction with one tuple adds no edge and is local. So each cut edge stands for exactly its weight in distributed transactions, and no distributed transaction is missed. □\square

The bound can be loose: a transaction that touches dd tuples spread over two parts can cut up to d2/4d^2/4 of its own edges and still counts as one distributed transaction. This is why the cut is a proxy for the cost, and why line L6 counts the distributed transactions directly.

The graph with replication (line L2). Let u(t)=∣{x:t∈W(x)}∣u(t) = |\{x : t \in W(x)\}|, the number of transactions that write tt. For each tuple tt there is a center ctc_t and, for each transaction xx that touches tt, a replica rt,xr_{t,x}. The star edge {ct,rt,x}\{c_t, r_{t,x}\} has weight u(t)u(t), and it is left out when u(t)=0u(t) = 0. For each transaction xx and two tuples t≠t′t \ne t' in T(x)T(x), the edge {rt,x,rt′,x}\{r_{t,x}, r_{t',x}\} has weight 1. The placement of line L4 is P(t)={π(ct)}∪{π(rt,x):t∈T(x)}P(t) = \{\pi(c_t)\} \cup \{\pi(r_{t,x}) : t \in T(x)\}, the parts of the star of tt.

Theorem 2. For every partition π\pi of the graph of line L2, the number of distributed transactions under PP is at most cut(π)\mathrm{cut}(\pi).

Proof. First we show: if all replicas rt,xr_{t,x} with t∈T(x)t \in T(x) lie in one part pp, and for each t∈W(x)t \in W(x) the star of tt lies in one part, then xx is local. For t∈T(x)t \in T(x), rt,xr_{t,x} is in pp, so p∈P(t)p \in P(t). For t∈W(x)t \in W(x), the star of tt lies in one part, which holds rt,xr_{t,x}, so it is pp, and P(t)={p}P(t) = \{p\}.

So a distributed transaction xx has one of two defects. (a) Its replicas lie in at least two parts. The replicas of xx are joined by a complete graph of edges of weight 1 that belong to xx alone, so one of these edges is cut. Charge xx to it. (b) Its replicas lie in one part, but some t∈W(x)t \in W(x) has a star that lies in at least two parts. Then u(t)≥1u(t) \ge 1, the star is connected, and one of its edges is cut. For each tuple tt, fix one cut star edge ete_t if there is one, and charge xx to ete_{t} for the first such tt. A weight 1 edge of (a) gets at most one charge. A star edge ete_t gets charges only from transactions that write tt, so at most u(t)=w(et)u(t) = w(e_t) charges. Each distributed transaction is charged once, and only cut edges get charges, so the number of distributed transactions is at most cut(π)\mathrm{cut}(\pi). □\square

A cut star edge also has a meaning of its own: if a replica of tt is in a different part from the center, the tuple has a second copy, and each of the u(t)u(t) writes of tt must update it. A tuple that no transaction writes has no star edges, so its copies are free in the cut; this is why the partitioner can copy read-only tuples to every part that reads them.

Corollary. If cut(π)=0\mathrm{cut}(\pi) = 0, every transaction of the workload is local under the placement of line L4. In particular, if the workload splits into kk groups of transactions that share no written tuple and touch only their own tuples apart from read-only ones, and a balanced partition with a zero cut exists, then a perfect partitioner gives a placement with no distributed transaction.

The candidates of line L6. Line L6 evaluates every candidate placement with the definition of a local transaction, and line L7 returns one with the fewest distributed transactions (the simplest one on a tie, in the order hash, replication, tree, lookup). So the chosen placement is never worse, on the training workload, than hash partitioning or full replication. Under full replication with k≥2k \ge 2 parts, a transaction is local exactly when it writes nothing, since a written tuple has k≥2k \ge 2 copies. On a different workload than the training one, these comparisons need not hold.

The decision tree of line L5. Each split has two nonempty sides, so the recursion ends after at most n−1n - 1 splits for nn training tuples. An impure node is split whenever two of its rows differ in some attribute, so when the training rows are pairwise distinct every leaf is pure and the tree predicts the label of line L4 for every training tuple. With a depth limit, or with equal rows of different labels, the tree can differ from the lookup table; line L6 measures the effect.

Termination. The graphs are finite. The local search of the partitioner applies only steps that lower the cut, which is a non-negative integer, so it ends. Coarsening stops when a level removes fewer than a tenth of the nodes, so the number of levels is finite. The tree ends as shown above. □\square

Complexity

  • Graph size. A transaction with dd tuples adds d(d−1)/2d(d - 1)/2 edges, so the graph has O(m)O(m) nodes and O(md)O(m d) edges, and line L1 or L2 takes O(md)O(m d) time. With replication, the number of nodes is mm plus the number of tuples.
  • Partitioning. METIS is built for large sparse graphs and is fast in practice; the page gives no bound for it. The local search of the implementation recomputes all gains at each step and is meant for small inputs.
  • Validation. One candidate costs O(mk)O(m k) set operations.
  • The bound in the front matter. O(md+mk)O(m d + m k) covers lines L1, L2, L4 and L6. It leaves out the partitioner of line L3 and the tree of line L5, which have no simple bound.
  • Graph size in practice. The graph grows with the trace, not with the database, and wide transactions make it dense. The paper keeps it small with sampling and filtering heuristics.

Properties

  • Workload driven. The placement fits the trace. If the access pattern changes, the placement has to be computed again.
  • Fine grained. Unlike hash partitioning or range partitioning on one key, the lookup table can follow any grouping of tuples, for example the tuples of one customer in several tables.
  • Heuristic at two levels. The cut weight is a proxy for the count of distributed transactions, and the partitioner only finds a small cut, not the smallest.
  • Replication costs writes. The star graph trades the reads that a copy makes local against the writes that every copy must take.
  • Explainable. When the tree fits well, the result is a short set of range predicates over attributes such as a warehouse id, which a database designer can read and check.

Variants and improvements

  • Graph or hypergraph. A transaction is really a hyperedge on its tuples, and a hypergraph partitioning counts each cut transaction once, which matches the cost better than the clique of edges. Later systems model the workload this way.
  • Sampling and filtering. The paper shrinks the graph with sampling of the trace and with filters that drop parts of the trace that add many edges and little information.
  • Balance on data or on load. The node weights can be the number of accesses, as on this page, or the size of the tuple.
  • Other partitioners. The cut step can use any balanced partitioner, such as Kernighan-Lin, Fiduccia-Mattheyses or a multilevel method. The difference from the graph partitioning problem itself is that Schism adds the workload graph, the replication stars, the explanation and the validation around it.
  • Data allocation. Schism decides which tuples go together and how many copies they get. Which node gets which part is a separate question, the data allocation problem.

When to use it

Use Schism for an OLTP database with many short transactions, a trace that represents the future workload, and a cluster where distributed transactions are costly. It works best when the data has a hidden grouping, such as the warehouses of a TPC-C database, that a single hash key does not show. For analytic workloads with large scans and joins, the parallel hash join and plain hash partitioning are a better fit.

Pitfalls

  • Overfitting the trace. The lookup table is exact only for the tuples and transactions of the trace. New tuples need the tree, or a default such as hashing.
  • Balanced cut, unbalanced load. A cut can be balanced in the node weights of the graph but not in the real load, if the weights do not match the cost of the accesses.
  • Copies of hot written tuples. A tuple that many transactions read and also write should not be copied. The star edges weigh its writes, but a partitioner that ignores the balance of copies can still make a poor choice.
  • Big graphs. One large scan in the trace adds a clique on all its tuples. Filter such statements before building the graph.
  • Reading the cut as the cost. The cut overcounts wide transactions. Compare candidates by the count of distributed transactions, as line L6 does.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

schism_partitioning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schism-partitioning/. The authors are listed in prov/RGG5F9.jsonl.

"""Schism: workload-driven partitioning and replication of the tuples of a database.

A workload is a list of transactions. A transaction is a pair (reads, writes) of
frozensets of tuple ids; a tuple that is both read and written counts as written.
A placement maps each tuple id to the nonempty set of the parts (0 .. k-1) that
hold a copy of it.

A transaction is local under a placement when one part holds a copy of every
tuple it touches and every tuple it writes has exactly one copy (a write must
update all copies). Otherwise it is distributed. Schism tries to find a placement
with few distributed transactions and balanced parts:

1. build a graph with a node per tuple and an edge for each pair of tuples that
   a transaction touches together (weight: the number of such transactions);
2. with replication, replace each tuple by a star: a center and one replica node
   per transaction that touches it, joined by edges whose weight is the number
   of transactions that write the tuple;
3. cut the graph into k balanced parts with a small total weight of cut edges;
4. read the placement off the parts;
5. learn a decision tree that predicts the placement of a tuple from its
   attributes (a set of range predicates);
6. count the distributed transactions of the lookup table, the tree, hash
   partitioning and full replication, and keep the best.

Step 3 uses METIS in the paper. Here a small balanced k-way local search (single
moves and swaps, from several random starts) takes its place.
"""

from __future__ import annotations

import math
import random
import zlib
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from itertools import combinations, product
from collections.abc import Hashable, Iterable, Mapping, Sequence

Txn = tuple[frozenset, frozenset]
Placement = dict[Hashable, frozenset]


def make_txn(reads: Iterable = (), writes: Iterable = ()) -> Txn:
    w = frozenset(writes)
    return (frozenset(reads) - w, w)


def touched(x: Txn) -> frozenset:
    return x[0] | x[1]


def stable_hash(v) -> int:
    return zlib.crc32(repr(v).encode())


def _ordered(items: Iterable) -> list:
    return sorted(items, key=repr)


# ---------------------------------------------------------------- graphs


@dataclass
class Graph:
    weight: dict = field(default_factory=dict)   # node -> node weight (its number of accesses)
    edges: Counter = field(default_factory=Counter)  # frozenset({u, v}) -> edge weight

    def add_edge(self, u, v, w: int = 1) -> None:
        if u == v or w == 0:
            return
        self.edges[frozenset((u, v))] += w


def build_graph(workload: Sequence[Txn]) -> Graph:
    """A node per tuple, weighted by the number of transactions that touch it; an edge
    per pair of tuples, weighted by the number of transactions that touch both."""
    g = Graph()
    for x in workload:
        ts = _ordered(touched(x))
        for t in ts:
            g.weight[t] = g.weight.get(t, 0) + 1
        for u, v in combinations(ts, 2):
            g.add_edge(u, v)
    return g


def build_replicated_graph(workload: Sequence[Txn]) -> Graph:
    """The graph with replication: tuple t becomes a center ('c', t) of weight 0 and a
    replica ('r', t, i) of weight 1 for each transaction i that touches t. The star edges
    weigh the number of transactions that write t; the edges of transaction i join its
    replicas with weight 1."""
    writes = Counter(t for x in workload for t in x[1])
    g = Graph()
    for i, x in enumerate(workload):
        ts = _ordered(touched(x))
        for t in ts:
            g.weight[("c", t)] = 0
            g.weight[("r", t, i)] = 1
            g.add_edge(("c", t), ("r", t, i), writes[t])
        for u, v in combinations(ts, 2):
            g.add_edge(("r", u, i), ("r", v, i))
    return g


def cut_weight(g: Graph, part: Mapping) -> int:
    total = 0
    for e, w in g.edges.items():
        u, v = tuple(e)
        if part[u] != part[v]:
            total += w
    return total


def placement_from(g: Graph, part: Mapping, replicated: bool) -> Placement:
    """Read the placement of the tuples off a partition of the graph."""
    if not replicated:
        return {t: frozenset([part[t]]) for t in g.weight}
    out: dict = defaultdict(set)
    for node in g.weight:
        out[node[1]].add(part[node])
    return {t: frozenset(s) for t, s in out.items()}


# ---------------------------------------------------------------- partitioner


def _greedy_start(nodes: Sequence, weight: Mapping, k: int) -> tuple[dict, list[int]]:
    """Largest weight first, each node to the lightest part (lowest index on a tie)."""
    load = [0] * k
    part = {}
    for v in sorted(nodes, key=lambda v: -weight[v]):  # stable: ties keep the given order
        q = min(range(k), key=lambda j: (load[j], j))
        part[v] = q
        load[q] += weight[v]
    return part, load


def balance_cap(weight: Mapping, k: int, eps: float) -> float:
    """The largest allowed load of a part: (1 + eps) W / k, raised to the largest load
    of the greedy start if that is higher (so that a balanced partition always exists)."""
    if not weight:
        return 0
    total = sum(weight.values())
    _, load = _greedy_start(_ordered(weight), weight, k)
    return max((1 + eps) * total / k, max(load))


def _connections(g: Graph, part: Mapping, k: int) -> dict:
    conn = {v: [0] * k for v in g.weight}
    for e, w in g.edges.items():
        u, v = tuple(e)
        conn[u][part[v]] += w
        conn[v][part[u]] += w
    return conn


def _best_step(g: Graph, part: dict, load: list, conn: dict, cap: float, nodes: Sequence):
    """The single move or swap that keeps every load at most cap and lowers the cut most."""
    w = g.weight
    best_gain, best = 0, None
    for u in nodes:
        a = part[u]
        for q in range(len(load)):
            if q != a and load[q] + w[u] <= cap:
                gain = conn[u][q] - conn[u][a]
                if gain > best_gain:
                    best_gain, best = gain, ((u, q),)
    # A swap of two nodes that have no neighbor outside their own parts cannot lower the
    # cut, so one end of a useful swap is a boundary node.
    boundary = [u for u in nodes if conn[u][part[u]] < sum(conn[u])]
    for u in boundary:
        for v in nodes:
            a, b = part[u], part[v]
            if a == b:
                continue
            if load[a] - w[u] + w[v] > cap or load[b] - w[v] + w[u] > cap:
                continue
            wuv = g.edges.get(frozenset((u, v)), 0)
            gain = conn[u][b] - conn[u][a] + conn[v][a] - conn[v][b] - 2 * wuv
            if gain > best_gain:
                best_gain, best = gain, ((u, b), (v, a))
    return best


def local_search(g: Graph, part: dict, k: int, cap: float) -> dict:
    """Apply the best improving move or swap until none is left. The cut drops by at
    least 1 per step, so this ends."""
    part = dict(part)
    nodes = _ordered(g.weight)
    load = [0] * k
    for v in nodes:
        load[part[v]] += g.weight[v]
    while True:
        conn = _connections(g, part, k)
        step = _best_step(g, part, load, conn, cap, nodes)
        if step is None:
            return part
        for v, q in step:
            load[part[v]] -= g.weight[v]
            load[q] += g.weight[v]
            part[v] = q


def _loads(g: Graph, part: Mapping, k: int) -> list:
    load = [0] * k
    for v, q in part.items():
        load[q] += g.weight[v]
    return load


def coarsen(g: Graph, rng: random.Random, limit: float) -> tuple[Graph, dict]:
    """One level of heavy edge matching: visit the nodes in random order and match each
    free node with the free neighbor of the heaviest edge, if the pair weighs at most limit.
    Return the contracted graph and the map from the nodes of g to the coarse nodes."""
    adj: dict = defaultdict(dict)
    for e, w in g.edges.items():
        u, v = tuple(e)
        adj[u][v] = w
        adj[v][u] = w
    nodes = _ordered(g.weight)
    rng.shuffle(nodes)
    mate = {}
    for u in nodes:
        if u in mate:
            continue
        best = None
        for v in _ordered(adj[u]):
            if v not in mate and g.weight[u] + g.weight[v] <= limit:
                if best is None or adj[u][v] > adj[u][best]:
                    best = v
        mate[u] = u if best is None else best
        if best is not None:
            mate[best] = u
    cmap, count = {}, 0
    for u in nodes:
        if u not in cmap:
            cmap[u] = cmap[mate[u]] = count
            count += 1
    coarse = Graph()
    for u in nodes:
        coarse.weight[cmap[u]] = coarse.weight.get(cmap[u], 0) + g.weight[u]
    for e, w in g.edges.items():
        u, v = tuple(e)
        coarse.add_edge(cmap[u], cmap[v], w)
    return coarse, cmap


def _rebalance(g: Graph, part: dict, k: int, cap: float) -> dict:
    """Move nodes out of parts above cap, the least harmful move first."""
    part = dict(part)
    load = _loads(g, part, k)
    while max(load) > cap:
        conn = _connections(g, part, k)
        a = max(range(k), key=lambda j: load[j])
        best = None
        for u in _ordered(v for v in g.weight if part[v] == a and g.weight[v] > 0):
            for q in range(k):
                if q != a and load[q] + g.weight[u] <= cap:
                    gain = conn[u][q] - conn[u][a]
                    if best is None or gain > best[0]:
                        best = (gain, u, q)
        if best is None:
            return part
        _, u, q = best
        load[a] -= g.weight[u]
        load[q] += g.weight[u]
        part[u] = q
    return part


def multilevel(g: Graph, k: int, cap: float, rng: random.Random) -> dict:
    """Coarsen by heavy edge matching, partition the small graph, then project the
    partition back level by level and refine it with local search at each level."""
    levels, cur = [], g
    while len(cur.weight) > max(2 * k, 8):
        coarse, cmap = coarsen(cur, rng, cap / 2)
        if len(coarse.weight) > 0.9 * len(cur.weight):
            break
        levels.append((cur, cmap))
        cur = coarse
    order = _ordered(cur.weight)
    rng.shuffle(order)
    part = local_search(cur, _greedy_start(order, cur.weight, k)[0], k, cap)
    for fine, cmap in reversed(levels):
        part = {v: part[cmap[v]] for v in fine.weight}
        part = local_search(fine, _rebalance(fine, part, k, cap), k, cap)
    if max(_loads(g, part, k)) > cap:  # the projection could not be balanced: start at the finest level
        part = local_search(g, _greedy_start(_ordered(g.weight), g.weight, k)[0], k, cap)
    return part


def partition(g: Graph, k: int, eps: float = 0.1, seed: int = 0, restarts: int = 4) -> dict:
    """A balanced k-way partition with a small cut, in the style of METIS: multilevel
    runs from several random seeds; keep the best. A heuristic."""
    if k < 1:
        raise ValueError("k must be at least 1")
    if not g.weight:
        return {}
    cap = balance_cap(g.weight, k, eps)
    rng = random.Random(seed)
    best, best_cut = None, None
    for _ in range(max(1, restarts)):
        part = multilevel(g, k, cap, rng)
        c = cut_weight(g, part)
        if best is None or c < best_cut:
            best, best_cut = part, c
    return best


def brute_force_partition(g: Graph, k: int, eps: float = 0.1) -> tuple[int, dict]:
    """The smallest cut over all partitions that respect the same cap (tiny graphs only)."""
    nodes = _ordered(g.weight)
    if len(nodes) > 10:
        raise ValueError("brute force is for at most 10 nodes")
    cap = balance_cap(g.weight, k, eps)
    best = None
    for labels in product(range(k), repeat=len(nodes)):
        load = [0] * k
        for v, q in zip(nodes, labels):
            load[q] += g.weight[v]
        if max(load, default=0) > cap:
            continue
        part = dict(zip(nodes, labels))
        c = cut_weight(g, part)
        if best is None or c < best[0]:
            best = (c, part)
    return best


# ---------------------------------------------------------------- cost of a placement


def is_distributed(x: Txn, placement: Mapping) -> bool:
    reads, writes = x
    for t in writes:
        if len(placement[t]) != 1:
            return True
    common = None
    for t in touched(x):
        common = set(placement[t]) if common is None else common & placement[t]
        if not common:
            return True
    return False


def distributed_count(workload: Sequence[Txn], placement: Mapping) -> int:
    return sum(1 for x in workload if is_distributed(x, placement))


def hash_placement(ids: Iterable, k: int, h=stable_hash) -> Placement:
    return {t: frozenset([h(t) % k]) for t in ids}


def replication_placement(ids: Iterable, k: int) -> Placement:
    return {t: frozenset(range(k)) for t in ids}


# ---------------------------------------------------------------- explanation


def _entropy(labels: Counter) -> float:
    n = sum(labels.values())
    return -sum(c / n * math.log2(c / n) for c in labels.values() if c)


def _label_key(label) -> tuple:
    return tuple(sorted(label)) if isinstance(label, (set, frozenset)) else (label,)


def _majority(labels: Counter):
    return min(labels, key=lambda lab: (-labels[lab], _label_key(lab)))


def train_tree(rows: Sequence[Mapping], labels: Sequence, max_depth: int | None = None, depth: int = 0):
    """A decision tree on numeric attributes. A leaf is ('leaf', label). A split is
    ('split', attr, thr, left, right): rows with row[attr] <= thr go left. Each split has
    the largest information gain among the splits with two nonempty sides; an impure
    node is split even when the gain is 0, so that distinct rows end in pure leaves."""
    counts = Counter(labels)
    if len(counts) <= 1 or (max_depth is not None and depth >= max_depth):
        return ("leaf", _majority(counts))
    base = _entropy(counts)
    n = len(rows)
    best = None
    for attr in sorted(rows[0]):
        values = sorted({r[attr] for r in rows})
        for thr in values[:-1]:
            left = Counter(lab for r, lab in zip(rows, labels) if r[attr] <= thr)
            right = counts - left
            nl = sum(left.values())
            gain = base - nl / n * _entropy(left) - (n - nl) / n * _entropy(right)
            if best is None or gain > best[0] + 1e-12:
                best = (gain, attr, thr)
    if best is None:  # all rows are equal on every attribute
        return ("leaf", _majority(counts))
    _, attr, thr = best
    li = [i for i, r in enumerate(rows) if r[attr] <= thr]
    ri = [i for i, r in enumerate(rows) if r[attr] > thr]
    return ("split", attr, thr,
            train_tree([rows[i] for i in li], [labels[i] for i in li], max_depth, depth + 1),
            train_tree([rows[i] for i in ri], [labels[i] for i in ri], max_depth, depth + 1))


def predict(tree, row: Mapping):
    while tree[0] == "split":
        _, attr, thr, left, right = tree
        tree = left if row[attr] <= thr else right
    return tree[1]


def tree_rules(tree, path: tuple = ()) -> list[tuple[tuple, object]]:
    """The tree as a list of (conjunction of range predicates, label)."""
    if tree[0] == "leaf":
        return [(path, tree[1])]
    _, attr, thr, left, right = tree
    return tree_rules(left, path + ((attr, "<=", thr),)) + tree_rules(right, path + ((attr, ">", thr),))


# ---------------------------------------------------------------- Schism


SIMPLICITY = ("hash", "replication", "tree", "lookup")


@dataclass
class Result:
    choice: str
    costs: dict
    placements: dict
    part: dict
    graph: Graph
    tree: object


def schism(db: Mapping[Hashable, Mapping], workload: Sequence[Txn], k: int, replicate: bool = True,
           eps: float = 0.1, seed: int = 0, restarts: int = 4, max_depth: int | None = None,
           h=stable_hash) -> Result:
    """db maps each tuple id to its attributes (numbers). Return the chosen strategy, the
    number of distributed transactions of each candidate, and the placements."""
    for x in workload:
        missing = touched(x) - db.keys()
        if missing:
            raise KeyError(f"transaction touches unknown tuples {sorted(missing, key=repr)}")
    ids = _ordered(db)
    g = build_graph(workload)  # @line L1
    if replicate:
        g = build_replicated_graph(workload)  # @line L2
    part = partition(g, k, eps, seed, restarts)  # @line L3
    from_graph = placement_from(g, part, replicate)  # @line L4
    lookup = hash_placement(ids, k, h)  # tuples that no transaction touches fall back to hashing
    lookup.update(from_graph)
    seen = [t for t in ids if t in from_graph]
    tree = train_tree([db[t] for t in seen], [lookup[t] for t in seen], max_depth) if seen else ("leaf", frozenset([0]))  # @line L5
    placements = {
        "hash": hash_placement(ids, k, h),
        "replication": replication_placement(ids, k),
        "tree": {t: frozenset(predict(tree, db[t])) for t in ids},
        "lookup": lookup,
    }
    costs = {name: distributed_count(workload, p) for name, p in placements.items()}  # @line L6
    choice = min(SIMPLICITY, key=lambda name: (costs[name], SIMPLICITY.index(name)))
    return Result(choice, costs, placements, part, g, tree)  # @line L7
test_schism_partitioning.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schism-partitioning/. The authors are listed in prov/RGG5F9.jsonl.

import random
from collections import Counter
from itertools import combinations

import pytest

from schism_partitioning import (balance_cap, brute_force_partition, build_graph, build_replicated_graph,
                                 coarsen, cut_weight, distributed_count, hash_placement, is_distributed, make_txn,
                                 partition, placement_from, predict, replication_placement, schism,
                                 touched, train_tree, tree_rules)

PAGE_DB = {i: {"id": i, "wid": 1 if i <= 3 else (2 if i <= 6 else 0)} for i in range(1, 9)}
PAGE_WORKLOAD = [
    make_txn([7], [1, 2]),
    make_txn([8], [2, 3]),
    make_txn([7], [4, 5]),
    make_txn([8], [5, 6]),
    make_txn([], [1, 3]),
    make_txn([], [4, 6]),
]


def ident(t):
    return t


def random_workload(rng, n, q, max_size=3, write_rate=0.4):
    out = []
    for _ in range(q):
        ts = rng.sample(range(n), rng.randint(1, min(max_size, n)))
        writes = [t for t in ts if rng.random() < write_rate]
        out.append(make_txn([t for t in ts if t not in writes], writes))
    return out


def local_by_definition(x, placement, k):
    for p in range(k):
        if all(p in placement[t] for t in touched(x)) and all(placement[t] == {p} for t in x[1]):
            return True
    return False


def test_page_example_without_replication():
    r = schism(PAGE_DB, PAGE_WORKLOAD, 2, replicate=False, h=ident)
    assert len(r.graph.weight) == 8 and len(r.graph.edges) == 14 and set(r.graph.edges.values()) == {1}
    assert cut_weight(r.graph, r.part) == 4 == brute_force_partition(r.graph, 2)[0]
    assert r.costs == {"hash": 4, "replication": 6, "tree": 2, "lookup": 2}
    assert r.choice == "tree"


def test_page_example_with_replication():
    r = schism(PAGE_DB, PAGE_WORKLOAD, 2, replicate=True, h=ident)
    g = r.graph
    assert len(g.weight) == 24 and len(g.edges) == 26 and sum(g.edges.values()) == 38
    assert cut_weight(g, r.part) == 0
    look = r.placements["lookup"]
    assert look[7] == look[8] == {0, 1}
    assert look[1] == look[2] == look[3] and look[4] == look[5] == look[6] and look[1] != look[4]
    assert r.costs == {"hash": 4, "replication": 6, "tree": 0, "lookup": 0}
    assert r.choice == "tree"
    rules = tree_rules(r.tree)
    assert len(rules) == 3
    for t in PAGE_DB:
        assert r.placements["tree"][t] == look[t]


def test_graph_matches_definition():
    rng = random.Random(1)
    for _ in range(30):
        w = random_workload(rng, 6, rng.randint(1, 8))
        g = build_graph(w)
        for u, v in combinations(range(6), 2):
            expect = sum(1 for x in w if {u, v} <= touched(x))
            assert g.edges.get(frozenset((u, v)), 0) == expect
        assert g.weight == dict(Counter(t for x in w for t in touched(x)))


def test_replicated_graph_matches_definition():
    rng = random.Random(2)
    for _ in range(30):
        w = random_workload(rng, 5, rng.randint(1, 7))
        g = build_replicated_graph(w)
        writes = Counter(t for x in w for t in x[1])
        star = sum(writes[t] * sum(1 for x in w if t in touched(x)) for t in range(5))
        clique = sum(len(touched(x)) * (len(touched(x)) - 1) // 2 for x in w)
        assert sum(g.edges.values()) == star + clique
        assert sum(g.weight.values()) == sum(len(touched(x)) for x in w)


@pytest.mark.parametrize("seed", range(40))
def test_is_distributed_matches_definition(seed):
    rng = random.Random(100 + seed)
    k = rng.randint(1, 3)
    placement = {t: frozenset(rng.sample(range(k), rng.randint(1, k))) for t in range(6)}
    for x in random_workload(rng, 6, 10):
        assert is_distributed(x, placement) == (not local_by_definition(x, placement, k))


@pytest.mark.parametrize("seed", range(40))
def test_distributed_count_at_most_cut_for_any_partition(seed):
    rng = random.Random(200 + seed)
    k = rng.randint(2, 3)
    w = random_workload(rng, 7, rng.randint(1, 10))
    for replicated in (False, True):
        g = build_replicated_graph(w) if replicated else build_graph(w)
        for _ in range(5):
            part = {v: rng.randrange(k) for v in g.weight}
            placement = placement_from(g, part, replicated)
            assert distributed_count(w, placement) <= cut_weight(g, part)


@pytest.mark.parametrize("seed", range(20))
def test_cut_equals_distributed_for_pairs(seed):
    rng = random.Random(300 + seed)
    w = random_workload(rng, 7, 12, max_size=2)
    g = build_graph(w)
    part = {v: rng.randrange(3) for v in g.weight}
    assert distributed_count(w, placement_from(g, part, False)) == cut_weight(g, part)


def _no_improving_step(g, part, k, cap):
    load = [0] * k
    for v, q in part.items():
        load[q] += g.weight[v]
    c = cut_weight(g, part)
    nodes = list(g.weight)
    for u in nodes:
        for q in range(k):
            if q != part[u] and load[q] + g.weight[u] <= cap:
                if cut_weight(g, {**part, u: q}) < c:
                    return False
    for u, v in combinations(nodes, 2):
        a, b = part[u], part[v]
        if a != b and load[a] - g.weight[u] + g.weight[v] <= cap and load[b] - g.weight[v] + g.weight[u] <= cap:
            if cut_weight(g, {**part, u: b, v: a}) < c:
                return False
    return True


@pytest.mark.parametrize("seed", range(30))
def test_partitioner_is_balanced_local_optimum_and_not_below_brute_force(seed):
    rng = random.Random(400 + seed)
    k = rng.randint(2, 3)
    w = random_workload(rng, 8, rng.randint(2, 9))
    g = build_graph(w)
    part = partition(g, k, eps=0.1, seed=seed)
    cap = balance_cap(g.weight, k, 0.1)
    load = Counter()
    for v, q in part.items():
        load[q] += g.weight[v]
    assert max(load.values()) <= cap
    assert set(part) == set(g.weight)
    assert _no_improving_step(g, part, k, cap)
    assert cut_weight(g, part) >= brute_force_partition(g, k, 0.1)[0]


@pytest.mark.parametrize("seed", range(15))
def test_coarsening_keeps_weights_and_cuts(seed):
    rng = random.Random(500 + seed)
    w = random_workload(rng, 9, 12)
    g = build_replicated_graph(w) if seed % 2 else build_graph(w)
    coarse, cmap = coarsen(g, rng, limit=4)
    assert sum(coarse.weight.values()) == sum(g.weight.values())
    assert max(Counter(cmap.values()).values()) <= 2
    for _ in range(5):
        cpart = {c: rng.randrange(3) for c in coarse.weight}
        assert cut_weight(coarse, cpart) == cut_weight(g, {v: cpart[cmap[v]] for v in g.weight})


def test_planted_warehouses_beat_hashing():
    rng = random.Random(7)
    k, per = 4, 6
    db = {(wid, j): {"wid": wid, "j": j} for wid in range(k) for j in range(per)}
    db.update({("item", j): {"wid": -1, "j": j} for j in range(3)})
    w = []
    for i in range(40):
        wid = i % k  # the same number of transactions per warehouse, so a perfect split is balanced
        ts = rng.sample(range(per), 2)
        w.append(make_txn([("item", rng.randrange(3))], [(wid, ts[0]), (wid, ts[1])]))
    r = schism(db, w, k, replicate=True, seed=3)
    assert r.costs["lookup"] == 0 == r.costs["tree"]
    assert r.costs["hash"] > 20
    assert r.costs["replication"] == 40
    plain = schism(db, w, k, replicate=False, seed=3)
    assert plain.costs["lookup"] > 0  # the shared items cannot sit with every warehouse without copies


def test_full_replication():
    rng = random.Random(8)
    reads = [make_txn(rng.sample(range(6), 3), []) for _ in range(10)]
    placement = replication_placement(range(6), 3)
    assert distributed_count(reads, placement) == 0
    assert is_distributed(make_txn([0], [1]), placement)
    assert not is_distributed(make_txn([0], [1]), replication_placement(range(6), 1))


def test_tree_fits_distinct_rows():
    rng = random.Random(9)
    for _ in range(20):
        n = rng.randint(1, 15)
        pts = rng.sample([(a, b) for a in range(5) for b in range(5)], n)
        rows = [{"a": a, "b": b} for a, b in pts]
        labels = [rng.randrange(3) for _ in rows]
        tree = train_tree(rows, labels)
        assert [predict(tree, r) for r in rows] == labels
        rules = tree_rules(tree)
        for r, lab in zip(rows, labels):
            hits = [l for path, l in rules if all((r[a] <= t) if op == "<=" else (r[a] > t) for a, op, t in path)]
            assert hits == [lab]


def test_tree_finds_ranges():
    rows = [{"x": x, "y": (7 * x) % 11} for x in range(30)]
    labels = [0 if x < 10 else (1 if x < 20 else 2) for x in range(30)]
    tree = train_tree(rows, labels, max_depth=2)
    assert [predict(tree, r) for r in rows] == labels
    assert {(path, lab) for path, lab in tree_rules(tree)} == {
        ((("x", "<=", 9),), 0), ((("x", ">", 9), ("x", "<=", 19)), 1), ((("x", ">", 9), ("x", ">", 19)), 2)}


def test_edge_cases():
    assert schism({1: {"a": 1}}, [], 2).costs == {"hash": 0, "replication": 0, "tree": 0, "lookup": 0}
    r = schism(PAGE_DB, PAGE_WORKLOAD, 1)
    assert set(r.costs.values()) == {0}
    with pytest.raises(KeyError):
        schism(PAGE_DB, [make_txn([99], [])], 2)
    with pytest.raises(ValueError):
        partition(build_graph(PAGE_WORKLOAD), 0)
    assert hash_placement([5], 2, ident) == {5: frozenset([1])}

History

Curino, Jones, Zhang and Madden presented Schism at VLDB 2010, in the context of shared-nothing OLTP systems where distributed transactions limit the throughput. Earlier work on distributed database design chose fragments from predicates and allocated them with cost models, as in horizontal fragmentation and the data allocation problem. Schism instead worked from a trace at the level of single tuples, used a graph partitioner from scientific computing, and returned a range partitioning that a designer could read. The paper reports experiments on TPC-C, TPC-E and other workloads.

References

  1. Carlo Curino, Evan Jones, Yang Zhang and Sam Madden, Schism: a workload-driven approach to database replication and partitioning, Proceedings of the VLDB Endowment 3(1-2), 2010, pages 48 to 57, the graph of tuples and transactions, the star graph for replication, the use of METIS, the explanation phase with a decision tree, the final validation against hash partitioning and full replication, and the experiments on TPC-C and TPC-E (general locator)
  2. George Karypis and Vipin Kumar, A fast and high quality multilevel scheme for partitioning irregular graphs, SIAM Journal on Scientific Computing 20(1), 1998, pages 359 to 392, the multilevel scheme with heavy edge matching, partitioning of the coarsest graph, and refinement during uncoarsening, which METIS implements

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example