Algorithm Search⌘K

Techniqueresearch

Write-behind logging

Also called WBL.

A protocol for non-volatile memory that writes data first and logs only commit timestamp ranges, so recovery needs no redo.

Write-behind logging (WBL) is a logging protocol for a database system that keeps its data in byte-addressable non-volatile memory (NVM). It turns the order of write-ahead logging around: a transaction's changes reach durable storage before its log record, and the log record holds no data, only a range of commit timestamps. With multiversion concurrency control, every version of a tuple carries the timestamp of the transaction that wrote it. After a crash, the versions whose timestamps fall in the range that was open at the crash are simply not visible. Recovery has no redo and no undo pass, and it reads only the end of the log. Arulraj, Perron and Pavlo proposed it in 2016.

In plain words

Picture a bank where every change to an account is a new card in a drawer, with a stamp number on it. The newest card of an account holds its balance. The drawer does not lose cards when the power fails.

Work goes in batches. The clerk files the new cards of a batch at once. When the whole batch is filed, he writes one line in a book: "everything up to 150 is done, and the next batch gets stamps up to 249".

After a power cut, he reads only the last line of the book. Cards with stamps after the last "done" number and below the promised limit belong to a batch that never finished. He ignores them when he reads a balance and throws them out later. Nothing needs to be copied or repaired before work starts again.

When it applies

  • The database keeps its tuples in NVM with fast persistent writes, for example on a memory bus, and the system can flush CPU cache lines to it.
  • The system uses multiversion concurrency control, so a version is visible or not according to its timestamp, and the old version of a tuple stays in place while the new one is uncommitted. The paper also describes a variant for a single-version system.
  • Commits are grouped. A group commit can then persist many changes and write one small log record.
  • It does not apply to disks and flash. Writing every changed tuple at commit is a force policy, and on SSDs and hard disks this random writing costs more than a sequential log. The paper measures WBL as slower than WAL on those devices.

The template

The system assigns increasing commit timestamps. The dirty tuple table (DTT), in volatile memory, lists the versions that each transaction of the open group has created or changed. A log record has two timestamps, cpc_p and cdc_d, and the list of the gaps that still hold versions. Every timestamp up to cpc_p belongs to a transaction whose fate is decided and whose changes are persistent. No transaction gets a timestamp of cdc_d or more before the next group commit.

  1. COMMIT-GROUP()
  2. 1for each transaction of the group: persist every version that the DTT lists for it (flush its cache lines to NVM)
  3. 2c_p ← the largest timestamp given out; c_d ← c_p + G ▷ the next group gets timestamps below c_d
  4. 3persist the log record ⟨c_p, c_d, the gaps that still hold versions⟩
  5. 4report the transactions of the group
  6. RECOVER()
  7. 5read the last log record ⟨c_p, c_d, gaps⟩
  8. 6add the gap (c_p, c_d) to gaps; persist the record ⟨c_d, c_d + G, gaps⟩; open the database ▷ no redo, no undo
  9. VISIBLE(v) ▷ on every read
  10. 7v is visible if no gap (a, b) has a < v.ts < b, and v is the newest such version of its key
  11. GC-STEP() ▷ in the background
  12. 8remove a version whose timestamp lies in a gap

Uncommitted versions may reach NVM at any time, as a cache line is evicted; this is a steal policy. An aborted transaction's versions are removed from the DTT and from NVM, which MVCC does anyway. A gap is dropped from the next log record when garbage collection has removed all its versions.

Why it works. Take a crash at any point. Every transaction that was reported belongs to a group whose log record was persisted, and line L1 persisted its versions before line L3. So every reported change is in NVM, with a timestamp at or below the cpc_p of the last record, which is not in a gap. Every transaction whose group was not reported has a timestamp above that cpc_p and below cdc_d, by the promise of line L2, so all its versions that reached NVM lie in the new gap of line L6 and are not visible. Older gaps stay in the record until they are empty. So the visible state is the newest version per key among the reported transactions. A crash during recovery only repeats line L6. The tests check this by a crash after every prefix of a random workload, new work after the restart and a second crash.

Cost. For one restart:

  • Log records read and written. The last record is read, and one record is written. This does not depend on the length of the log or on the work since a checkpoint.
  • Pages read and written. None during recovery. Garbage collection later removes the versions in the gaps.
  • Log volume per update. None. Each group commit writes one record of two timestamps and its gap list. The data is written once, to its place in NVM, instead of once to the log and once to the database.
  • Checkpoints. WBL needs no checkpoints of the kind that WAL uses to bound redo, since there is no redo. The work at a commit grows with the changes of the group, because they are all persisted at that moment.

