Techniquecore
Point-in-time recovery
Also called PITR, log replay to a timestamp.
Restore a backup and replay the archived log up to a chosen time, which undoes the effect of a later user error.
Point-in-time recovery (PITR), or log replay to a timestamp, rebuilds a database as it was at a chosen moment in the past. It restores an archive copy taken before that moment, replays the archived log from the copy up to the target, and rolls back the transactions that had not committed at the target. Committed work after the target is not undone: it is simply never replayed. It uses the same parts as media recovery, with the log cut at an earlier point, and its main use is to remove the effect of a user error, such as a wrong DELETE, that the database has already committed and that every replica has already copied.
In plain words
Someone deleted a table at 14:05, and the database committed it, as it should. A crash recovery does not help, because the delete is committed work.
So you take the last full copy of the database from before 14:05, for example the one from the night before. You replay the journal of changes over it, in order, and you stop just before 14:05. Work that was half done at that moment is cancelled, as after a crash. Work after 14:05 is never replayed.
The result is the database as it was at 14:04. Everything after that is gone, the good changes with the bad one. You can then copy the lost table back into the live database, or use the restored copy as the new database.
When it applies
- The system keeps archive copies and keeps every log record since the oldest copy that it may need, as for media recovery.
- Each commit record holds a time, or the operator knows a log position (an LSN), a transaction or a named restore point to stop at.
- The target is after the end of some archive copy. A copy taken while transactions run (a fuzzy copy) is consistent only together with the log up to its end, so it cannot give a state from before its end.
- The loss of all committed work after the target is acceptable, or the result is used only to copy data back.
The template
The log is the one of write-ahead logging: update records with before and after images, compensation records (CLRs) for undo, and pages with a pageLSN. A commit record holds its time. An archive copy has a start LSN, the smallest recLSN of the pages that were dirty in the buffer when the copy began, and an end LSN, the LSN of the record that ends the copy.
RECOVER-TO(t)- 1
stop ← the LSN just before the first commit record with a time after t, or the end of the log - 2
restore, on a new device, the newest archive copy whose end LSN is at most stop - 3
cut the log at stop: the records after stop are not used - 4
for each update or CLR r from the start LSN of the copy up to stop, in LSN order do - 5
if pageLSN(r.page) < r.lsn then apply r.after to the page; pageLSN(r.page) ← r.lsn - 6
losers ← the transactions in the log up to stop with no commit record and no end record - 7
for each loser, undo its updates newest first with CLRs, written to the new branch of the log - 8
append ⟨end, T⟩ for each loser; open the database on the new branch
What happens to transactions open at the target. A transaction that began before the target and committed after it has no commit record in the log up to stop. Line L6 makes it a loser, and line L7 rolls back the part of it that is before the target, even though it committed later. A transaction that began after the target has no records up to stop and does not appear. So the result holds exactly the transactions with a commit record at or before the target, as if the system had crashed at that moment.
The new branch. After line L8 the database writes new records after the CLRs and end records of line L7. These records must not mix with the old records after stop, which are still in the archive and describe a different history. PostgreSQL gives each such branch a new timeline ID and keeps a history file that says where it branched off.
Why it works. The log up to stop is a prefix of the log, and a crash at stop would have left exactly this prefix as the stable log, with some disk state. Lines L2 to L5 build, from the copy, the state that holds every record on each page up to stop, by the pageLSN argument of crash recovery and ARIES: each page in the copy holds all records on it below the start LSN and up to its own pageLSN, and lines L4 and L5 add the rest. The copy ended at or before stop, so no page in it holds a record after stop. Lines L6 to L8 are then the undo of a crash recovery at stop. The tests check this by a media failure after every prefix of a random workload, and recovery to every target time.
Cost. Line L2 reads every page of the copy and writes it to the new device. Lines L4 and L5 read the log records from the start LSN of the copy to stop, and write each page that they change once at the end. Line L7 reads the records of the losers and writes one CLR per loser update. The log volume per update in normal work is that of write-ahead logging, but every record must be kept in the archive for as long as a target before it may be asked for. A checkpoint does not shorten the replay: the time since the newest copy that ended before the target bounds it, so more frequent copies make it shorter.
Example. Items a = 10 and c = 30, a copy that ends before T1 starts, and commit times 1, 2 and 3.
| LSN | record |
|---|---|
| 1, 2 | begin copy, end copy |
| 3, 4 | begin T1, update T1 a: 10 to 11 |
| 5, 6 | commit T1 (time 1), end T1 |
| 7, 8 | begin T2, update T2 c: 30 to 31 |
| 9, 10 | commit T2 (time 2), end T2 |
| 11, 12 | begin T3, update T3 a: 11 to 99 (the user error) |
| 13, 14 | commit T3 (time 3), end T3 |
RECOVER-TO(2) finds the first commit after time 2 at LSN 13, so stop = 12. It restores the copy and replays records 4, 8 and 12. T3 has no commit record up to 12, so it is a loser, and a CLR sets a back to 11. The result is a = 11, c = 31: T1 and T2 are in, the error is out. RECOVER-TO(1) stops at 8, rolls back the open T2 with a CLR, and gives a = 11, c = 30.
Classic examples
- PostgreSQL. A base backup and an archive of the write-ahead log. The recovery target is a time, a transaction ID, an LSN or a named restore point. The setting recovery_target_inclusive says whether a transaction that commits exactly at the target is included. Each completed archive recovery starts a new timeline.
- Database systems with log backups. Systems with full backups and log backups restore a full backup, then the log backups in order, and stop at a time or at a marked transaction.
- ARIES image copies. The fuzzy image copies of ARIES and redo from the log give the media recovery on which point-in-time recovery builds.
- Recovery of a differential file. The read-only main file and a dump of the differential file give a point to restore to; the logged changes since then are redone up to the target.
Variations
- Target by transaction. Stop just after the commit of a named transaction. Transaction IDs are given at the start of a transaction, but transactions commit in another order, so the target is a position in the commit order, not an ID range.
- Inclusive or exclusive target. Include or exclude a transaction whose commit time is exactly the target.
- Named restore points. The system writes a record with a name into the log, for example before a risky change, so that the operator can later stop exactly there.
- Delayed replica. A replica that applies the log a fixed time late keeps a state from the past at all times, so that recovery from a user error needs no restore.
- Table-level recovery. Recover the whole database to a side copy, then copy only the lost rows or tables back into the live database. The live database keeps its later work.
- Flashback by undo. A system that keeps old versions of rows can read or rebuild a past state without a restore, as long as the old versions are still kept. This replaces replay by undo and is limited by how long the old versions stay.
Pitfalls
- A copy that ended after the target. A fuzzy copy can hold committed changes after the target, and recovery never undoes committed work. Use only a copy whose end is at or before the target. The tests check that such a copy is refused.
- Redo from the end of the copy, or from the begin record only. Redo must start at the start LSN, the smallest recLSN of the pages dirty in the buffer when the copy began. A later start loses committed changes that were only in the buffer.
- Forgetting the open transactions. Stopping replay at the target without the undo of lines L6 to L8 leaves changes of transactions that had not committed at the target, some of which may never have committed at all.
- Mixing timelines. After a recovery to the past, the old log after the target is still in the archive. A later recovery must not replay it on top of the new branch.
- A gap in the archive. If one log segment between the copy and the target is missing, replay must stop at the gap. The result is then older than the target.
- Clock targets. A target time is compared with commit times in the log, which come from the clock of the server. A user who gives the time from another clock can stop on the wrong side of the error.
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/point-in-time-recovery/. The authors are listed in prov/9VV51Q.jsonl.
"""Point-in-time recovery from a fuzzy archive copy and the archive log.
Normal processing is write-ahead logging with record locks held to the end
of the transaction, steal and no-force, and physical update records. Each
commit record carries the time of the commit. A fuzzy copy reads the disk one
page at a time while transactions run; its start LSN is the smallest recLSN of
the pages that are dirty in the buffer when it begins. The log is kept on a
device of its own and is the archive log.
recover_to(archive, log, t) builds a new database that holds the effects of
exactly the transactions that committed at or before time t.
"""
from dataclasses import dataclass
PAGE_OF = {"a": "P1", "b": "P1", "c": "P2", "d": "P2", "e": "P3"}
INIT = {"a": 10, "b": 20, "c": 30, "d": 40, "e": 50}
@dataclass(frozen=True)
class Rec:
lsn: int
kind: str # begin, update, clr, commit, end, begin_copy, end_copy
txn: int = 0
prev: int = 0
page: str = ""
key: str = ""
before: int = 0
after: int = 0
time: int = 0 # commit only
undo_next: int = 0 # clr only
@dataclass(frozen=True)
class Copy:
start: int # redo from here
end: int # LSN of the end_copy record
pages: dict # page -> (values, page_lsn)
class Db:
def __init__(self):
self.disk: dict = {}
for k, p in sorted(PAGE_OF.items()):
self.disk.setdefault(p, ({}, 0))[0][k] = INIT[k]
self.log: list[Rec] = [] # stable log, also the archive log
self.tail: list[Rec] = []
self.buf: dict[str, list] = {} # page -> [values, page_lsn, rec_lsn or 0]
self.last: dict[int, int] = {}
self.locks: dict[str, int] = {}
self.clock = 0
self.archive: list[Copy] = []
self.copying: tuple | None = None # (start, pages copied, pages left)
def _append(self, **kw) -> Rec:
r = Rec(lsn=len(self.log) + len(self.tail) + 1, **kw)
self.tail.append(r)
if r.txn:
self.last[r.txn] = r.lsn
return r
def flush_log(self) -> None:
self.log.extend(self.tail)
self.tail = []
def _fix(self, p: str) -> list:
if p not in self.buf:
vals, lsn = self.disk[p]
self.buf[p] = [dict(vals), lsn, 0]
return self.buf[p]
def flush_page(self, p: str) -> None:
if p in self.buf:
pg = self.buf[p]
if pg[1] > len(self.log): # the WAL rule
self.flush_log()
self.disk[p] = (dict(pg[0]), pg[1])
pg[2] = 0
def begin(self, txn: int) -> None:
self._append(kind="begin", txn=txn)
def _set(self, txn: int, key: str, value: int, kind: str, undo_next: int = 0) -> None:
pg = self._fix(PAGE_OF[key])
r = self._append(kind=kind, txn=txn, prev=self.last[txn], page=PAGE_OF[key], key=key,
before=pg[0][key], after=value, undo_next=undo_next)
pg[0][key], pg[1] = value, r.lsn
if not pg[2]:
pg[2] = r.lsn
def write(self, txn: int, key: str, value: int) -> bool:
if self.locks.setdefault(key, txn) != txn:
return False
self._set(txn, key, value, "update")
return True
def _end(self, txn: int) -> None:
self._append(kind="end", txn=txn, prev=self.last.pop(txn))
for k in [k for k, t in self.locks.items() if t == txn]:
del self.locks[k]
def commit(self, txn: int) -> int:
self.clock += 1
self._append(kind="commit", txn=txn, prev=self.last[txn], time=self.clock)
self.flush_log()
self._end(txn)
return self.clock
def abort(self, txn: int) -> None:
"""Roll back at once with CLRs."""
nxt = self.last[txn]
while nxt:
r = self.rec(nxt)
if r.kind == "update":
self._set(txn, r.key, r.before, "clr", undo_next=r.prev)
nxt = r.undo_next if r.kind == "clr" else r.prev
self._end(txn)
def rec(self, lsn: int) -> Rec:
i = lsn - 1
return self.log[i] if i < len(self.log) else self.tail[i - len(self.log)]
def begin_copy(self) -> None:
r = self._append(kind="begin_copy")
self.flush_log()
start = min([pg[2] for pg in self.buf.values() if pg[2]] + [r.lsn])
self.copying = (start, {}, sorted(self.disk))
def copy_step(self) -> None:
"""Copy one page from the disk, or end the copy."""
start, pages, left = self.copying
if left:
pages[left[0]] = (dict(self.disk[left[0]][0]), self.disk[left[0]][1])
self.copying = (start, pages, left[1:])
return
r = self._append(kind="end_copy")
self.flush_log()
self.archive.append(Copy(start, r.lsn, pages))
self.copying = None
def target_lsn(log: list[Rec], t: int) -> int:
"""The last LSN before the first commit after time t."""
for r in log:
if r.kind == "commit" and r.time > t:
return r.lsn - 1
return len(log)
def recover_to(archive: list[Copy], log: list[Rec], t: int) -> tuple[dict, list[Rec]]:
"""A new database with the transactions committed at or before t, and the
log of the new branch."""
stop = target_lsn(log, t) # @line L1
usable = [c for c in archive if c.end <= stop]
if not usable:
raise ValueError("no archive copy ended before the target")
copy = max(usable, key=lambda c: c.end) # @line L2
disk = {p: [dict(v), lsn] for p, (v, lsn) in copy.pages.items()} # @line L2
head = log[:stop] # @line L3
for r in head[copy.start - 1:]: # @line L4
if r.kind in ("update", "clr") and disk[r.page][1] < r.lsn: # @line L5
disk[r.page][0][r.key], disk[r.page][1] = r.after, r.lsn # @line L5
last: dict[int, int] = {}
for r in head: # @line L6
if r.kind == "end":
last.pop(r.txn, None)
elif r.txn and r.kind != "commit":
last[r.txn] = r.lsn # @line L6
elif r.kind == "commit":
last[r.txn] = 0 # committed by the target: not a loser
branch = list(head)
for txn in sorted(t for t, lsn in last.items() if lsn): # @line L7
nxt, prev = last[txn], last[txn]
while nxt:
r = branch[nxt - 1]
if r.kind == "update": # @line L7
c = Rec(lsn=len(branch) + 1, kind="clr", txn=txn, prev=prev, page=r.page, key=r.key,
before=disk[r.page][0][r.key], after=r.before, undo_next=r.prev)
branch.append(c) # @line L7
disk[r.page][0][r.key], disk[r.page][1] = r.before, c.lsn # @line L7
prev = c.lsn
nxt = r.undo_next if r.kind == "clr" else r.prev
branch.append(Rec(lsn=len(branch) + 1, kind="end", txn=txn, prev=prev)) # @line L8
return {p: (v, lsn) for p, (v, lsn) in disk.items()}, branch # @line L8
test_point_in_time_recovery.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/point-in-time-recovery/. The authors are listed in prov/9VV51Q.jsonl.
"""Point-in-time recovery checked by failure injection.
A random workload with fuzzy copies runs and is cut by a media failure after
every prefix. For every target time, the recovered database must hold the
effects of exactly the transactions that committed at or before the target.
"""
import random
import pytest
from point_in_time_recovery import INIT, PAGE_OF, Copy, Db, recover_to, target_lsn
KEYS = sorted(PAGE_OF)
PAGES = sorted(set(PAGE_OF.values()))
def workload(rng: random.Random, steps: int) -> tuple[Db, list]:
"""Run steps random actions. Return the database and the committed
transactions as (commit time, writes) in commit order."""
db = Db()
db.begin_copy()
while db.copying:
db.copy_step()
active: dict[int, dict] = {}
done: list = []
nxt = 1
for _ in range(steps):
r = rng.random()
if r < 0.15 and len(active) < 3:
db.begin(nxt)
active[nxt] = {}
nxt += 1
elif r < 0.5 and active:
t = rng.choice(sorted(active))
k = rng.choice(KEYS)
v = rng.randint(100, 999)
if db.write(t, k, v):
active[t][k] = v
elif r < 0.62 and active:
t = rng.choice(sorted(active))
done.append((db.commit(t), active.pop(t)))
elif r < 0.67 and active:
t = rng.choice(sorted(active))
db.abort(t)
del active[t]
elif r < 0.75:
if db.copying:
db.copy_step()
else:
db.begin_copy()
else:
db.flush_page(rng.choice(PAGES))
return db, done
def state_at(done: list, t: int) -> dict:
s = dict(INIT)
for time, writes in done:
if time <= t:
s.update(writes)
return s
def values(disk: dict) -> dict:
return {k: disk[PAGE_OF[k]][0][k] for k in KEYS}
def test_every_failure_point_and_every_target() -> None:
for seed in range(4):
steps = 70
for k in range(0, steps + 1, 2):
db, done = workload(random.Random(seed), k)
log = list(db.log) # the media failure: only the archive and the log are left
for t in range(db.clock + 1):
try:
disk, branch = recover_to(db.archive, log, t)
except ValueError:
assert all(c.end > target_lsn(log, t) for c in db.archive)
continue
assert values(disk) == state_at(done, t)
# the new branch is the log up to the target plus the undo of the losers
stop = target_lsn(log, t)
assert branch[:stop] == log[:stop]
assert all(r.kind in ("clr", "end") for r in branch[stop:])
def test_recovery_is_repeatable_after_a_crash() -> None:
# recovery writes only to the new device; after a crash it starts again
# from the archive copy and gives the same result
db, done = workload(random.Random(9), 120)
log = list(db.log)
for t in range(db.clock + 1):
try:
a = recover_to(db.archive, log, t)
except ValueError:
continue
b = recover_to(db.archive, log, t)
assert a == b and values(a[0]) == state_at(done, t)
def test_transaction_open_at_the_target_is_rolled_back() -> None:
db = Db()
db.begin_copy()
while db.copying:
db.copy_step()
db.begin(1)
db.write(1, "a", 11)
t1 = db.commit(1) # time 1
db.begin(2)
db.write(2, "c", 31) # T2 is open at time 1
db.flush_page("P2") # and its change reaches the disk
db.begin_copy()
while db.copying:
db.copy_step()
t2 = db.commit(2) # time 2
db.begin(3)
db.write(3, "a", 99) # a user error
db.commit(3) # time 3
disk, branch = recover_to(db.archive, list(db.log), t1)
assert values(disk) == dict(INIT, a=11) # c = 31 of T2 is undone, a = 99 is not applied
assert [r.kind for r in branch[-2:]] == ["clr", "end"] and branch[-1].txn == 2
disk, _ = recover_to(db.archive, list(db.log), t2)
assert values(disk) == dict(INIT, a=11, c=31)
def test_a_copy_that_ended_after_the_target_is_not_used() -> None:
db = Db()
db.begin_copy()
while db.copying:
db.copy_step()
db.begin(1)
db.write(1, "e", 55)
db.commit(1)
db.flush_page("P3")
db.begin_copy()
while db.copying:
db.copy_step()
first, second = db.archive
# with only the second copy, a target before T1 cannot be reached: its
# pages hold the committed change of T1, and recovery never undoes it
with pytest.raises(ValueError):
recover_to([second], list(db.log), 0)
disk, _ = recover_to([first, second], list(db.log), 0)
assert values(disk) == INIT
def test_start_lsn_of_a_fuzzy_copy_covers_dirty_pages() -> None:
db = Db()
db.begin_copy()
while db.copying:
db.copy_step()
db.begin(1)
db.write(1, "b", 22) # LSN 4, P1 stays dirty in the buffer
db.commit(1)
db.begin_copy() # the copy reads P1 without b = 22
while db.copying:
db.copy_step()
copy = db.archive[-1]
assert copy.start == 4 and copy.pages["P1"][0]["b"] == 20
disk, _ = recover_to([copy], list(db.log), 1)
assert values(disk)["b"] == 22
# a start LSN at the begin_copy record would lose the committed change
late = Copy(start=copy.end - 1, end=copy.end, pages=copy.pages)
disk, _ = recover_to([late], list(db.log), 1)
assert values(disk)["b"] == 20
Exercises
- In the example, a fuzzy copy reads page a after LSN 12 and ends at LSN 15. Show that RECOVER-TO(2) with this copy gives a = 99, and that no undo with the log alone can repair it.
- Change line L1 to stop at the first commit after t instead of just before it. Which transaction is then wrong, and how?
- A transaction T starts at time 1, writes x, and commits at time 5. Give the value of x after RECOVER-TO(t) for t = 0, 3 and 5, and the log records that line L7 writes in each case.
- Show that recovery to a target and then a second recovery of the new branch to a later target never replays a record of the old branch after the first target.
References
- PostgreSQL documentation, Continuous Archiving and Point-in-Time Recovery (PITR), Section 25.3.5, Recovering Using a Continuous Archive Backup (the recovery target, and the note that the stop point must be after the end of the base backup), and Section 25.3.6, Timelines
- PostgreSQL documentation, Write Ahead Log settings, Section 19.5.6, Recovery Target (recovery_target_time, recovery_target_xid, recovery_target_lsn and recovery_target_inclusive)
- Philip A. Bernstein, Vassos Hadzilacos and Nathan Goodman, Concurrency Control and Recovery in Database Systems, Addison-Wesley, 1987, Chapter 6, Centralized Recovery, Section 6.8 (the archive database and the archive log)
- 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 section on media recovery (fuzzy image copies and redo from the log), 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 9VV51Q Edit this page History Report an error Markdown