Algorithm Search⌘K

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
Properties
deterministic
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 T1,…,TnT_1, \ldots, T_n, the complete workload. Each program is a sequence of statements: reads r(x)r(x), writes w(x)w(x) 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 TiT_i cuts its sequence into pieces pi,1,…,pi,kp_{i,1}, \ldots, p_{i,k}. On this page each piece is a run of consecutive statements, and the pieces of TiT_i run in program order. A chopping of the workload is a chopping of each TiT_i.

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 TiT_i 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 T1,…,TnT_1, \ldots, T_n.

The test of Shasha et al.

  • A chopping is rollback-safe if, for every TiT_i 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 TiT_i depends only on the other transactions as wholes, not on how they are chopped. FINEST-CHOPPING computes this private chopping of each TiT_i and returns the union. The positions of TiT_i are 1,…,∣Ti∣1, \ldots, |T_i|.

  1. FINEST-CHOPPING(T_1, ..., T_n)
  2. 1for i ← 1 to n do
  3. 2U ← a union-find over the transactions T_j with j ≠ i
  4. 3for each pair j, k ≠ i such that T_j and T_k have conflicting accesses do UNION(U, j, k)
  5. 4P ← a union-find over the positions of T_i; owner ← an empty map
  6. 5for p ← 1 to |T_i| do
  7. 6for each j ≠ i such that T_j has an access in conflict with statement p of T_i do
  8. 7r ← FIND(U, j); if r ∈ owner then UNION(P, owner[r], p) else owner[r] ← p
  9. 8end ← the position of the last rollback statement of T_i, or 1 if there is none
  10. 9for p ← 1 to |T_i| do end ← max(end, the last position in the class of p in P)
  11. 10if end = p then cut T_i after position p
  12. 11return 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 TiT_i 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 TiT_i. This is exactly the condition for no SC-cycle through TiT_i: an SC-cycle that uses an S edge of TiT_i must leave TiT_i through a C edge, walk inside one component of the others, and come back through a C edge into a different piece of TiT_i. 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 aa and bb. The workload has a transfer T1=r(a) w(a) r(b) w(b)T_1 = r(a)\, w(a)\, r(b)\, w(b), a deposit T2=r(b) w(b)T_2 = r(b)\, w(b) on bb, and a deposit T3=r(a) w(a)T_3 = r(a)\, w(a) on aa. For T1T_1, the others are T2T_2 and T3T_3. They do not conflict, so lines L2 and L3 leave two components, {T2}\{T_2\} and {T3}\{T_3\}.

step statement pp of T1T_1 conflicts with owner classes of PP end cut
L5 to L7 1: r(a)r(a) T3T_3 {T3}↦1\{T_3\} \mapsto 1 {1},{2},{3},{4}\{1\}, \{2\}, \{3\}, \{4\}
L5 to L7 2: w(a)w(a) T3T_3 {1,2},{3},{4}\{1, 2\}, \{3\}, \{4\}
L5 to L7 3: r(b)r(b) T2T_2 {T2}↦3\{T_2\} \mapsto 3 {1,2},{3},{4}\{1, 2\}, \{3\}, \{4\}
L5 to L7 4: w(b)w(b) T2T_2 {1,2},{3,4}\{1, 2\}, \{3, 4\}
L8 1
L9, L10 p=1p = 1 2
L9, L10 p=2p = 2 2 after 2
L9, L10 p=3p = 3 4
L9, L10 p=4p = 4 4 after 4

The transfer becomes two pieces, r(a) w(a)r(a)\, w(a) and r(b) w(b)r(b)\, w(b). A deposit on aa can run between them and sees the debit, which is fine: in the equivalent serial order it runs after T1T_1. Both deposits stay whole, because each of their two statements conflicts with the transfer, which is one component for them.

Now add an audit T4=r(a) r(b)T_4 = r(a)\, r(b). It conflicts with T2T_2 and with T3T_3, so for T1T_1 the others form one component {T2,T3,T4}\{T_2, T_3, T_4\}, and every statement of T1T_1 lands in one class: the transfer cannot be chopped. The old chopping now has the SC-cycle p1,1→CT4→Cp1,2→Sp1,1p_{1,1} \xrightarrow{C} T_4 \xrightarrow{C} p_{1,2} \xrightarrow{S} p_{1,1}, and the execution r1(a) w1(a) r4(a) r4(b) c4 r1(b) w1(b) c1r_1(a)\, w_1(a)\, r_4(a)\, r_4(b)\, c_4\, r_1(b)\, w_1(b)\, c_1 shows why: the audit sees aa debited and bb not yet credited, and its conflict graph has the cycle T1→T4→T1T_1 \to T_4 \to T_1.