Measurements (Arulraj, Perron and Pavlo, PVLDB 2016; the Peloton system and the YCSB benchmark, on the Intel persistent memory emulation platform (PMEP) with NVM latency set to 4 times that of DRAM, two Intel Xeon E5-4620 processors and 128 GB of memory): compared with write-ahead logging on the same emulated NVM, WBL gave about 1.3 times the throughput, recovered more than 100 times faster, and needed about 1.5 times less storage. On SSD and HDD, WBL was slower than WAL. These are measurements on an emulator in 2016, not on the NVM devices that came later.

Example. The code uses G=100G = 100 and starts with the record ⟨0, 100, none⟩. T1 gets timestamp 1 and writes a = 11. Its group commits: the version is persisted and the record ⟨1, 101, none⟩ is written. T2 gets timestamp 2 and writes b = 22, and the cache evicts the version to NVM, but the system crashes before the next group commit. NVM now holds versions (a, 1) and (b, 2). Recovery reads ⟨1, 101, none⟩ and writes ⟨101, 201, (1, 101)⟩. The version (b, 2) lies in the gap, so b reads as 20, and a reads as 11. The next transaction gets timestamp 102. Garbage collection later removes (b, 2); after that, the next group commit drops the empty gap from its record.

Classic examples

  • Peloton. The paper implements WBL in the Peloton in-memory database with multiversion concurrency control on NVM, and compares it with a WAL implementation in the same system.
  • Replication. Section 5 of the paper discusses WBL in a system with replicas. The log holds no data, so the changes that a replica needs must come from another source than the log.
  • Steal and force on NVM. WBL is the force side of the steal and force trade-off, made cheap by fast persistent writes, together with steal made safe by versions and timestamps instead of before images.
  • Related ideas. Shadow paging also writes new data before the commit and needs no redo, but it switches a root pointer at commit. Instant restart keeps WAL and makes the system available before redo and undo end.

Variations

  • Single-version storage. Without multiversion tuples, an uncommitted change in place hides the old value, so the system must keep the old value somewhere until the commit. The paper describes a variant of WBL for such systems.
  • Size of the group. A larger GG allows longer groups between log records; a crash then leaves a wider gap, which costs nothing at recovery but more work for garbage collection.
  • Gaps in the index. Indexes in NVM must also ignore entries of versions in a gap, or remove them in the background.

Pitfalls

  • Writing the log record before the data. If line L3 runs before line L1 ends, a crash can lose the data of a reported transaction, and nothing in the log can redo it.
  • Breaking the promise of cdc_d. If a transaction of the open group gets a timestamp of cdc_d or more, its versions fall outside the gap after a crash and become visible although it never committed. A group must commit before the timestamps run out.
  • Dropping a gap too early. If a gap leaves the log record while versions in it remain in NVM, those uncommitted versions become visible.
  • Volatile CPU caches. A store to NVM is persistent only after its cache line is flushed and the flush is ordered. Line L1 needs the flush and a fence, not only the store.
  • Using it on block devices. On disks and SSDs the forced random writes at each commit cost more than WAL.

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.

write_behind_logging.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/write-behind-logging/. The authors are listed in prov/80XPYE.jsonl.

"""Write-behind logging (Arulraj, Perron and Pavlo) on simulated non-volatile memory.

Data lives in NVM as multiversion tuples: each version holds a key, a value and
the timestamp of the transaction that wrote it. A new version first sits in
the volatile CPU cache and may reach NVM at any time (an eviction). The dirty
tuple table (DTT), in DRAM, lists the versions of each transaction.

Transactions run one at a time and are grouped. At a group commit the system
persists every version of the group, and only then persists a log record
<c_p, c_d, gaps>: every timestamp up to c_p is decided, and no transaction of
the next group gets a timestamp of c_d or more. After a crash, the interval
(c_p, c_d) of the last record is a gap: versions with a timestamp in a gap are
not visible. Recovery reads one log record and writes one. There is no redo
and no undo; garbage collection removes the versions in the gaps later.
"""

from dataclasses import dataclass

INIT = {"a": 10, "b": 20, "c": 30, "d": 40}


