Techniqueadvanced
Command logging
Also called stored procedure logging.
Log only the transaction requests of a deterministic in-memory database and recover by replaying them from a checkpoint.
Command logging, or stored procedure logging, is a recovery technique for in-memory databases in which every transaction is a call of a stored procedure. The log holds one small record per transaction: its id, the name of the procedure and the parameters, and no data at all. Recovery loads the newest snapshot of the database and runs the logged procedures again, in the same order. This works only if the execution is deterministic: the same procedure with the same parameters on the same state must make the same changes. Malviya, Weisberg, Madden and Stonebraker (ICDE 2014) built it in VoltDB and measured it against physiological logging, the record format of ARIES. It is the far end of logical logging: the logged operation is the whole transaction.
In plain words
A cook keeps a notebook. One way is to write down, after each step, how much of each thing is in each pot. That takes many lines per dish.
Another way is to write only the order: "dish 41, soup, for 3 people". If the cook always follows the recipe in the same way, the order is enough. After a fire, the cook takes the last photo of the kitchen and cooks every order written after the photo again, in the same order. The kitchen ends up the same.
This only works if the recipe never says "add a pinch, as you like". Every choice must come from the order itself. A random choice is fine only if it is made with a fixed rule, for example from the order number.
Short notes make cooking fast. The price is that recovery must cook every dish again.
When it applies
- The whole database is in main memory, and the disk holds only the log and snapshots.
- Every transaction is a stored procedure, or another request that the system can run again from its text and its parameters.
- Execution is deterministic: transactions run in one fixed serial order, for example one at a time per partition as in VoltDB, or in an order that a sequencer fixes before execution as in Calvin. Calls to the clock or to a random source must take their values from the log record, for example from a seed equal to the transaction id.
- Fast normal processing matters more than fast recovery, or recovery is rare because replicas take over after a failure.
The template
The log is an append-only file of command records. A snapshot is transaction consistent: it holds the effects of exactly the transactions up to one point in the serial order, and it stores that point.
EXECUTE(proc, params) ▷ normal work, one transaction at a time- 1
t ← the next transaction id; append ⟨t, proc, params⟩ to the log tail - 2
run proc(params) on the database in memory, with a random source seeded by t - 3
at the next group commit: write the log tail to stable storage, then report its transactions to the clients CHECKPOINT()- 4
between two transactions: mark a snapshot of the database with the LSN of the last logged transaction - 5
write the snapshot to disk while transactions go on (copy on write); when it is complete, it becomes the newest checkpoint RECOVER()- 6
load the newest complete snapshot, with its LSN c, and rebuild the indexes in memory - 7
for each command record r in the stable log after c, in log order do - 8
run r.proc(r.params) with the random source seeded by r.t
A transaction that the procedure itself aborts writes the same record. Its replay aborts again, at the same point, because the state is the same. A transaction whose record is in the tail at a crash was never reported, and it is lost with the tail: the state after recovery is that of a serial run of exactly the stable commands. The snapshot in line L5 must hold only the effects of stable commands; the code forces the tail before it records a snapshot.
Why it works. By determinism and induction over the log, the state after the replay of the first records is the state that normal work had after transaction . The snapshot is the state after transaction , so lines L7 and L8 give the state after the last stable record. Every reported transaction is stable, by line L3. Recovery writes nothing to disk, so a crash during recovery only makes it start again. The tests check this by a crash after every prefix of a random workload with group commits and checkpoints.
Cost. For one restart:
- Log records read. The command records after the snapshot. The snapshot interval bounds them: a checkpoint is the only thing that shortens the replay.
- Pages read and written. The whole snapshot is read once. Replay writes nothing to disk; the next checkpoint writes a new snapshot.
- Work. Each replayed transaction runs again in full, reads included, so replay costs about as much as the original work. Physiological redo instead applies only the changes, and can run in parallel per page.
- Log volume per update. One record per transaction, whatever the number of updates in it. Malviya et al. report command records of 50 to 170 bytes.
Measurements (Malviya, Weisberg, Madden and Stonebraker, ICDE 2014; VoltDB with command logging and with an ARIES-style physiological log; a two-socket Intel Xeon machine at 2.4 GHz with 8 cores and 24 GB of memory; group commit every 5 ms):
- On TPC-C, throughput with command logging was about 1.5 times that with physiological logging. With 50 percent distributed transactions the gain was still about 1.4 times.
- Physiological logging wrote about 10 times as many log bytes on TPC-C.
- Recovery was slower with command logging: replay of the physiological log was about 1.5 times faster on TPC-C and about 5 times faster on the Voter benchmark.
These numbers hold for that system, workload and machine. They are not a guarantee for other systems.
Example. Accounts a, b, c and d hold 100 each. The log holds three records: 1001 transfer(a, b, 500), 1002 transfer(a, b, 60), 1003 transfer(a, b, 60). The first aborts, since a has only 100. The second moves 60. The third aborts, since a has only 40. The newest snapshot has LSN 0. After a crash, recovery loads it and runs the three records again; the same two aborts happen, and the state is a = 40, b = 160. A physiological log would hold the before and after values of a and b for record 1002, and nothing for the aborts.
Classic examples
- VoltDB logs the stored procedure calls of each transaction with group commit and takes asynchronous transaction-consistent snapshots, as described by Malviya et al. It runs the transactions of a partition one at a time, so each partition is deterministic, and a coordinator logs the distributed transactions.
- Calvin fixes the order of the transaction inputs before it runs them, and replicates and logs only the inputs. See Calvin.
- State machine replication. A replicated log of commands that every replica applies in the same order is the same idea used for replication instead of recovery; see state machine replication.
- Statement-based replication in some SQL systems ships the SQL text of each statement to replicas. It has the same need for determinism, and it fails on statements whose effect depends on the clock or on an order of rows that is not fixed.
Variations
- Command logging with physical logging for some transactions. Log the changes of a transaction that is not deterministic, or that is very long, and the command for the others.
- Parallel replay. Replay can run the commands of different partitions in parallel, as long as each partition keeps its order and distributed transactions are synchronized across the partitions they touch.
- Replicas instead of recovery. With a replica that runs the same commands, a failure is handled by failover, and the slow replay is needed only when all replicas fail.
- Asynchronous command logging. Report a transaction before its record is stable. This is faster but loses reported transactions in a crash.
Pitfalls
- Hidden non-determinism. A call to the clock, to a random source that is not seeded from the log, to an outside service, or a loop over a hash table whose order is not fixed makes the replay differ. The tests show a procedure that reads a clock and gets another value in the replay.
- A snapshot that is not transaction consistent. A fuzzy snapshot of the kind that physiological redo accepts is wrong here: replaying a whole transaction on a state that already holds half of it applies the first half twice.
- A snapshot ahead of the stable log. If the snapshot holds the effect of a command that the crash then loses from the tail, the next transaction after recovery gets the same LSN with other contents.
- Long replay. Replay time grows with the time since the last snapshot and with the cost of the transactions, reads included. Take snapshots often enough for the recovery time that the system must meet.
- A changed procedure. If the code of a stored procedure changes between the run and the replay, the replay runs the new code. The log or the snapshot must name the version of each procedure.
Code
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
# Part of https://algorithm.tamnd.com/command-logging/. The authors are listed in prov/DQZNNJ.jsonl.
"""Command logging for a deterministic in-memory database.
Transactions are stored procedures that run one at a time. The log holds one
record per transaction: its id, the name of the procedure and the parameters.
The record goes into the log tail before the procedure runs, and a group
commit writes the tail to stable storage and only then reports the
transactions. A checkpoint is a transaction-consistent snapshot, taken between
two transactions and written in steps. Recovery loads the newest complete
snapshot and runs the logged procedures after it again, in log order.
A procedure gets its random numbers from a source seeded by its transaction
id, so that the replay makes the same choices.
"""
import random
from dataclasses import dataclass
ACCOUNTS = ["a", "b", "c", "d"]
def deposit(db: dict, rnd: random.Random, acct: str, amount: int) -> bool:
db[acct] += amount
return True
def transfer(db: dict, rnd: random.Random, src: str, dst: str, amount: int) -> bool:
if db[src] < amount:
return False # the procedure aborts, and it aborts again in the replay
db[src] -= amount
db[dst] += amount
return True
def bonus(db: dict, rnd: random.Random, acct: str) -> bool:
db[acct] += rnd.randint(1, 50) # a random choice, seeded by the transaction id
return True
PROCS = {"deposit": deposit, "transfer": transfer, "bonus": bonus}
@dataclass(frozen=True)
class Cmd:
lsn: int
txn: int
proc: str
params: tuple
@dataclass(frozen=True)
class Snapshot:
lsn: int # the last command whose effect the snapshot holds
state: dict
class CmdDb:
def __init__(self, log: list | None = None, snapshots: list | None = None, procs: dict = PROCS):
self.procs = procs
self.log: list[Cmd] = list(log or []) # stable
self.tail: list[Cmd] = []
self.snapshots: list[Snapshot] = list(snapshots or [Snapshot(0, {k: 100 for k in ACCOUNTS})])
self.state: dict = dict(self.snapshots[-1].state)
self.writing: tuple | None = None # (lsn, copy, keys written, keys left)
def _run(self, c: Cmd) -> bool:
rnd = random.Random(c.txn) # @line L2
return self.procs[c.proc](self.state, rnd, *c.params) # @line L2
def submit(self, proc: str, *params) -> int:
"""Log a transaction in the tail and run it. Return its id."""
lsn = len(self.log) + len(self.tail) + 1
c = Cmd(lsn, txn=1000 + lsn, proc=proc, params=params) # @line L1
self.tail.append(c) # @line L1
self._run(c)
return c.txn
def group_commit(self) -> list[int]:
"""Write the tail to the stable log. Return the ids that may now be reported."""
done = [c.txn for c in self.tail]
self.log.extend(self.tail) # @line L3
self.tail = []
return done # @line L3
def begin_checkpoint(self) -> None:
"""Take a snapshot between two transactions. A real system marks it and
copies a record only before a later transaction changes it (copy on
write); here the copy is made at once and written in steps."""
lsn = len(self.log) + len(self.tail) # @line L4
self.writing = (lsn, dict(self.state), {}, sorted(self.state)) # @line L4
def checkpoint_step(self) -> None:
lsn, copy, out, left = self.writing
if left:
out[left[0]] = copy[left[0]] # @line L5
self.writing = (lsn, copy, out, left[1:])
return
if lsn > len(self.log): # the snapshot may hold only stable commands
self.group_commit()
self.snapshots.append(Snapshot(lsn, out)) # @line L5
self.writing = None
def crash(self) -> "CmdDb":
return CmdDb(self.log, self.snapshots, self.procs)
def recover(self) -> int:
"""Load the newest complete snapshot and replay the log after it.
Return the number of commands replayed."""
snap = self.snapshots[-1] # @line L6
self.state = dict(snap.state) # @line L6
replayed = 0
for c in self.log[snap.lsn:]: # @line L7
self._run(c) # @line L8
replayed += 1
return replayed
test_command_logging.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/command-logging/. The authors are listed in prov/DQZNNJ.jsonl.
"""Command logging checked by crash injection.
A random workload of procedures, group commits and checkpoints is cut by a
crash after every prefix. Recovery must give the state of a serial run of
exactly the commands in the stable log, and every reported transaction must
be among them.
"""
import random
from command_logging import ACCOUNTS, PROCS, CmdDb
def random_action(db: CmdDb, rng: random.Random, reported: set, states: dict) -> None:
r = rng.random()
if r < 0.55:
kind = rng.choice(sorted(PROCS))
if kind == "deposit":
db.submit("deposit", rng.choice(ACCOUNTS), rng.randint(1, 30))
elif kind == "transfer":
src, dst = rng.sample(ACCOUNTS, 2)
db.submit("transfer", src, dst, rng.randint(1, 150))
else:
db.submit("bonus", rng.choice(ACCOUNTS))
states[len(db.log) + len(db.tail)] = dict(db.state)
elif r < 0.75:
reported.update(db.group_commit())
elif r < 0.85 and db.writing is None:
db.begin_checkpoint()
elif db.writing is not None:
db.checkpoint_step()
def test_crash_at_every_prefix() -> None:
for seed in range(5):
steps = 80
for k in range(steps + 1):
rng = random.Random(seed)
db = CmdDb()
reported: set = set()
states = {0: dict(db.state)}
for _ in range(k):
random_action(db, rng, reported, states)
stable = len(db.log)
db = db.crash()
db.recover()
# the state after the last stable command, as it was before the crash
assert db.state == states[stable]
assert reported <= {c.txn for c in db.log}
def test_recovery_equals_replay_from_the_start() -> None:
rng = random.Random(3)
db = CmdDb()
reported: set = set()
for _ in range(300):
random_action(db, rng, reported, {})
db.group_commit()
db = db.crash()
replayed = db.recover()
full = CmdDb(db.log)
full.snapshots = full.snapshots[:1]
assert full.recover() == len(db.log)
assert full.state == db.state
# the snapshot bounds the replay to the commands after it
assert replayed == len(db.log) - db.snapshots[-1].lsn
def test_crash_during_recovery() -> None:
rng = random.Random(8)
db = CmdDb()
for _ in range(200):
random_action(db, rng, set(), {})
db.group_commit()
expect = db.state
# recovery changes only memory, so a crash during it loses nothing
db = db.crash()
db.recover()
db = db.crash()
db.recover()
assert db.state == expect
def test_aborts_replay_as_aborts() -> None:
db = CmdDb()
db.submit("transfer", "a", "b", 500) # aborts: a has 100
db.submit("transfer", "a", "b", 60)
db.submit("transfer", "a", "b", 60) # aborts: a has 40
db.group_commit()
db = db.crash()
db.recover()
assert db.state == {"a": 40, "b": 160, "c": 100, "d": 100}
def test_a_procedure_that_is_not_deterministic_breaks_recovery() -> None:
clock = [0]
def stamp(state: dict, rnd: random.Random, acct: str) -> bool:
clock[0] += 7 # reads a clock outside the database, not the seeded source
state[acct] += clock[0]
return True
db = CmdDb(procs=dict(PROCS, stamp=stamp))
db.submit("stamp", "a")
db.submit("bonus", "b")
db.group_commit()
before = dict(db.state)
db = db.crash()
db.recover()
assert db.state["b"] == before["b"] # the seeded source gives the same bonus
assert db.state["a"] != before["a"] # the clock does not
Exercises
- A procedure reads all rows of a table and updates the first one in the order of a hash table. Give two runs with the same log and different results, and two ways to make the procedure deterministic.
- In the example, the snapshot is taken after record 1002 but before it is stable, and the tail is lost. Describe the state after recovery and the next LSN.
- A transaction updates 1,000 rows of 100 bytes each. Compare the log volume of command logging and of physiological logging with before and after images.
- Prove that replaying the stable log from a transaction-consistent snapshot gives the state after the last stable command, and show where the proof uses determinism.
References
- Nirmesh Malviya, Ariel Weisberg, Samuel Madden and Michael Stonebraker, Rethinking main memory OLTP recovery, Proceedings of the 30th IEEE International Conference on Data Engineering (ICDE), 2014, pages 604 to 615, the command log record format, synchronous logging with group commit, the transaction-consistent snapshots, recovery by replay, and the measurements against ARIES-style logging in VoltDB with TPC-C and Voter, paper level
- C. Mohan, Don Haderle, Bruce Lindsay, Hamid Pirahesh and Peter Schwarz, ARIES, a transaction recovery method supporting fine-granularity locking and partial rollbacks using write-ahead logging, ACM Transactions on Database Systems 17(1), 1992, pages 94 to 162, physiological log records and redo with the page_LSN, the baseline that command logging replaces, paper level
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag DQZNNJ Edit this page History Report an error Markdown