Rollbacks change the picture too. If the transfer checks the balance after r(a)r(a) and may roll back there, the first piece is r(a)r(a), rollback, w(a)w(a), 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 TiT_i 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 T1,…,TnT_1, \ldots, T_n. A chopping cuts each TiT_i into contiguous pieces. An execution EE runs every piece as a transaction. Pieces that the system aborts are restarted until they commit, and a rollback statement of TiT_i aborts TiT_i in the piece that contains it. Let CGP(E)CG_P(E) be the conflict graph of the committed pieces: an arc p→qp \to q when an access of pp comes before a conflicting access of qq in EE. The concurrency control of the pieces makes CGP(E)CG_P(E) acyclic. Let CGT(E)CG_T(E) be the conflict graph of the committed whole transactions: an arc Ta→TbT_a \to T_b (a≠ba \ne b) when an access of TaT_a comes before a conflicting access of TbT_b. By the serializability theorem, EE is conflict equivalent to a serial execution of the whole transactions if and only if CGT(E)CG_T(E) is acyclic. The chopping graph GG and SC-cycles are as defined on the page. For a fixed ii, let HiH_i be the graph on the transactions TjT_j, j≠ij \ne i, 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 TiT_i lies in its first piece. If TiT_i rolls back, it does so while the first piece runs, and that piece aborts; the later pieces never start, so no piece of TiT_i commits. Otherwise each piece is restarted until it commits. □\square

So the committed pieces form whole transactions, and CGT(E)CG_T(E) is defined on them.

Theorem 2 (Shasha et al.). If the chopping is rollback-safe and GG has no SC-cycle, then CGT(E)CG_T(E) is acyclic for every execution EE.

Proof. Suppose CGT(E)CG_T(E) has a cycle Ta1→Ta2→⋯→Tak→Ta1T_{a_1} \to T_{a_2} \to \cdots \to T_{a_k} \to T_{a_1} with k≥2k \ge 2 distinct transactions. Indices are taken modulo kk. The arc Taj→Taj+1T_{a_j} \to T_{a_{j+1}} comes from an access in a piece pjp_j of TajT_{a_j} that comes before a conflicting access in a piece qj+1q_{j+1} of Taj+1T_{a_{j+1}}. Then pj→qj+1p_j \to q_{j+1} is an arc of CGP(E)CG_P(E), and pjp_j and qj+1q_{j+1} are joined by a C edge in GG. In each transaction TajT_{a_j} of the cycle, the arc in ends at qjq_j and the arc out starts at pjp_j.

Case 1: qj=pjq_j = p_j for every jj. Then p1→p2→⋯→pk→p1p_1 \to p_2 \to \cdots \to p_k \to p_1 is a closed walk in CGP(E)CG_P(E) through kk pieces of distinct transactions, so it is a cycle, and CGP(E)CG_P(E) is not acyclic. This contradicts the model.

Case 2: qj≠pjq_j \ne p_j for some jj. Consider the closed walk in GG that goes p1,q2p_1, q_2 by a C edge, then q2,p2q_2, p_2 by an S edge if q2≠p2q_2 \ne p_2, then p2,q3p_2, q_3 by a C edge, and so on, until it returns to p1p_1. The transactions TajT_{a_j} are distinct, and inside one transaction the walk visits qjq_j and pjp_j, which are distinct whenever both appear. So no node repeats, and the walk is a simple cycle. It has k≥2k \ge 2 C edges and at least one S edge, so it has at least three nodes. It is an SC-cycle, a contradiction. □\square

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). GG has an SC-cycle if and only if, for some ii, two different pieces of TiT_i each contain a statement that conflicts with a transaction of the same component of the others.

Proof. (⇐\Leftarrow) Let pieces p≠p′p \ne p' of TiT_i conflict with TjT_j and TlT_l of one component KK of HiH_i. Take a shortest path Tj=U0,U1,…,Us=TlT_j = U_0, U_1, \ldots, U_s = T_l in HiH_i; its transactions are distinct and none is TiT_i. For each t<st < s choose pieces xtx_t of UtU_t and yt+1y_{t+1} of Ut+1U_{t+1} with conflicting accesses, let y0y_0 be a piece of U0U_0 that conflicts with pp, and let xsx_s be a piece of UsU_s that conflicts with p′p'. The walk p,y0,x0,y1,x1,…,ys,xs,p′,pp, y_0, x_0, y_1, x_1, \ldots, y_s, x_s, p', p uses C edges from pp to y0y_0, from each xtx_t to yt+1y_{t+1} and from xsx_s to p′p', an S edge from yty_t to xtx_t when they differ (drop the step when yt=xty_t = x_t), and the S edge from p′p' to pp. Its nodes are pieces of distinct transactions, except for the pairs yt,xty_t, x_t and p′,pp', p, which are distinct inside each pair. So it is a simple cycle with at least three nodes, an S edge and a C edge.

