Algorithmresearch
Silo epoch-based OCC
Also called Silo, Silo commit protocol.
An optimistic commit protocol for multicore in-memory databases: lock the write set, read a global epoch, validate the read set by TIDs, then install. Reads never write shared memory.
- Time
- O(r + w log w) worst
- Space
- O(r + w) extra
- Where
- r = the size of the read set; w = the size of the write set
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephen Tu, Wenting Zheng, Eddie Kohler, Barbara Liskov, Samuel Madden, 2013
Silo is an in-memory database for multicore machines by Tu, Zheng, Kohler, Liskov and Madden (2013), and its commit protocol is a form of optimistic concurrency control. A transaction runs without locks and records the version (the TID) of each record it reads. At commit it locks the records it writes, reads a global epoch number, and then validates that every record it read still has the same TID and is not locked by another transaction. If so, it picks a TID in the current epoch and installs its writes. There is no shared counter: TIDs are chosen by each worker from the TIDs it saw, and the only shared word, the epoch, changes every 40 ms. Reads never write shared memory. The design is close to TL2 and other software transactional memory systems, which also validate a read set against version numbers; Silo replaces the global version clock of TL2 by the epoch and by local TID choice. The result is conflict serializable. The code on this page is a toy, single-threaded model of the protocol and not Silo itself.
In plain words
Many cores run transactions at the same time on data in memory. A shared counter for transaction numbers would make every core write the same memory word, and that alone limits speed. Silo avoids it. Each record carries a version stamp. A transaction remembers the stamps of what it read and keeps its writes private. To commit, it locks what it will write, looks once at a slowly moving clock (the epoch), and then checks that nothing it read has changed or is locked by someone else. If the check passes, it makes a new stamp a little larger than every stamp it saw, writes it with the new values, and unlocks. If the check fails, it aborts and runs again. The epoch groups transactions into time slices, which logging, recovery and memory cleanup use.
The problem
Give serializable transactions on a database in main memory, on a machine with tens of cores, so that throughput grows with the number of cores. The obstacles are writes to shared memory: a central lock manager, a central counter for transaction numbers, or reader counts on records all move cache lines between cores. Silo wants a protocol in which a read-only access to a record does not write anything shared, and in which the only global state is written rarely.
The algorithm
Each record has a TID word: the TID of the transaction that last wrote it, plus status bits, one of which is the lock bit. In Silo a TID is a 64-bit integer whose high bits hold the epoch in which the writer committed. A global epoch number is advanced by one designated thread, every 40 ms in the paper. Each worker keeps , the TID it chose last. maps each record read to the TID seen at the read, and maps each record written to its new value.
READ(T, x)- 1
if x ∈ W(T) then return W(T)[x] - 2
read x.value and x.tid as one consistent pair; add (x, x.tid) to R(T); return x.value WRITE(T, x, v)- 3
W(T)[x] ← v ▷ private until Phase 3 COMMIT(T) on worker w- 4
for x in W(T), in one fixed global order do lock(x) ▷ Phase 1 - 5
e ← E ▷ the serialization point - 6
for (x, t) in R(T) do ▷ Phase 2 - 7
if x.tid ≠ t or (x is locked and x ∉ W(T)) then unlock W(T); abort T - 8
tid ← the smallest TID in epoch e that is larger than every TID in R(T), every x.tid for x ∈ W(T), and last[w] - 9
last[w] ← tid - 10
for x in W(T) do x.value ← W(T)[x]; x.tid ← tid; unlock(x) ▷ Phase 3 ADVANCE-EPOCH() ▷ one thread, every 40 ms- 11
E ← E + 1
Phase 1 (line L4) locks the write set. The global order, the record addresses in Silo, prevents deadlock. The serialization point is line L5: Silo uses memory fences so that this read of comes after all the locks and before all the checks. Phase 2 (lines L6 and L7) aborts if a record read has a new TID or is locked by another transaction; a record locked by another may be about to change. In Silo the check also tests a latest-version bit for records that were replaced, and checks the version numbers of index nodes to catch phantoms in range scans. The TID of line L8 is larger than every TID the transaction saw. So the TIDs of one record grow, the TIDs of one worker grow, and a transaction that reads or overwrites the data of another gets a larger TID. TIDs do not follow anti-dependencies: if reads and later overwrites it, either TID may be larger. Phase 3 (line L10) writes each record and releases its lock in one store, since the lock bit is in the TID word.
Epochs. TIDs of different epochs agree with the serial order, and committed transactions of an earlier epoch never depend on transactions of a later one. Silo uses this for durability: it logs by epoch and tells clients that a transaction is durable once its whole epoch is on disk. Epochs also drive the reclamation of old records, as in epoch-based reclamation, and the snapshots for read-only transactions.
Example
Records and start at 0 with TID ; a TID is written (epoch, sequence). on worker 1 runs and on worker 2 runs . This is Figure 3 of the paper: in a serializable run both cannot read 0.
| step | action | line | (value, TID, lock) | (value, TID, lock) | |
|---|---|---|---|---|---|
| 1 | reads ; | L2 | 1 | 0, (0,0), free | 0, (0,0), free |
| 2 | reads ; | L2 | 1 | 0, (0,0), free | 0, (0,0), free |
| 3 | buffers , locks | L3, L4 | 1 | 0, (0,0), free | 0, (0,0), |
| 4 | reads | L5 | 1 | ||
| 5 | checks : same TID, not locked | L7 | 1 | ||
| 6 | picks and installs | L8, L10 | 1 | 0, (0,0), free | 1, (1,0), free |
| 7 | the epoch advances | L11 | 2 | ||
| 8 | buffers , locks , reads | L3 to L5 | 2 | 0, (0,0), | 1, (1,0), free |
| 9 | checks : TID , abort, unlock | L7 | 2 | 0, (0,0), free | |
| 10 | runs again: reads with TID , buffers | L2, L3 | 2 | ||
| 11 | locks , reads , checks , picks , installs | L4 to L10 | 2 | 2, (2,0), free | 1, (1,0), free |
The result is the serial order . If instead had locked before checked in step 5, would find locked and abort. In the toy test of this case, then commits, and the history is .
Correctness
The proof is in proofs/correctness.md. It is for the toy model, in which every step is atomic. Order the committed transactions by the time of line L5. For two conflicting operations, the one that comes first belongs to the transaction with the earlier serialization point. A write-write or write-read pair is ordered by the lock of the writer, which is held from before its serialization point until after its install. A read-write pair is ordered by Phase 2: if the writer had its serialization point first, it held the lock before the reader validated, so the reader saw either the lock or a new TID and aborted. So the committed projection is conflict equivalent to the serial order of the serialization points. The paper argues the same result by a reduction to strict two-phase locking: whenever validation succeeds, strict 2PL could have held a read lock on each record from the read to the commit. The proof also shows the TID rules: TIDs grow along every write-read and write-write dependency, along each worker and along each record, and epochs never go back along the serial order.
Proof: The Silo commit protocol is conflict serializable in the order of its serialization pointsfull
Model. This is the model of the implementation on the page. Every line of the pseudocode is one atomic step, and the steps of all transactions and of ADVANCE-EPOCH are interleaved in some order. Line L4 takes one lock per step and waits while another transaction holds it; line L7 checks one record per step; line L10 installs one record per step. A record is written only by line L10 of a transaction that holds its lock. A transaction reads at line L2 (line L1 returns its own write and is not an access to the database), and writes at line L10. For a committed transaction , let be the time of its line L5. Two operations of different committed transactions conflict when they access the same record and at least one is a write. There are no inserts, deletes or range scans.
Lemma 1 (locks). If a committed transaction writes , then holds the lock of during the whole interval from before until its write of , and no other transaction writes in that interval.
Proof. Line L4 locks all of before line L5. The lock of is released only at the install of in line L10, or at an abort, and does not abort. Only the lock holder writes .
Lemma 2 (write-write). If committed transactions both write , and writes it first, then .
Proof. By Lemma 1 each holds the lock of from before its serialization point to its write, and the two intervals cannot overlap. writes first, so the interval of ends before the interval of starts, and .
Lemma 3 (write-read). If committed reads after committed wrote it, then .
Proof. comes before the write of by Lemma 1. The read of comes after that write, and comes after all reads of , since line L5 runs after the program ends.
Lemma 4 (read-write). If committed reads before committed writes it, then .
Proof. Let be the TID that saw at its first read of , stored in by line L2. Suppose . locked before and holds it until its write of . Line L7 of checks after , so after locked . At that check, either still holds the lock, and sees locked by another transaction, or has written . In the second case is the TID of , or of a later writer. By Lemma 5 below, that TID is larger than , so . In both cases aborts, which contradicts the assumption that it commits. The serialization points are distinct steps, so . If also writes , it holds the lock itself, and Lemma 2 applies to the two writes.
Lemma 5 (TIDs grow). Every write of a record sets to a value larger than the value it replaces. The TID of a transaction is larger than every TID in its read set and larger than the previous TID of its worker. Its epoch is the value of at its serialization point.
Proof. Line L8 picks a TID in epoch above the maximum of the TIDs in , the current TIDs of the records in , and . Such a TID exists when the epoch of is at most . Every TID in the maximum was chosen by a transaction whose epoch was read at its serialization point before (by Lemmas 2 and 3 for records, and by the order of the worker for ), and never decreases, so the epoch of is at most . The records of are locked from before , so their TIDs do not change between line L8 and line L10.
Theorem 6. In every run, the committed projection of the history is conflict equivalent to the serial history of the committed transactions in the order of . So it is conflict serializable.
Proof. By Lemmas 2, 3 and 4, every pair of conflicting operations of two committed transactions comes in the same order as their serialization points. So every arc of the conflict graph goes forward in the order of , the graph is acyclic, and the serial order of puts every conflicting pair in the same order as the history. By the serializability theorem the two histories are conflict equivalent. Aborted transactions write nothing to the database, because they never reach line L10.
Corollary 7 (epochs and TIDs). Along the order of the epochs of committed transactions never decrease. If is a write-write or write-read arc of the conflict graph, then the TID of is smaller than the TID of . The TIDs of one worker increase.
Proof. The epoch of is at , and only grows. For a write-read arc on , saw a TID at least the TID of on (Lemma 5 for the later writers between them), and its own TID is larger. For a write-write arc on , line L8 of runs after installed , since waited for the lock, and its TID exceeds . The worker case is the term of line L8.
An arc from a read of to a write of need not have a larger TID at , so the TIDs alone are not a serial order; the epochs and the serialization points are. Without the check of line L7 Lemma 4 fails. The test test_without_validation_some_run_is_not_serializable finds such a run, and test_random_runs_are_serializable checks Theorem 6 and Corollary 7 on 400 seeded runs, together with a serial replay in the order of that gives the same reads and the same final values.
Complexity
A commit sorts and locks the write set, checks each entry of the read set once, and installs each write once: steps, plus the time spent waiting for locks that others hold. Waiting is short, because a lock is held only during the commit of a transaction, never during its execution. The read set and the write set take space. No step writes a shared word except the locks and installs of the records in , and the epoch update of one thread every 40 ms.
Measurements. These are results of the paper, not properties of the algorithm. On a machine with four 8-core Intel Xeon E7-4830 processors at 2.1 GHz (32 cores) and 256 GB of DRAM, running 64-bit Linux 3.2.0, Silo reached almost 700,000 transactions per second on the standard TPC-C mix on 32 cores, about 22,000 per core (SOSP 2013). The paper reports near-linear scaling with the number of cores on this benchmark.
Properties
- Serializable. Committed transactions are equivalent to their order of serialization points.
- Invisible reads. A read changes nothing in shared memory, so readers of a hot record do not slow each other down.
- No global counter. The TID comes from local information; the epoch is the only global word, and it is written rarely.
- Deadlock-free. Locks are taken only at commit and in one global order.
- Not opaque. A running transaction can read an inconsistent state, because nothing is checked until commit. A transaction that will abort can see values that no serial run produces. Unlike TL2, Silo does not check reads against a start time.
- Aborts under contention. A transaction aborts whenever a record it read was overwritten before its validation, even if a serial order exists.
Variants and improvements
- Snapshot transactions. Silo keeps old versions for a while and lets read-only transactions read a consistent snapshot of a recent epoch, so they never abort.
- Range scans. The index (a variant of Masstree, a B+ tree and trie for multicore machines) gives each leaf a version number; the transaction validates the versions of the leaves it scanned, which detects inserts into a scanned range, the phantom problem.
- Durability. SiloR (Zheng, Tu, Kohler and Liskov, OSDI 2014) adds parallel logging, checkpoints and recovery around the epochs.
- TicToc. Yu, Pavlo, Sanchez and Devadas (2016) compute a commit timestamp for each transaction from the read and write timestamps of the records it touched, which commits some schedules that Silo aborts.
- Transactional memory. TL2 uses a global version clock and validates at every read; NOrec uses one global sequence lock and value-based validation. Silo is closer to TL2 with the clock replaced by the epoch.
When to use it
Use a Silo-style protocol in a main-memory store on a multicore machine when transactions are short, mostly touch disjoint data, and are known in full when they start, such as stored procedures. It is a poor fit under high contention on a few hot records, where OCC aborts and retries waste work, and for long transactions that read much data, which are likely to fail validation; there, locking or a snapshot read for the long reader is better.
Pitfalls
- Reading the epoch too early. Line L5 must come after line L4. If a transaction reads before it holds its locks, a later epoch can contain a transaction that it depends on, and the epoch order no longer agrees with the serial order. Silo puts memory fences around line L5; without them a compiler or CPU can move the read.
- Not checking the lock bit. Line L7 must abort on a record locked by another transaction even when its TID is unchanged. A version of line L7 that tests only lets and of the example both commit with the values , which no serial order gives.
- Locks in arbitrary order. Line L4 must take the locks in one global order. Taking them in program order can deadlock two committing transactions that write the same two records.
- A TID that ignores the write set. Line L8 must exceed for each , not only the TIDs in . A blind write can otherwise get a TID smaller than the version it overwrites, and the TIDs of the record stop growing.
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()
silo_concurrency_control.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/silo-concurrency-control/. The authors are listed in prov/023YX3.jsonl.
"""A toy model of the Silo commit protocol (Tu, Zheng, Kohler, Liskov and
Madden, SOSP 2013).
This is not Silo. It runs in one thread, and a seeded scheduler interleaves
the steps of several simulated workers and of the thread that advances the
global epoch. Each step is atomic, so there are no memory fences, no
cache lines and no spinning. There are no inserts, deletes, range scans,
node sets, snapshot transactions, garbage collection or logging. What it
keeps is the order of the commit protocol: lock the write set in a global
order, read the epoch (the serialization point), validate the read set,
choose the TID, install and unlock.
A TID is a pair (epoch, sequence), compared as a tuple; the real system
packs the epoch into the high bits of a 64-bit word.
"""
class Record:
__slots__ = ("value", "tid", "owner")
def __init__(self, value):
self.value = value
self.tid = (0, 0)
self.owner = None # the transaction that holds the lock bit
class Txn:
def __init__(self, tid_name, worker, program, program_id=None):
self.name = tid_name # an int, unique for each attempt
self.worker = worker
self.program = list(program)
self.program_id = program_id
self.pc = 0
self.reads = {} # item -> TID seen at the first read
self.seen = [] # the values returned by reads, in order
self.writes = {} # item -> new value
self.phase = "exec"
self.locked = []
self.to_lock = []
self.to_check = []
self.to_install = []
self.epoch = None
self.tid = None
class Silo:
def __init__(self, items, initial=0, validate=True):
self.db = {x: Record(initial) for x in items}
self.E = 1
self.last = {} # worker -> its most recent TID
self.log = [] # actions for dbsched, in the order they happen
self.sp = [] # names of transactions, in the order of their serialization points
self.committed = {} # name -> Txn
self.check = validate # False gives the broken variant without Phase 2
# ------------------------------------------------------------ execution
def read(self, t, x):
if x in t.writes:
return t.writes[x] # @line L1
rec = self.db[x]
t.reads.setdefault(x, rec.tid) # @line L2
self.log.append(("r", t.name, x))
return rec.value
def write(self, t, x, v):
t.writes[x] = v # @line L3
def exec_step(self, t):
"""Run the next statement of the program. A write stores a value that
depends on every value the transaction has read so far."""
kind, x = t.program[t.pc]
if kind == "r":
t.seen.append(self.read(t, x))
else:
self.write(t, x, (t.program_id, x, tuple(t.seen)))
t.pc += 1
if t.pc == len(t.program):
t.phase = "lock"
t.to_lock = sorted(t.writes)
# --------------------------------------------------------------- commit
def lock_step(self, t):
"""Phase 1: lock the next record of the write set in sorted order.
Return False if another transaction holds it (the worker waits)."""
if t.to_lock:
x = t.to_lock[0]
rec = self.db[x]
if rec.owner is not None:
return False
rec.owner = t.name # @line L4
t.locked.append(x)
t.to_lock.pop(0)
if not t.to_lock:
t.phase = "epoch"
return True
def epoch_step(self, t):
t.epoch = self.E # @line L5
self.sp.append(t.name)
t.phase = "validate"
t.to_check = sorted(t.reads) if self.check else []
def validate_step(self, t):
"""Phase 2: check one record of the read set. Return False on abort."""
if t.to_check:
x = t.to_check.pop(0) # @line L6
rec = self.db[x]
if rec.tid != t.reads[x] or (rec.owner is not None and rec.owner != t.name):
self.abort(t) # @line L7
return False
if not t.to_check:
t.phase = "tid"
return True
def tid_step(self, t):
bound = max([t.reads[x] for x in t.reads]
+ [self.db[x].tid for x in t.writes]
+ [self.last.get(t.worker, (0, 0))])
assert bound[0] <= t.epoch
t.tid = (t.epoch, bound[1] + 1) if bound[0] == t.epoch else (t.epoch, 0) # @line L8
self.last[t.worker] = t.tid # @line L9
t.phase = "install"
t.to_install = sorted(t.writes)
def install_step(self, t):
"""Phase 3: write one record with the new TID and release its lock."""
if t.to_install:
x = t.to_install.pop(0)
rec = self.db[x]
rec.value, rec.tid, rec.owner = t.writes[x], t.tid, None # @line L10
self.log.append(("w", t.name, x))
if not t.to_install:
self.log.append(("c", t.name, None))
self.committed[t.name] = t
t.phase = "done"
def abort(self, t):
for x in t.locked:
self.db[x].owner = None
self.sp.remove(t.name)
self.log.append(("a", t.name, None))
t.phase = "aborted"
def advance_epoch(self):
self.E += 1 # @line L11
def step(self, t):
"""One atomic step of t. Return False if t had to wait."""
if t.phase == "exec":
self.exec_step(t)
elif t.phase == "lock":
return self.lock_step(t)
elif t.phase == "epoch":
self.epoch_step(t)
elif t.phase == "validate":
self.validate_step(t)
elif t.phase == "tid":
self.tid_step(t)
elif t.phase == "install":
self.install_step(t)
return True
def simulate(rng, workers, items, epoch_rate=0.05, retries=2, validate=True):
"""Run the programs of each worker one after the other. workers is a list
of lists of programs; a program is a list of ("r", x) and ("w", x). An
aborted attempt restarts with a new name, at most retries times. Return
the Silo object, with its log and its committed transactions."""
silo = Silo(items, validate=validate)
queues = [[(pid, p) for pid, p in progs] for progs in workers]
current = [None] * len(workers)
tries = [0] * len(workers)
names = iter(range(1, 10 ** 9))
while True:
live = [w for w in range(len(workers)) if current[w] or queues[w]]
if not live:
return silo
if rng.random() < epoch_rate:
silo.advance_epoch()
continue
w = rng.choice(live)
if current[w] is None:
pid, prog = queues[w][0]
current[w] = Txn(next(names), w, prog, pid)
t = current[w]
silo.step(t)
if t.phase == "done":
queues[w].pop(0)
current[w], tries[w] = None, 0
elif t.phase == "aborted":
current[w] = None
tries[w] += 1
if tries[w] > retries:
queues[w].pop(0)
tries[w] = 0
test_silo_concurrency_control.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/silo-concurrency-control/. The authors are listed in prov/023YX3.jsonl.
import random
import dbsched
from silo_concurrency_control import Silo, Txn, simulate
ITEMS = ["x", "y", "z"]
def workload(rng, n_programs, n_workers):
workers = [[] for _ in range(n_workers)]
for pid in range(n_programs):
prog = [(rng.choice("rw"), rng.choice(ITEMS)) for _ in range(rng.randint(1, 3))]
workers[rng.randrange(n_workers)].append((pid, prog))
return workers
def replay(order, txns):
"""Run the committed transactions one by one in the given order and
return the values each one reads and the final state."""
db = {x: 0 for x in ITEMS}
seen = {}
for name in order:
t = txns[name]
mine, vals = {}, []
for kind, x in t.program:
if kind == "r":
vals.append(mine.get(x, db[x]))
else:
mine[x] = (t.program_id, x, tuple(vals))
db.update(mine)
seen[name] = vals
return seen, db
def check_run(silo):
log = tuple(silo.log)
dbsched.validate(log)
cp = dbsched.committed_projection(log)
order = [n for n in silo.sp if n in silo.committed]
# The serialization points give a conflict-equivalent serial order.
assert dbsched.conflict_equivalent(cp, dbsched.serial_schedule(cp, order))
assert dbsched.is_conflict_serializable(log)
# The same reads and the same final state as the serial run in that order.
seen, final = replay(order, silo.committed)
for name, t in silo.committed.items():
assert t.seen == seen[name]
assert {x: r.value for x, r in silo.db.items()} == final
# Epochs never go back along the serial order.
epochs = [silo.committed[n].epoch for n in order]
assert epochs == sorted(epochs)
# TIDs grow along write-read and write-write dependencies, per record
# and per worker.
tid = {n: t.tid for n, t in silo.committed.items()}
for i, p in enumerate(cp):
for q in cp[i + 1:]:
if p[0] == "w" and dbsched.conflicts(p, q):
assert tid[p[1]] < tid[q[1]]
by_worker = {}
for n in order:
by_worker.setdefault(silo.committed[n].worker, []).append(n)
for names in by_worker.values():
names.sort()
assert [tid[n] for n in names] == sorted(tid[n] for n in names)
for t in silo.committed.values():
assert t.tid[0] == t.epoch
def drive(silo, t, steps):
for _ in range(steps):
assert silo.step(t)
def test_read_write_conflict_of_figure_3():
# T1 reads x and writes y; T2 reads y and writes x. Both read 0. T1
# commits first, so T2 sees a new TID on y in Phase 2 and aborts.
silo = Silo(ITEMS)
t1 = Txn(1, 0, [("r", "x"), ("w", "y")], "A")
t2 = Txn(2, 1, [("r", "y"), ("w", "x")], "B")
silo.step(t1)
silo.step(t2)
silo.step(t1) # w(y) buffered
silo.step(t2) # w(x) buffered
silo.step(t1) # lock y
silo.step(t1) # e = 1, the serialization point of T1
silo.step(t2) # lock x
silo.step(t2) # e = 1, the serialization point of T2
silo.step(t1) # validate x: T2 holds its lock, so T1 aborts
assert t1.phase == "aborted"
silo.step(t2) # validate y: same TID, and T1 released the lock
drive(silo, t2, 2) # TID, install x
assert t2.phase == "done" and t2.tid == (1, 0)
assert dbsched.format(silo.log) == "r1(x) r2(y) a1 w2(x) c2"
def test_one_commits_when_the_other_runs_later():
silo = Silo(ITEMS)
t1 = Txn(1, 0, [("r", "x"), ("w", "y")], "A")
t2 = Txn(2, 1, [("r", "y"), ("w", "x")], "B")
silo.step(t1)
silo.step(t2) # T2 reads y = 0 with TID (0, 0)
drive(silo, t1, 6) # w, lock y, epoch, validate x, TID, install y
assert t1.phase == "done" and t1.tid == (1, 0)
silo.advance_epoch()
drive(silo, t2, 4) # w, lock x, epoch 2, validate y
assert t2.phase == "aborted" # y now has TID (1, 0)
t3 = Txn(3, 1, [("r", "y"), ("w", "x")], "B")
drive(silo, t3, 7)
assert t3.phase == "done" and t3.tid == (2, 0)
assert silo.db["x"].value == ("B", "x", (("A", "y", (0,)),))
def test_tid_rule():
# Same epoch: one more than the largest TID seen; new epoch: (e, 0).
silo = Silo(ITEMS)
silo.db["x"].tid = (1, 5)
t = Txn(1, 0, [("r", "x"), ("w", "y")], "A")
drive(silo, t, 7)
assert t.tid == (1, 6)
silo.advance_epoch()
u = Txn(2, 0, [("w", "z")], "B")
drive(silo, u, 6) # write, lock, epoch, validate, TID, install
assert u.tid == (2, 0)
v = Txn(3, 0, [("w", "z")], "C")
drive(silo, v, 6) # the worker's last TID is (2, 0)
assert v.tid == (2, 1)
def test_random_runs_are_serializable():
rng = random.Random(2013)
commits = aborts = 0
for _ in range(400):
workers = workload(rng, rng.randint(2, 5), rng.randint(2, 4))
silo = simulate(rng, workers, ITEMS, epoch_rate=0.1)
check_run(silo)
commits += len(silo.committed)
aborts += sum(1 for a in silo.log if a[0] == "a")
assert commits > 1000 and aborts > 20
def test_lock_waits_keep_the_order():
silo = Silo(ITEMS)
t1 = Txn(1, 0, [("w", "x"), ("w", "y")], "A")
t2 = Txn(2, 1, [("w", "y")], "B")
drive(silo, t1, 3) # both writes, lock x
drive(silo, t2, 2) # write, lock y
assert not silo.step(t1) # y is locked: T1 waits
drive(silo, t2, 4) # epoch, validate, TID, install y
drive(silo, t1, 6) # lock y, epoch, validate, TID, install x and y
assert t2.tid < t1.tid and silo.db["y"].value[0] == "A"
def test_without_validation_some_run_is_not_serializable():
rng = random.Random(7)
found = False
for _ in range(300):
workers = workload(rng, rng.randint(2, 5), rng.randint(2, 4))
silo = simulate(rng, workers, ITEMS, epoch_rate=0.1, validate=False)
if not dbsched.is_conflict_serializable(tuple(silo.log)):
found = True
break
assert found
History
Kung and Robinson introduced optimistic concurrency control in 1981. Work on software transactional memory in the 2000s, in particular TL2 (2006), made validation of a read set by version numbers fast. Stephen Tu, Wenting Zheng, Eddie Kohler, Barbara Liskov and Samuel Madden presented Silo at SOSP 2013; it took its index from Masstree (Mao, Kohler and Morris, 2012) and replaced the central transaction counter by epochs and local TIDs. SiloR added fast durability and recovery in 2014, and later in-memory OCC protocols such as TicToc (2016) were measured against Silo.
References
- Stephen Tu, Wenting Zheng, Eddie Kohler, Barbara Liskov and Samuel Madden, Speedy transactions in multicore in-memory databases, Proceedings of the 24th ACM SOSP, 2013, pages 18 to 32, Section 4.1 (epochs, updated every 40 ms), Section 4.2 (TIDs and the rule for choosing one), Section 4.4 and Figure 2 (the commit protocol and its serializability argument), Section 5.1 (the machine) and Figures 5 and 6 (TPC-C throughput)
- H. T. Kung and John T. Robinson, On optimistic methods for concurrency control, ACM Transactions on Database Systems 6(2), 1981, pages 213 to 226, the read, validation and write phases that Silo refines, chapter level only
- Yandong Mao, Eddie Kohler and Robert Morris, Cache craftiness for fast multicore key-value storage, Proceedings of EuroSys 2012, the Masstree index that Silo builds on, chapter level only
- Xiangyao Yu, Andrew Pavlo, Daniel Sanchez and Srinivas Devadas, TicToc, time traveling optimistic concurrency control, Proceedings of ACM SIGMOD 2016, pages 1629 to 1642, a later OCC protocol that computes commit timestamps from data, chapter level only
- Wenting Zheng, Stephen Tu, Eddie Kohler and Barbara Liskov, Fast databases with fast durability and recovery through multicore parallelism, Proceedings of USENIX OSDI 2014, pages 465 to 477, SiloR, the logging, checkpoint and recovery design built on Silo, 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 023YX3 Edit this page History Report an error Markdown