@dataclass(frozen=True)
class Version:
    key: str
    value: int
    ts: int


@dataclass(frozen=True)
class LogRec:
    cp: int
    cd: int
    gaps: tuple  # of (low, high), open intervals


def in_gap(ts: int, gaps) -> bool:
    return any(lo < ts < hi for lo, hi in gaps)


class WblDb:
    def __init__(self, nvm: list | None = None, log: list | None = None, group: int = 100):
        self.G = group
        self.nvm: list[Version] = list(nvm or [])  # persistent
        self.log: list[LogRec] = list(log or [LogRec(0, group, ())])  # persistent
        self.cache: list[Version] = []  # volatile
        self.dtt: dict[int, list[Version]] = {}  # volatile
        self.pending: list[int] = []  # transactions of the open group
        self.next_ts = self.log[-1].cp + 1
        self.records_read = 0

    # ------------------------------------------------------------ reads
    def read(self, key: str) -> int:
        gaps = self.log[-1].gaps
        best = None
        for v in self.nvm + self.cache:
            if v.key == key and not in_gap(v.ts, gaps):  # @line L7
                if best is None or v.ts > best.ts:  # @line L7
                    best = v
        return INIT[key] if best is None else best.value

    def state(self) -> dict:
        return {k: self.read(k) for k in INIT}

    # ------------------------------------------------------------ transactions
    def begin(self) -> int:
        if self.next_ts >= self.log[-1].cd:
            raise RuntimeError("the group is full: call group_commit first")  # the promise of c_d
        ts = self.next_ts
        self.next_ts += 1
        self.dtt[ts] = []
        return ts

    def write(self, ts: int, key: str, value: int) -> None:
        for old in [o for o in self.dtt[ts] if o.key == key]:  # a transaction keeps one version per key
            self.dtt[ts].remove(old)
            self.cache = [o for o in self.cache if o != old]
            self.nvm = [o for o in self.nvm if o != old]
        v = Version(key, value, ts)
        self.cache.append(v)
        self.dtt[ts].append(v)

    def evict(self, i: int) -> None:
        """The cache writes one version to NVM before commit."""
        if self.cache:
            self.nvm.append(self.cache.pop(i % len(self.cache)))

    def commit(self, ts: int) -> None:
        """Pre-commit: the versions stay visible, and the transaction is
        reported at the end of its group."""
        self.pending.append(ts)

    def abort(self, ts: int) -> None:
        mine = set(self.dtt.pop(ts))
        self.cache = [v for v in self.cache if v not in mine]
        self.nvm = [v for v in self.nvm if v not in mine]

    def group_commit(self) -> list[int]:
        """Persist the group, then its log record. Return the reported transactions."""
        for ts in self.pending:  # @line L1
            for v in self.dtt.pop(ts):  # @line L1
                if v in self.cache:
                    self.cache.remove(v)
                    self.nvm.append(v)  # @line L1
        cp = self.next_ts - 1  # @line L2
        cd = cp + self.G  # @line L2
        gaps = tuple(g for g in self.log[-1].gaps if any(in_gap(v.ts, [g]) for v in self.nvm))
        self.log.append(LogRec(cp, cd, gaps))  # @line L3
        done, self.pending = self.pending, []
        return done  # @line L4

    # ------------------------------------------------------------ failure and recovery
    def crash(self) -> "WblDb":
        return WblDb(self.nvm, self.log, self.G)

    def recover(self) -> None:
        last = self.log[-1]  # @line L5
        self.records_read = 1
        gaps = last.gaps + ((last.cp, last.cd),)  # @line L6
        self.log.append(LogRec(last.cd, last.cd + self.G, gaps))  # @line L6
        self.next_ts = last.cd + 1

    def gc_step(self) -> bool:
        """Remove one version that lies in a gap. Return False if none is left."""
        gaps = self.log[-1].gaps
        for i, v in enumerate(self.nvm):
            if in_gap(v.ts, gaps):
                del self.nvm[i]  # @line L8
                return True
        return False
test_write_behind_logging.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/write-behind-logging/. The authors are listed in prov/80XPYE.jsonl.

"""Write-behind logging checked by crash injection.

A random workload with evictions, aborts and group commits is cut by a crash
after every prefix, recovered, continued and cut again. The visible state must
be the effect of exactly the reported transactions.
"""

import random

from write_behind_logging import INIT, LogRec, WblDb, in_gap