(⇒\Rightarrow) Let ZZ be a simple SC-cycle. Let u,vu, v be the ends of an S edge of ZZ; they are pieces of one transaction TiT_i. Remove that edge from ZZ to get a simple path from vv to uu. Two pieces of TiT_i are joined only by S edges, and ZZ has a C edge, whose ends lie in different transactions, so the path visits a piece of another transaction. Let ww be the last piece of TiT_i before the first such visit, and w′w' the first piece of TiT_i after it. They are different nodes of a simple path. Every node strictly between them is a piece of a transaction other than TiT_i, 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 KK of HiH_i. The node after ww conflicts with ww, and the node before w′w' conflicts with w′w', so ww and w′w' are different pieces of TiT_i that conflict with KK. □\square

The condition of Lemma 3 for a given ii depends on the chopping of TiT_i only, since HiH_i 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 ii, the chopping of TiT_i 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 TiT_i, two statements of TiT_i are in the same class of PP if and only if a chain of statements of TiT_i joins them, in which each consecutive pair conflicts with a common component of the others. All statements that conflict with one component KK are in one class.

Proof. Lines L2 and L3 finish before line L5 starts, so FIND(U,j)FIND(U, j) in line L7 returns the final representative of the component of TjT_j. Line L7 unites each statement that conflicts with KK with owner[K]owner[K], the first statement that did. So all such statements share a class, and every UNION joins two statements that conflict with a common component. □\square

Theorem 6 (finest chopping). Let FiF_i be the chopping of TiT_i made by lines L8 to L10. A contiguous chopping cic_i of TiT_i is rollback-safe and satisfies the condition of Lemma 3 for ii if and only if every cut of cic_i is a cut of FiF_i.

Proof. For a position pp, let last(p)last(p) be the last position in the class of pp, and let e0e_0 be the last rollback position of TiT_i, or 1. After line L9 at position pp, end=max⁡(e0,max⁡q≤plast(q))end = \max(e_0, \max_{q \le p} last(q)), and line L10 cuts after pp exactly when this value is pp.

(Only if.) Let cic_i 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 cic_i; so each class lies inside one piece of cic_i. Suppose cic_i cuts after a position pp where FiF_i does not, so end>pend > p there. If e0>pe_0 > p, then positions 1 and e0e_0 are on different sides of the cut, and the rollback statement at e0e_0 is not in the first piece of cic_i, a contradiction. Otherwise last(q)>plast(q) > p for some q≤pq \le p, and qq and last(q)last(q) are in one class but on different sides of the cut, a contradiction.

(If.) Every piece of cic_i is a union of pieces of FiF_i. The first piece of FiF_i ends at or after e0e_0, because end≥e0end \ge e_0 throughout; so the first piece of cic_i contains every rollback statement. If two pieces of cic_i had statements s,s′s, s' that conflict with one component KK, then by Lemma 5 ss and s′s' are in one class. For every position pp with first≤p<lastfirst \le p < last of that class, end≥last>pend \ge last > p, so FiF_i has no cut inside the span of the class; ss and s′s' are in one piece of FiF_i, hence in one piece of cic_i, a contradiction. □\square

Conclusion. Taking ci=Fic_i = F_i in Theorem 6 shows that each FiF_i passes the test, and Corollary 4 shows that the union FF has no SC-cycle; it is rollback-safe by construction. By Theorem 2, FF is correct. By Theorem 6 and Corollary 4, the choppings that pass the test are exactly those whose cuts are cuts of FF, so FF 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 nn be the number of transactions and mm 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: O(m2)O(m^2) time and O(mn)O(m n) space. For each ii, lines L2 and L3 make at most n2n^2 calls to UNION, and lines L5 to L7 make at most ∣Ti∣⋅n|T_i| \cdot n calls, so the whole loop makes O(n3+mn)O(n^3 + m n) union-find calls. With union by size and path compression, each call costs O(α(m))O(\alpha(m)) amortized, where α\alpha is the inverse Ackermann function. The sweep of lines L8 to L10 is linear. The total is O((m2+n3) α(m))O((m^2 + n^3)\, \alpha(m)) 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 pp and p′p' of TiT_i both conflict with an unchopped TjT_j, the execution p,Tj,p′p, T_j, p' gives the conflict cycle Ti→Tj→TiT_i \to T_j \to T_i.

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 TjT_j. A version that keys owner by jj itself merges two statements only when they conflict with the same transaction, and misses longer SC-cycles such as p→CT2→CT3→Cp′→Spp \xrightarrow{C} T_2 \xrightarrow{C} T_3 \xrightarrow{C} p' \xrightarrow{S} p. 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 PP after line L7 may interleave, as in classes {1,3}\{1, 3\} and {2}\{2\}. 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.

dbsched.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

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
  • a scene preset for the example