Algorithmadvanced
Transaction chopping
Also called SC-graph chopping, finest chopping.
Split known transaction programs into pieces that commit one by one, and keep every execution serializable: a chopping is safe when its graph of sibling and conflict edges has no SC-cycle.
- Time
- O((m^2 + n^3) α(m)) worst
- Space
- O(m n) extra
- Where
- m = the number of statements in all transactions; n = the number of transactions
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dennis Shasha, Eric Simon, Patrick Valduriez, 1992
Transaction chopping is a method of Shasha, Simon and Valduriez (1992), developed with Llirbat in a journal paper of 1995, to get more concurrency from a workload whose transaction programs are all known in advance. It splits each transaction into pieces, and each piece runs and commits as a transaction of its own, so locks are held for a shorter time. A chopping is correct if every execution of the pieces is equivalent to a serial execution of the original, whole transactions. The test is on an undirected graph of the pieces with S (sibling) edges between pieces of one transaction and C (conflict) edges between conflicting pieces of different transactions: if no simple cycle has both kinds of edge (an SC-cycle), and every rollback statement is in the first piece, the chopping is correct. The finest correct chopping is unique, and a union-find pass per transaction computes it. The test reasons about conflict serializability at the level of whole transactions; it does not change the concurrency control, which can be two-phase locking or any other serializable method for the pieces.
In plain words
A long transaction holds its locks until it ends, and the other transactions wait. If we knew that no other transaction can see the difference, we could commit the transaction in several steps and release the locks after each step. Chopping finds where this is safe. It looks at all the programs that can run. Two steps of one transaction may be split apart only if no chain of conflicting transactions joins them: if one step touches data that some group of transactions uses, and another step touches data of the same group, then a member of the group can run between the two steps, see half of the work, and break serializability. The method also keeps every possible rollback in the first step, because a later step cannot undo the steps that already committed.
The problem
Input. A set of transaction programs , the complete workload. Each program is a sequence of statements: reads , writes and rollback statements, the places where the program may decide to abort. Two accesses conflict if they touch the same item and at least one is a write.
Chopping. A chopping of cuts its sequence into pieces . On this page each piece is a run of consecutive statements, and the pieces of run in program order. A chopping of the workload is a chopping of each .
Execution model. Each piece runs as a transaction under a concurrency control that makes the execution of the pieces serializable. A piece that the system aborts (for example as the victim of a deadlock) is restarted until it commits. Only a rollback statement can make the whole give up.
Correctness. A chopping is correct if every execution of the pieces allowed by the model is conflict equivalent to a serial execution of the whole transactions .
The test of Shasha et al.
- A chopping is rollback-safe if, for every with rollback statements, all of them are in its first piece.
- The chopping graph has a node for each piece. An S edge joins two pieces of the same transaction. A C edge joins two pieces of different transactions that contain conflicting accesses.
- An SC-cycle is a simple cycle of the chopping graph with at least one S edge and at least one C edge.
Theorem (Shasha et al.). A rollback-safe chopping with no SC-cycle is correct.
The goal is the finest such chopping: the one with the most pieces.
The algorithm
The S edges of one transaction form a clique, so the other transactions join their own pieces anyway. For this reason the finest chopping of depends only on the other transactions as wholes, not on how they are chopped. FINEST-CHOPPING computes this private chopping of each and returns the union. The positions of are .
FINEST-CHOPPING(T_1, ..., T_n)- 1
for i ← 1 to n do - 2
U ← a union-find over the transactions T_j with j ≠ i - 3
for each pair j, k ≠ i such that T_j and T_k have conflicting accesses do UNION(U, j, k) - 4
P ← a union-find over the positions of T_i; owner ← an empty map - 5
for p ← 1 to |T_i| do - 6
for each j ≠ i such that T_j has an access in conflict with statement p of T_i do - 7
r ← FIND(U, j); if r ∈ owner then UNION(P, owner[r], p) else owner[r] ← p - 8
end ← the position of the last rollback statement of T_i, or 1 if there is none - 9
for p ← 1 to |T_i| do end ← max(end, the last position in the class of p in P) - 10
if end = p then cut T_i after position p - 11
return the cuts of T_1, ..., T_n
Lines L2 and L3 find the connected components of the conflict graph of the other transactions: two transactions are in one component if a chain of conflicts joins them. Lines L4 to L7 put two statements of into one class when they conflict with the same component; owner remembers the first statement that touched each component. Lines L8 to L10 turn the classes into contiguous pieces. A piece must contain every class that it touches from its first to its last position, and the first piece must reach the last rollback statement. The sweep keeps in end the furthest position that the current piece must reach, and cuts as soon as the sweep arrives there.
Each component of the other transactions ends up inside one piece of . This is exactly the condition for no SC-cycle through : an SC-cycle that uses an S edge of must leave through a C edge, walk inside one component of the others, and come back through a C edge into a different piece of . The same observation gives the test HAS-SC-CYCLE of the implementation, which runs in the same time and needs no cycle search.
Example
Accounts and . The workload has a transfer , a deposit on , and a deposit on . For , the others are and . They do not conflict, so lines L2 and L3 leave two components, and .
| step | statement of | conflicts with | owner | classes of | end | cut |
|---|---|---|---|---|---|---|
| L5 to L7 | 1: | |||||
| L5 to L7 | 2: | |||||
| L5 to L7 | 3: | |||||
| L5 to L7 | 4: | |||||
| L8 | 1 | |||||
| L9, L10 | 2 | |||||
| L9, L10 | 2 | after 2 | ||||
| L9, L10 | 4 | |||||
| L9, L10 | 4 | after 4 |
The transfer becomes two pieces, and . A deposit on can run between them and sees the debit, which is fine: in the equivalent serial order it runs after . Both deposits stay whole, because each of their two statements conflicts with the transfer, which is one component for them.
Now add an audit . It conflicts with and with , so for the others form one component , and every statement of lands in one class: the transfer cannot be chopped. The old chopping now has the SC-cycle , and the execution shows why: the audit sees debited and not yet credited, and its conflict graph has the cycle .
Rollbacks change the picture too. If the transfer checks the balance after and may roll back there, the first piece is , rollback, , which is the same cut. If it checks at the very end, line L8 sets the end of the first piece to the last position, and the transfer is one piece.
Correctness
The proof is in proofs/correctness.md. It has three parts. First, the theorem of Shasha et al.: suppose an execution of a rollback-safe chopping with no SC-cycle had a cycle among the whole transactions; contract each transaction to its pieces and follow the cycle in the chopping graph; either the walk gives an SC-cycle, or it stays on C edges between single pieces, which is a cycle in the conflict graph of the pieces and contradicts that the pieces ran serializably. Second, the component lemma: there is an SC-cycle if and only if two different pieces of one transaction conflict with the same component of the other transactions. Third, the output of FINEST-CHOPPING passes the test, and a contiguous chopping of passes it if and only if every one of its cuts is a cut of the output. So the output is the unique finest correct chopping in the sense of the test.
Proof: The SC-cycle test is sound, and FINEST-CHOPPING returns the finest chopping that passes itfull
Model. The workload is . A chopping cuts each into contiguous pieces. An execution runs every piece as a transaction. Pieces that the system aborts are restarted until they commit, and a rollback statement of aborts in the piece that contains it. Let be the conflict graph of the committed pieces: an arc when an access of comes before a conflicting access of in . The concurrency control of the pieces makes acyclic. Let be the conflict graph of the committed whole transactions: an arc () when an access of comes before a conflicting access of . By the serializability theorem, is conflict equivalent to a serial execution of the whole transactions if and only if is acyclic. The chopping graph and SC-cycles are as defined on the page. For a fixed , let be the graph on the transactions , , with an edge when two of them have conflicting accesses; its components are the components of the others.
Lemma 1 (rollback safety). If the chopping is rollback-safe, then in every execution each transaction either commits all its pieces or commits none.
Proof. A rollback statement of lies in its first piece. If rolls back, it does so while the first piece runs, and that piece aborts; the later pieces never start, so no piece of commits. Otherwise each piece is restarted until it commits.
So the committed pieces form whole transactions, and is defined on them.
Theorem 2 (Shasha et al.). If the chopping is rollback-safe and has no SC-cycle, then is acyclic for every execution .
Proof. Suppose has a cycle with distinct transactions. Indices are taken modulo . The arc comes from an access in a piece of that comes before a conflicting access in a piece of . Then is an arc of , and and are joined by a C edge in . In each transaction of the cycle, the arc in ends at and the arc out starts at .
Case 1: for every . Then is a closed walk in through pieces of distinct transactions, so it is a cycle, and is not acyclic. This contradicts the model.
Case 2: for some . Consider the closed walk in that goes by a C edge, then by an S edge if , then by a C edge, and so on, until it returns to . The transactions are distinct, and inside one transaction the walk visits and , which are distinct whenever both appear. So no node repeats, and the walk is a simple cycle. It has C edges and at least one S edge, so it has at least three nodes. It is an SC-cycle, a contradiction.
The proof does not use the order of the pieces inside a transaction; it holds for any order in which the pieces of a transaction run.
Lemma 3 (components). has an SC-cycle if and only if, for some , two different pieces of each contain a statement that conflicts with a transaction of the same component of the others.
Proof. () Let pieces of conflict with and of one component of . Take a shortest path in ; its transactions are distinct and none is . For each choose pieces of and of with conflicting accesses, let be a piece of that conflicts with , and let be a piece of that conflicts with . The walk uses C edges from to , from each to and from to , an S edge from to when they differ (drop the step when ), and the S edge from to . Its nodes are pieces of distinct transactions, except for the pairs and , which are distinct inside each pair. So it is a simple cycle with at least three nodes, an S edge and a C edge.
() Let be a simple SC-cycle. Let be the ends of an S edge of ; they are pieces of one transaction . Remove that edge from to get a simple path from to . Two pieces of are joined only by S edges, and has a C edge, whose ends lie in different transactions, so the path visits a piece of another transaction. Let be the last piece of before the first such visit, and the first piece of after it. They are different nodes of a simple path. Every node strictly between them is a piece of a transaction other than , and consecutive nodes there are pieces of one transaction (S edge) or of two conflicting transactions (C edge). So all their transactions lie in one component of . The node after conflicts with , and the node before conflicts with , so and are different pieces of that conflict with .
The condition of Lemma 3 for a given depends on the chopping of only, since is built from whole transactions. If the other transactions are not chopped, they have one piece each, and the condition for them is empty. So:
Corollary 4. A chopping has no SC-cycle if and only if, for each , the chopping of with all other transactions whole has no SC-cycle. In particular the union of SC-free private choppings is SC-free.
Lemma 5 (the classes). After line L7 for transaction , two statements of are in the same class of if and only if a chain of statements of joins them, in which each consecutive pair conflicts with a common component of the others. All statements that conflict with one component are in one class.
Proof. Lines L2 and L3 finish before line L5 starts, so in line L7 returns the final representative of the component of . Line L7 unites each statement that conflicts with with , the first statement that did. So all such statements share a class, and every UNION joins two statements that conflict with a common component.
Theorem 6 (finest chopping). Let be the chopping of made by lines L8 to L10. A contiguous chopping of is rollback-safe and satisfies the condition of Lemma 3 for if and only if every cut of is a cut of .
Proof. For a position , let be the last position in the class of , and let be the last rollback position of , or 1. After line L9 at position , , and line L10 cuts after exactly when this value is .
(Only if.) Let pass the test. By Lemma 5, each UNION joins two statements that conflict with a common component, which by Lemma 3 lie in the same piece of ; so each class lies inside one piece of . Suppose cuts after a position where does not, so there. If , then positions 1 and are on different sides of the cut, and the rollback statement at is not in the first piece of , a contradiction. Otherwise for some , and and are in one class but on different sides of the cut, a contradiction.
(If.) Every piece of is a union of pieces of . The first piece of ends at or after , because throughout; so the first piece of contains every rollback statement. If two pieces of had statements that conflict with one component , then by Lemma 5 and are in one class. For every position with of that class, , so has no cut inside the span of the class; and are in one piece of , hence in one piece of , a contradiction.
Conclusion. Taking in Theorem 6 shows that each passes the test, and Corollary 4 shows that the union has no SC-cycle; it is rollback-safe by construction. By Theorem 2, is correct. By Theorem 6 and Corollary 4, the choppings that pass the test are exactly those whose cuts are cuts of , so is the unique finest one. The function HAS-SC-CYCLE of the implementation checks the condition of Lemma 3 directly, so it agrees with the definition of an SC-cycle; the tests also compare it with a search over all simple cycles on small workloads.
Complexity
Let be the number of transactions and the number of statements. A first pass compares every pair of statements and records, for each statement, the set of transactions it conflicts with, and for each transaction the transactions it conflicts with: time and space. For each , lines L2 and L3 make at most calls to UNION, and lines L5 to L7 make at most calls, so the whole loop makes union-find calls. With union by size and path compression, each call costs amortized, where is the inverse Ackermann function. The sweep of lines L8 to L10 is linear. The total is time. With an index from items to accesses, the first pass costs time proportional to the number of conflicting pairs.
Properties
- Unique result. The finest correct chopping is unique, so the output does not depend on the order in which the loops visit transactions and statements.
- Compositional. The union of the private choppings, each computed against the other transactions whole, is correct. A transaction can be chopped without knowing how the others are chopped.
- Monotone. Merging two adjacent pieces of a correct chopping keeps it correct. Cutting a piece of an incorrect chopping keeps it incorrect, since the SC-cycle stays.
- Static. The test needs the whole workload. A new program that conflicts with two components joins them and can forbid cuts that were safe before.
- The simplest SC-cycle always hurts. If two pieces and of both conflict with an unchopped , the execution gives the conflict cycle .
Variants and improvements
- Robustness. Robustness against weak isolation asks the general question: do all executions of a fixed set of programs at a weak level stay serializable? Ketsman et al. place chopping as the case of no isolation at all between the pieces of one transaction.
- Chains in geo-replicated stores. Lynx (Zhang et al., 2013) chops transactions into chains of hops, one per server, and runs the SC-cycle test on the static set of chains, so that the first hop can return to the client early.
- Other consistency models. Cerone, Gotsman and Yang (2015) give a chopping test for parallel snapshot isolation, where the pieces run at that level instead of serializable.
- Semantic methods. Sagas split a transaction with no test at all and give up isolation; escrow and open nested transactions use the meaning of the operations to allow more interleavings than conflicts permit.
When to use it
Use chopping when the workload is fixed and known, for example a set of stored procedures in an OLTP system, when long transactions hold hot locks, and when the system can retry a piece until it commits. It does not help a workload with ad hoc queries, because a single new program can join the components. It is also not a fit when the application needs a rollback late in the transaction, because rollback safety then forces the whole transaction into one piece.
Pitfalls
- Single transactions in place of components. Line L7 looks up the component of . A version that keys
ownerby itself merges two statements only when they conflict with the same transaction, and misses longer SC-cycles such as . Lines L2 and L3 must run first. - Forgetting the rollback statements. A cut before a rollback statement lets a later piece abort after the earlier pieces have committed and released their locks. Line L8 must start the sweep at the last rollback position, not at 1.
- Pieces that are not contiguous. The classes of after line L7 may interleave, as in classes and . If pieces must be runs of consecutive statements, cutting at class boundaries alone is wrong; lines L9 and L10 must extend the piece to the last position of every class that it touches.
- Treating the test as dynamic. The test assumes every program in the workload. Adding a report query later without running the test again can make a correct chopping incorrect, as the audit of the example shows.
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.
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Schedules of transactions, and their classes checked by definition.
This is the reference that the tests of the concurrency pages compare
against. Every class test here follows its definition directly. The
serializability tests try every serial order of the committed transactions;
there is no conflict graph and no cycle test here. Do not use it as a
scheduler.
Actions and schedules
An action is a tuple (kind, txn, item). kind is "r" (read), "w" (write),
"c" (commit) or "a" (abort). txn is a transaction id (an int after
parse). item is a string for r and w, and None for c and a.
A schedule is a tuple of actions. In a well-formed schedule each
transaction has at most one c or a, and it is the last action of that
transaction. A schedule may be a prefix: a transaction with no c or a
is active.
parse("r1(x) w2(x) c1 a2") the schedule as a tuple of actions
format(s) the inverse of parse (also format_schedule)
validate(s) raise ValueError if s is not well formed
transactions(s) the ids in the order of their first action
committed(s), aborted(s) the ids with a c, or with an a, in s
actions_of(s, t) the actions of t, in order
committed_projection(s) the r, w and c actions of the committed
transactions, in the order of s
conflicts(p, q) different transactions, the same item, and
at least one write
serial_schedule(s, order) the actions of the transactions of order,
one transaction after the other
Equivalence and serializability (on the committed projection)
conflict_equivalent(s1, s2) same actions, and every pair of conflicting
actions in the same order
reads_from(s) {read: write it reads from}, see below
final_writes(s) {item: the last write on the item}
view_equivalent(s1, s2) same actions, same reads_from and the same
final_writes
conflict_serializable_orders(s), view_serializable_orders(s)
every serial order of the committed
transactions that is equivalent, as tuples,
in lexicographic order of the sorted ids
is_conflict_serializable(s), is_view_serializable(s)
These raise ValueError when s has more than MAX_BRUTE_FORCE committed
transactions. is_view_serializable uses the plain definition (view
equivalence of C(s) to a serial schedule), with no condition on prefixes.
Recovery classes (on the full schedule, with its aborts), as in Bernstein,
Hadzilacos and Goodman (1987), Section 1.2
is_recoverable(s) if T_i reads x from T_j (i != j) and c_i is
in s, then c_j < c_i
avoids_cascading_aborts(s) if T_i reads x from T_j (i != j), then
c_j < r_i(x)
is_strict(s) if w_j(x) < o_i(x) (i != j, o in r and w),
then a_j < o_i(x) or c_j < o_i(x)
Reads-from
An action is named by its occurrence id (txn, kind, item, k): the k-th
action of that kind on that item by that transaction, from 0. A read
r_i(x) reads from w_j(x) when w_j(x) comes before r_i(x), a_j does not
come before r_i(x), and every write w_k(x) between them has its a_k
before r_i(x). If no write qualifies, the read reads the initial value,
shown as None. The writer is a write occurrence, not only a transaction,
so a read between two writes of the same transaction on the same item
is told apart from a read after both.
Generators
interleavings(txns) every schedule that merges the sequences
of txns and keeps the order inside each
random_schedule(rng, txns) one of them, chosen uniformly with the
random.Random rng
Each element of txns is a sequence of actions or a string for parse.
"""
import itertools
import re
MAX_BRUTE_FORCE = 6
READ, WRITE, COMMIT, ABORT = "r", "w", "c", "a"
_KINDS = (READ, WRITE, COMMIT, ABORT)
_TOKEN = re.compile(r"^([rwca])(\d+)(?:\(([A-Za-z_][A-Za-z0-9_]*)\))?$")
# ---------------------------------------------------------------- basics
def parse(text):
"""Parse "r1(x) w2(x) c1 a2" into a tuple of actions."""
out = []
for tok in text.split():
m = _TOKEN.match(tok)
if not m:
raise ValueError("bad action %r" % tok)
kind, txn, item = m.group(1), int(m.group(2)), m.group(3)
if kind in (READ, WRITE) and item is None:
raise ValueError("a read or write needs an item: %r" % tok)
if kind in (COMMIT, ABORT) and item is not None:
raise ValueError("a commit or abort has no item: %r" % tok)
out.append((kind, txn, item))
s = tuple(out)
validate(s)
return s
def format(schedule):
"""Write a schedule in the notation of parse."""
parts = []
for kind, txn, item in schedule:
if item is None:
parts.append("%s%s" % (kind, txn))
else:
parts.append("%s%s(%s)" % (kind, txn, item))
return " ".join(parts)
format_schedule = format
def validate(schedule):
"""Raise ValueError unless each transaction ends at most once, at its end."""
ended = set()
for act in schedule:
if len(act) != 3:
raise ValueError("an action is (kind, txn, item): %r" % (act,))
kind, txn, item = act
if kind not in _KINDS:
raise ValueError("bad kind %r" % (kind,))
if (kind in (READ, WRITE)) != (item is not None):
raise ValueError("item must be set exactly for r and w: %r" % (act,))
if txn in ended:
raise ValueError("action after the end of transaction %r" % (txn,))
if kind in (COMMIT, ABORT):
ended.add(txn)
def transactions(schedule):
"""The transaction ids in the order of their first action."""
seen = []
for _, txn, _ in schedule:
if txn not in seen:
seen.append(txn)
return seen
def committed(schedule):
"""The set of ids that have a commit in the schedule."""
return {txn for kind, txn, _ in schedule if kind == COMMIT}
def aborted(schedule):
"""The set of ids that have an abort in the schedule."""
return {txn for kind, txn, _ in schedule if kind == ABORT}
def actions_of(schedule, txn):
"""The actions of one transaction, in order."""
return tuple(a for a in schedule if a[1] == txn)
def committed_projection(schedule):
"""The actions of the committed transactions, in the order of the schedule."""
validate(schedule)
keep = committed(schedule)
return tuple(a for a in schedule if a[1] in keep)
def conflicts(p, q):
"""True when p and q are reads or writes of different transactions on the
same item, and at least one of them is a write."""
return (p[0] in (READ, WRITE) and q[0] in (READ, WRITE)
and p[1] != q[1] and p[2] == q[2]
and (p[0] == WRITE or q[0] == WRITE))
def serial_schedule(schedule, order):
"""The serial schedule that runs the transactions of order one by one."""
out = []
for txn in order:
out.extend(actions_of(schedule, txn))
return tuple(out)
def _occurrences(schedule):
"""The occurrence id (txn, kind, item, k) of each action, by position."""
count = {}
ids = []
for kind, txn, item in schedule:
key = (txn, kind, item)
k = count.get(key, 0)
count[key] = k + 1
ids.append((txn, kind, item, k))
return ids
# ---------------------------------------------------------- equivalence
def _same_actions(s1, s2):
return sorted(_occurrences(s1), key=repr) == sorted(_occurrences(s2), key=repr)
def _conflict_pairs(schedule):
ids = _occurrences(schedule)
pairs = set()
for i in range(len(schedule)):
for j in range(i + 1, len(schedule)):
if conflicts(schedule[i], schedule[j]):
pairs.add((ids[i], ids[j]))
return pairs
def conflict_equivalent(s1, s2):
"""Same actions, and every pair of conflicting actions in the same order."""
return _same_actions(s1, s2) and _conflict_pairs(s1) == _conflict_pairs(s2)
def reads_from(schedule):
"""Map the occurrence id of each read to the write occurrence it reads
from, or to None for the initial value (see the module notes)."""
ids = _occurrences(schedule)
result = {}
for q, (kind, txn, item) in enumerate(schedule):
if kind != READ:
continue
ended_abort = {t for k, t, _ in schedule[:q] if k == ABORT}
source = None
for p in range(q - 1, -1, -1):
pk, pt, pi = schedule[p]
if pk == WRITE and pi == item and pt not in ended_abort:
source = ids[p]
break
result[ids[q]] = source
return result
def final_writes(schedule):
"""Map each written item to the occurrence id of its last write that is
not followed by an abort of its transaction."""
ids = _occurrences(schedule)
gone = aborted(schedule)
result = {}
for p, (kind, txn, item) in enumerate(schedule):
if kind == WRITE and txn not in gone:
result[item] = ids[p]
return result
def view_equivalent(s1, s2):
"""Same actions, the same reads-from map and the same final writes."""
return (_same_actions(s1, s2) and reads_from(s1) == reads_from(s2)
and final_writes(s1) == final_writes(s2))
# ------------------------------------------------------- serializability
def _orders(schedule, equivalent):
cp = committed_projection(schedule)
txns = sorted(committed(cp), key=repr)
if len(txns) > MAX_BRUTE_FORCE:
raise ValueError("brute force over %d committed transactions; at most %d"
% (len(txns), MAX_BRUTE_FORCE))
return [order for order in itertools.permutations(txns)
if equivalent(cp, serial_schedule(cp, order))]
def conflict_serializable_orders(schedule):
"""Every serial order of the committed transactions that is conflict
equivalent to the committed projection."""
return _orders(schedule, conflict_equivalent)
def view_serializable_orders(schedule):
"""Every serial order of the committed transactions that is view
equivalent to the committed projection."""
return _orders(schedule, view_equivalent)
def is_conflict_serializable(schedule):
return bool(conflict_serializable_orders(schedule))
def is_view_serializable(schedule):
return bool(view_serializable_orders(schedule))
# -------------------------------------------------------- recovery classes
def _position_of_end(schedule, kind):
return {txn: p for p, (k, txn, _) in enumerate(schedule) if k == kind}
def _foreign_reads(schedule):
"""(position of the read, reader, writer txn) for each read from another
transaction."""
validate(schedule)
ids = _occurrences(schedule)
rf = reads_from(schedule)
out = []
for q, (kind, txn, _) in enumerate(schedule):
if kind == READ:
src = rf[ids[q]]
if src is not None and src[0] != txn:
out.append((q, txn, src[0]))
return out
def is_recoverable(schedule):
"""If T_i reads from T_j (i != j) and c_i is in the schedule, then c_j < c_i."""
commit_at = _position_of_end(schedule, COMMIT)
for _, reader, writer in _foreign_reads(schedule):
if reader in commit_at:
if writer not in commit_at or commit_at[writer] > commit_at[reader]:
return False
return True
def avoids_cascading_aborts(schedule):
"""If T_i reads x from T_j (i != j), then c_j comes before the read."""
commit_at = _position_of_end(schedule, COMMIT)
for q, _, writer in _foreign_reads(schedule):
if writer not in commit_at or commit_at[writer] > q:
return False
return True
def is_strict(schedule):
"""If w_j(x) < o_i(x) with i != j, then T_j ended (c_j or a_j) before o_i(x)."""
validate(schedule)
end_at = _position_of_end(schedule, COMMIT)
end_at.update(_position_of_end(schedule, ABORT))
for q, (kind, txn, item) in enumerate(schedule):
if kind not in (READ, WRITE):
continue
for p in range(q):
pk, pt, pi = schedule[p]
if pk == WRITE and pi == item and pt != txn:
if pt not in end_at or end_at[pt] > q:
return False
return True
# ------------------------------------------------------------- generators
def _as_actions(txn):
return parse(txn) if isinstance(txn, str) else tuple(txn)
def interleavings(txns):
"""Yield every interleaving of the sequences, keeping each one in order."""
seqs = [_as_actions(t) for t in txns]
pos = [0] * len(seqs)
total = sum(len(s) for s in seqs)
current = []
def rec():
if len(current) == total:
yield tuple(current)
return
for i, seq in enumerate(seqs):
if pos[i] < len(seq):
current.append(seq[pos[i]])
pos[i] += 1
yield from rec()
pos[i] -= 1
current.pop()
yield from rec()
def random_schedule(rng, txns):
"""One interleaving, uniform over all interleavings: the next action comes
from a sequence with probability proportional to its remaining length."""
seqs = [_as_actions(t) for t in txns]
pos = [0] * len(seqs)
left = sum(len(s) for s in seqs)
out = []
while left:
r = rng.randrange(left)
for i, seq in enumerate(seqs):
rest = len(seq) - pos[i]
if r < rest:
out.append(seq[pos[i]])
pos[i] += 1
break
r -= rest
left -= 1
return tuple(out)
# -------------------------------------------------------------- self-test
def _self_test():
# A CSR schedule, equivalent to T1 T2 only.
s = parse("r1(x) w1(x) r2(x) r1(y) w2(x) w1(y) c1 c2")
assert format(s) == "r1(x) w1(x) r2(x) r1(y) w2(x) w1(y) c1 c2"
assert conflict_serializable_orders(s) == [(1, 2)]
assert is_view_serializable(s)
# The lost update: neither CSR nor VSR.
s = parse("r1(x) r2(x) w1(x) w2(x) c1 c2")
assert not is_conflict_serializable(s) and not is_view_serializable(s)
# Blind writes: VSR (as T1 T2 T3) but not CSR.
s = parse("r1(x) w2(x) w1(x) w3(x) c1 c2 c3")
assert not is_conflict_serializable(s)
assert view_serializable_orders(s) == [(1, 2, 3)]
# Not recoverable: T2 reads x from T1 and commits first.
s = parse("w1(x) r2(x) c2 c1")
assert not is_recoverable(s)
# Recoverable but not ACA; ACA but not strict; strict.
s = parse("w1(x) r2(x) c1 c2")
assert is_recoverable(s) and not avoids_cascading_aborts(s)
s = parse("w1(x) w2(x) c1 c2")
assert avoids_cascading_aborts(s) and not is_strict(s)
s = parse("w1(x) c1 r2(x) w2(x) c2")
assert is_strict(s)
# A read after an aborted write reads the initial value.
s = parse("w1(x) a1 r2(x) c2")
assert reads_from(s) == {(2, "r", "x", 0): None} and is_strict(s)
# Committed projection, interleavings and random schedules.
assert committed_projection(parse("r1(x) w2(x) a2 c1")) == parse("r1(x) c1")
allx = list(interleavings(["r1(x) w1(x)", "r2(x) c2"]))
assert len(allx) == 6 and len(set(allx)) == 6
import random
rng = random.Random(1)
t = [parse("r1(x) w1(y) c1"), parse("w2(x) c2"), parse("r3(y) c3")]
for _ in range(50):
assert random_schedule(rng, t) in set(interleavings(t))
return True
if __name__ == "__main__":
_self_test()
transaction_chopping.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transaction-chopping/. The authors are listed in prov/G7FCSD.jsonl.
"""Transaction chopping of Shasha, Llirbat, Simon and Valduriez (1995).
A transaction is a list of statements. A statement is ("r", item),
("w", item) or ("rollback",); the last one marks a place where the
program may roll back. A chopping of one transaction is a list of pieces,
and a piece is a half-open interval (start, end) of statement positions.
The pieces are contiguous, in order, and cover every position. A chopping
of the set is one such list per transaction.
finest_chopping(txns) the finest rollback-safe chopping with no SC-cycle
has_sc_cycle(txns, chop) the SC-cycle test by connected components
is_rollback_safe(t, pieces) every rollback statement is in the first piece
is_correct(txns, chop) rollback-safe and no SC-cycle
"""
ROLLBACK = "rollback"
def is_access(op):
return op[0] in ("r", "w")
def conflict(a, b):
"""Two accesses conflict when they touch the same item and one writes it."""
return (is_access(a) and is_access(b) and a[1] == b[1]
and (a[0] == "w" or b[0] == "w"))
class UnionFind:
"""Union by size with path compression."""
def __init__(self, keys):
self.parent = {k: k for k in keys}
self.size = {k: 1 for k in self.parent}
def find(self, k):
root = k
while self.parent[root] != root:
root = self.parent[root]
while self.parent[k] != root:
self.parent[k], k = root, self.parent[k]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
def _txn_conflicts(txns):
"""hits[i][p] is the set of j != i with an access in conflict with the
statement at position p of T_i; adj[j] is the set of k that conflict with T_j."""
n = len(txns)
hits = [[set() for _ in t] for t in txns]
adj = [set() for _ in range(n)]
for i in range(n):
for p, a in enumerate(txns[i]):
for j in range(n):
if j != i and any(conflict(a, b) for b in txns[j]):
hits[i][p].add(j)
adj[i].add(j)
return hits, adj
def _other_components(n, adj, i):
"""Union-find over the transactions other than T_i, joined by conflicts."""
others = [j for j in range(n) if j != i]
uf = UnionFind(others) # @line L2
for j in others:
for k in adj[j]:
if k != i:
uf.union(j, k) # @line L3
return uf
def _intervals(length, reach, first_end):
"""Cut 0..length into the finest intervals such that position p and
position reach[p] are in one interval, and 0..first_end is in one."""
pieces, start, cur = [], 0, first_end
for p in range(length):
cur = max(cur, reach[p]) # @line L9
if cur == p:
pieces.append((start, p + 1)) # @line L10
start = p + 1
return pieces
def private_chopping(txns, i, hits=None, adj=None):
"""The finest chopping of T_i when the other transactions are not chopped."""
if hits is None:
hits, adj = _txn_conflicts(txns)
n, t = len(txns), txns[i]
if not t:
return []
comp = _other_components(n, adj, i)
pos = UnionFind(range(len(t))) # @line L4
owner = {}
for p in range(len(t)): # @line L5
for j in hits[i][p]: # @line L6
r = comp.find(j)
if r in owner:
pos.union(owner[r], p) # @line L7
else:
owner[r] = p
last = {}
for p in range(len(t)):
last[pos.find(p)] = p
reach = [last[pos.find(p)] for p in range(len(t))]
rollbacks = [p for p, op in enumerate(t) if op[0] == ROLLBACK]
first_end = rollbacks[-1] if rollbacks else 0 # @line L8
return _intervals(len(t), reach, first_end)
def finest_chopping(txns):
"""The union of the private choppings of all transactions."""
hits, adj = _txn_conflicts(txns)
chop = []
for i in range(len(txns)): # @line L1
chop.append(private_chopping(txns, i, hits, adj))
return chop # @line L11
def valid_chopping(t, pieces):
"""True when pieces are contiguous intervals that cover t in order."""
pos = 0
for a, b in pieces:
if a != pos or b <= a:
return False
pos = b
return pos == len(t)
def is_rollback_safe(t, pieces):
rollbacks = [p for p, op in enumerate(t) if op[0] == ROLLBACK]
return not rollbacks or rollbacks[-1] < pieces[0][1]
def has_sc_cycle(txns, chop):
"""An SC-cycle exists if and only if two pieces of one T_i conflict with
the same connected component of the other transactions."""
hits, adj = _txn_conflicts(txns)
n = len(txns)
for i in range(n):
comp = _other_components(n, adj, i)
seen = {}
for k, (a, b) in enumerate(chop[i]):
for p in range(a, b):
for j in hits[i][p]:
r = comp.find(j)
if seen.setdefault(r, k) != k:
return True
return False
def is_correct(txns, chop):
"""The test of the theorem: rollback-safe and no SC-cycle."""
return (all(valid_chopping(t, c) for t, c in zip(txns, chop))
and all(is_rollback_safe(t, c) for t, c in zip(txns, chop) if t)
and not has_sc_cycle(txns, chop))
def parse_txn(text):
"""Parse "r(a) w(a) rollback r(b)" into a list of statements."""
out = []
for tok in text.split():
if tok == ROLLBACK:
out.append((ROLLBACK,))
else:
kind, item = tok[0], tok[2:-1]
if kind not in "rw" or tok[1] != "(" or tok[-1] != ")":
raise ValueError("bad statement %r" % tok)
out.append((kind, item))
return out
test_transaction_chopping.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transaction-chopping/. The authors are listed in prov/G7FCSD.jsonl.
import itertools
import random
import dbsched
from transaction_chopping import (
ROLLBACK, conflict, finest_chopping, has_sc_cycle, is_correct,
is_rollback_safe, parse_txn, private_chopping,
)
ITEMS = "xyz"
def gen(rng, n, m):
out = []
for _ in range(n):
t = [(rng.choice("rw"), rng.choice(ITEMS)) for _ in range(rng.randint(1, m))]
if rng.random() < 0.2:
t.insert(rng.randrange(len(t) + 1), (ROLLBACK,))
out.append(t)
return out
def all_choppings(t):
n = len(t)
out = []
for mask in range(1 << (n - 1)):
b = [0] + [p + 1 for p in range(n - 1) if mask >> p & 1] + [n]
out.append([(b[k], b[k + 1]) for k in range(len(b) - 1)])
return out
def coarser(c, f):
"""Every cut of c is a cut of f, so each piece of c is a union of pieces of f."""
return {b for _, b in c} <= {b for _, b in f}
def sc_cycle_brute(txns, chop):
"""Search every simple cycle of the chopping graph for one with an S edge
and a C edge."""
nodes = [(i, k) for i, c in enumerate(chop) for k in range(len(c))]
def label(u, v):
if u[0] == v[0]:
return "S"
a, b = chop[u[0]][u[1]], chop[v[0]][v[1]]
if any(conflict(p, q) for p in txns[u[0]][a[0]:a[1]]
for q in txns[v[0]][b[0]:b[1]]):
return "C"
return None
adj = {u: [(v, label(u, v)) for v in nodes if v != u and label(u, v)] for u in nodes}
def dfs(start, u, seen, kinds):
for v, lab in adj[u]:
if v == start and len(seen) >= 3 and kinds | {lab} == {"S", "C"}:
return True
if v not in seen and v > start:
seen.add(v)
if dfs(start, v, seen, kinds | {lab}):
return True
seen.discard(v)
return False
return any(dfs(s, s, {s}, frozenset()) for s in nodes)
def executions(txns, chop):
"""Every execution that runs each piece as one atomic step, the pieces of a
transaction in their order, as a dbsched schedule with the commit of a
transaction after its last piece."""
seqs = [[(i, k) for k in range(len(c))] for i, c in enumerate(chop)]
for order in dbsched.interleavings(seqs):
s = []
for i, k in order:
a, b = chop[i][k]
s.extend((op[0], i + 1, op[1]) for op in txns[i][a:b] if op[0] != ROLLBACK)
if k == len(chop[i]) - 1:
s.append(("c", i + 1, None))
yield tuple(s)
def all_executions_serializable(txns, chop):
return all(dbsched.is_conflict_serializable(s) for s in executions(txns, chop))
def test_transfer_example():
transfer = parse_txn("r(a) w(a) r(b) w(b)")
dep_b = parse_txn("r(b) w(b)")
dep_a = parse_txn("r(a) w(a)")
audit = parse_txn("r(a) r(b)")
txns = [transfer, dep_b, dep_a]
assert finest_chopping(txns) == [[(0, 2), (2, 4)], [(0, 2)], [(0, 2)]]
assert all_executions_serializable(txns, finest_chopping(txns))
# The audit joins the two deposits into one component: no cut is allowed.
txns = [transfer, dep_b, dep_a, audit]
assert finest_chopping(txns) == [[(0, 4)], [(0, 2)], [(0, 2)], [(0, 2)]]
bad = [[(0, 2), (2, 4)], [(0, 2)], [(0, 2)], [(0, 2)]]
assert has_sc_cycle(txns, bad) and not is_correct(txns, bad)
# The audit runs between the two pieces and sees a debited and b not yet credited.
s = dbsched.parse("r1(a) w1(a) r2(a) r2(b) c2 r1(b) w1(b) c1")
assert s in set(executions([transfer, audit], [[(0, 2), (2, 4)], [(0, 2)]]))
assert not dbsched.is_conflict_serializable(s)
def test_rollback_safety():
# A check on a before the write: the first piece must hold the rollback.
t1 = parse_txn("r(a) rollback w(a) r(b) w(b)")
txns = [t1, parse_txn("r(b) w(b)"), parse_txn("r(a) w(a)")]
assert finest_chopping(txns)[0] == [(0, 3), (3, 5)]
# A check on b at the end forces the whole transaction into one piece.
t1 = parse_txn("r(a) w(a) r(b) w(b) rollback")
txns = [t1, parse_txn("r(b) w(b)"), parse_txn("r(a) w(a)")]
assert finest_chopping(txns)[0] == [(0, 5)]
assert not is_rollback_safe(t1, [(0, 2), (2, 5)])
assert not is_correct(txns, [[(0, 2), (2, 5)], [(0, 2)], [(0, 2)]])
def test_no_conflict_means_one_piece_per_statement():
txns = [parse_txn("r(x) w(y) w(z)"), parse_txn("r(x) r(y)")]
# w(y) of T1 conflicts with T2; r(x) and w(z) conflict with nothing.
assert finest_chopping(txns)[0] == [(0, 1), (1, 2), (2, 3)]
def test_component_test_matches_brute_force():
rng = random.Random(11)
for _ in range(150):
txns = gen(rng, rng.randint(2, 3), 3)
for chop in itertools.product(*[all_choppings(t) for t in txns]):
chop = list(chop)
assert has_sc_cycle(txns, chop) == sc_cycle_brute(txns, chop)
def test_finest_is_correct_and_below_every_correct_chopping():
rng = random.Random(12)
for _ in range(300):
txns = gen(rng, rng.randint(2, 4), 4)
fine = finest_chopping(txns)
assert is_correct(txns, fine)
for i, t in enumerate(txns):
for c in all_choppings(t):
trial = [fine[j] if j != i else c for j in range(len(txns))]
# A private chopping is correct if and only if it is coarser.
assert is_correct(txns, trial) == coarser(c, fine[i])
assert fine[i] == private_chopping(txns, i)
everything = list(itertools.product(*[all_choppings(t) for t in txns]))
if len(everything) <= 64:
for chop in everything:
chop = list(chop)
ok = all(coarser(c, f) for c, f in zip(chop, fine))
assert is_correct(txns, chop) == ok
def test_correct_choppings_give_serializable_executions():
rng = random.Random(13)
for _ in range(25):
txns = gen(rng, 3, 3)
fine = finest_chopping(txns)
assert all_executions_serializable(txns, fine)
# Any chopping with an SC-cycle, on these sizes, has a bad execution.
for chop in itertools.product(*[all_choppings(t) for t in txns]):
chop = list(chop)
if has_sc_cycle(txns, chop):
assert not all_executions_serializable(txns, chop)
break
def test_two_pieces_against_one_transaction():
# The simplest SC-cycle: p and p' of T1 both conflict with T2.
t1, t2 = parse_txn("r(x) r(y)"), parse_txn("w(x) w(y)")
chop = [[(0, 1), (1, 2)], [(0, 2)]]
assert has_sc_cycle([t1, t2], chop)
s = dbsched.parse("r1(x) w2(x) w2(y) c2 r1(y) c1")
assert not dbsched.is_conflict_serializable(s)
assert s in set(executions([t1, t2], chop))
History
Dennis Shasha, Eric Simon and Patrick Valduriez presented the SC-cycle test and the finest chopping at SIGMOD 1992 as "simple rational guidance for chopping up transactions". The journal version with François Llirbat in ACM TODS 1995 extends the theory and reports performance studies. Lynx at SOSP 2013 brought the SC-graph analysis to geo-distributed storage, and later work by Cerone, Gotsman and Yang carried the test to weaker consistency models.
References
- Dennis Shasha, François Llirbat, Eric Simon and Patrick Valduriez, Transaction chopping, algorithms and performance studies, ACM Transactions on Database Systems 20(3), 1995, pages 325 to 363, the definitions of a chopping, of rollback-safe choppings and of the chopping graph with S and C edges, the theorem that a rollback-safe chopping with no SC-cycle is correct, and the algorithm for the finest chopping by private choppings
- Dennis Shasha, Eric Simon and Patrick Valduriez, Simple rational guidance for chopping up transactions, Proceedings of ACM SIGMOD 1992, pages 298 to 307, the first version of the SC-cycle test and of the finest chopping, chapter level only
- Bas Ketsman, Christoph Koch, Frank Neven and Brecht Vandevoort, Deciding robustness for lower SQL isolation levels, ACM Transactions on Database Systems 47(4), 2022, article 13, the related work, which places chopping as robustness against no isolation and notes that the SC-cycle test runs in polynomial time
- Yang Zhang, Russell Power, Siyuan Zhou, Yair Sovran, Marcos K. Aguilera and Jinyang Li, Transaction chains, achieving serializability with low latency in geo-distributed storage systems, Proceedings of the 24th ACM SOSP, 2013, the static analysis of chains with an SC-graph (Figure 2), chapter level only
- Andrea Cerone, Alexey Gotsman and Hongseok Yang, Transaction chopping for parallel snapshot isolation, Proceedings of DISC 2015, LNCS 9363, pages 388 to 404, the chopping test for parallel snapshot isolation, chapter level only
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G7FCSD Edit this page History Report an error Markdown