KEYS = sorted(INIT)


def run(db: WblDb, rng: random.Random, steps: int, committed: dict) -> None:
    """Random actions; committed gets the writes of each reported group."""
    groups: dict[int, dict] = {}
    open_txn = None
    writes: dict = {}
    for _ in range(steps):
        r = rng.random()
        if open_txn is None and db.next_ts >= db.log[-1].cd:
            for ts in db.group_commit():  # the group is full
                committed.update(groups.pop(ts))
        elif open_txn is None and r < 0.3:
            open_txn, writes = db.begin(), {}
        elif open_txn is not None and r < 0.6:
            k, v = rng.choice(KEYS), rng.randint(100, 999)
            db.write(open_txn, k, v)
            writes[k] = v
        elif open_txn is not None and r < 0.7:
            db.commit(open_txn)
            groups[open_txn] = writes
            open_txn = None
        elif open_txn is not None and r < 0.75:
            db.abort(open_txn)
            open_txn = None
        elif r < 0.9:
            db.evict(rng.randrange(1000))
        elif open_txn is None:
            for ts in db.group_commit():
                committed.update(groups.pop(ts))


def test_crash_at_every_prefix_twice() -> None:
    for seed in range(5):
        for k in range(0, 61, 3):
            rng = random.Random(seed)
            db, committed = WblDb(group=8), dict(INIT)
            run(db, rng, k, committed)
            db = db.crash()
            db.recover()
            assert db.records_read == 1
            assert db.state() == committed
            run(db, random.Random(seed + 100), 40, committed)  # new work after the restart
            db = db.crash()
            db.recover()
            assert db.state() == committed


def test_garbage_collection_removes_the_gaps() -> None:
    rng = random.Random(4)
    db, committed = WblDb(group=8), dict(INIT)
    for _ in range(5):
        run(db, rng, 50, committed)
        db = db.crash()
        db.recover()
    while db.gc_step():
        pass
    assert db.state() == committed
    assert not any(in_gap(v.ts, db.log[-1].gaps) for v in db.nvm)
    ts = db.begin()
    db.commit(ts)
    db.group_commit()
    assert db.log[-1].gaps == ()  # every gap is empty, so the next record drops them


def test_hand_example() -> None:
    db = WblDb(group=100)
    t1 = db.begin()  # timestamp 1
    db.write(t1, "a", 11)
    db.commit(t1)
    assert db.group_commit() == [1]
    assert db.log[-1] == LogRec(1, 101, ())
    t2 = db.begin()  # timestamp 2
    db.write(t2, "b", 22)
    db.commit(t2)
    db.evict(0)  # b = 22 reaches NVM before the group commits
    db = db.crash()
    assert [(v.key, v.ts) for v in db.nvm] == [("a", 1), ("b", 2)]
    db.recover()  # no redo and no undo
    assert db.log[-1] == LogRec(101, 201, ((1, 101),))
    assert db.state() == dict(INIT, a=11)  # version 2 lies in the gap (1, 101)
    t3 = db.begin()
    assert t3 == 102
    db.write(t3, "b", 23)
    db.commit(t3)
    db.group_commit()
    assert db.log[-1] == LogRec(102, 202, ((1, 101),))
    assert db.gc_step() and not db.gc_step()
    assert db.state() == dict(INIT, a=11, b=23)

Exercises

  1. In the example, T2 commits at once but its group never commits. Show that the client was never told of the commit, and that the result is correct.
  2. A system crashes twice, once during the group after ⟨1, 101⟩ and once during the group after ⟨101, 201⟩. Give the gap list after the second recovery, and the versions that garbage collection removes.
  3. Change line L2 to cd←cpc_d \leftarrow c_p and give a crash that makes an uncommitted version visible.
  4. Compare the bytes written per update by WBL and by WAL with before and after images, for tuples of 100 bytes and an update of one field of 8 bytes.

References

  1. Joy Arulraj, Matthew Perron and Andrew Pavlo, Write-behind logging, Proceedings of the VLDB Endowment 10(4), 2016, pages 337 to 348, Section 4 (the write-behind logging protocol, the dirty tuple table, the commit timestamp gaps and recovery), Section 6 (the NVM platform) and Section 7 (the evaluation in Peloton against write-ahead logging)
  2. 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, the redo and undo passes of write-ahead logging, the baseline that write-behind 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises