man postgres-internals/checkpoints
lesson 7 of 30 · Buffers and durability
Checkpoints, full-page writes and checksums
Lesson 6 ended with a log that only grows, and a rule: a changed page may reach its file only after the record describing the change has reached the log on disk. Two questions were left open. After a crash, where in the log does replay start? Not at the beginning of time: the log would have to be kept forever and replayed in full. And what does replay do with a page the crash left half written? A record that says “put this tuple at offset 6 of block 8” assumes the rest of block 8 is intact, and a torn page isn’t.
This lesson covers PostgreSQL’s answer to both, and the check that finds damaged pages when they are read back in:
- a checkpoint writes out the pages that were dirty when it began, and records a redo point: replay starts there;
- the first change to a page after the redo point logs an image of the whole page, a full-page write, so replay can restore the page instead of patching it;
- a checksum in each page’s header, set as the page is written and checked as it is read; with checksums on, even setting a hint bit can have to log the page whole.
All psql and shell output below comes from one run of
tools/record_checkpoint.py in the tinypg repository (tag lesson-07.1)
against PostgreSQL 19.0 on 64-bit ARM macOS, pasted as the script
recorded it. The cluster has data checksums on (initdb’s default in 19),
full_page_writes = on, wal_compression = off, wal_level = replica
and 16 MB segments.
The experiment
Two tables: ledger, 60 rows of 1000 characters, and hints, ten small
rows. Then a CHECKPOINT:
CREATE TABLE ledger (id int, note text) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO ledger SELECT i, repeat(chr(65 + i % 26), 1000) FROM generate_series(1, 60) AS i;
INSERT 0 60
CREATE TABLE hints (id int) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO hints SELECT generate_series(1, 10);
INSERT 0 10
CHECKPOINT;
CHECKPOINT
SELECT pg_relation_filepath('ledger') AS ledger, pg_relation_filepath('hints') AS hints;
ledger | hints
------------------+------------------
base/16384/16621 | base/16384/16626
(1 row)
SELECT redo_lsn, checkpoint_lsn FROM pg_control_checkpoint();
redo_lsn | checkpoint_lsn
------------+----------------
0/023AB660 | 0/023AB6B8
(1 row)
A ledger row is a 1032-byte tuple plus a 4-byte line pointer, so seven
fit on a page: blocks 0 to 7 hold 56 rows and block 8 holds the last four.
After the CHECKPOINT every page of both tables is in its file, with a
checksum. pg_control_checkpoint() reads the control file: the latest
checkpoint record starts at 0/023AB6B8, and its redo point is 88 bytes
before that, at 0/023AB660. Hold on to that redo point; most of this
lesson is about what changes when a page is first touched after it.
Checksums
pd_checksum is the 16-bit field at offset 8 of the page header, after
the 8-byte pd_lsn. When checksums are on, the server computes it from
the rest of the page as the page is written, and recomputes it when the
page is read back into a buffer, in PageIsVerified():
if (DataChecksumsEnabled())
{
checksum = pg_checksum_page(page, blkno);
if (checksum != p->pd_checksum)
{
checksum_failure = true;
if (checksum_failure_p)
*checksum_failure_p = true;
}
}
src/backend/storage/page/bufpage.c, lines 110–120
A mismatch is reported as data corruption, and the read fails unless
ignore_checksum_failure or zero_damaged_pages says otherwise. pageinspect has the same function as
SQL, page_checksum(). Right after the checkpoint the buffers hold
exactly what is in the files, so the stored and the computed values agree
on all nine pages of ledger (pageinspect prints them as smallint, so
values above 32767 show up negative):
SELECT blkno, (page_header(get_raw_page('ledger', blkno))).checksum AS pd_checksum,
page_checksum(get_raw_page('ledger', blkno), blkno) AS computed
FROM generate_series(0, 8) AS blkno;
blkno | pd_checksum | computed
-------+-------------+----------
0 | 17956 | 17956
1 | 21075 | 21075
2 | 9922 | 9922
3 | -21788 | -21788
4 | 11880 | 11880
5 | -15652 | -15652
6 | 4425 | 4425
7 | -29132 | -29132
8 | 32198 | 32198
(9 rows)
The algorithm is built for speed. The page is treated as 64 rows of 32 unsigned 32-bit words, and 32 running sums, one per column, each start from its own fixed constant. Each word is folded into its column’s sum with an FNV-1a-like step:
#define CHECKSUM_COMP(checksum, value) \
do { \
uint32 __tmp = (checksum) ^ (value); \
(checksum) = __tmp * FNV_PRIME ^ (__tmp >> 17); \
} while (0)
src/include/storage/checksum_impl.h, lines 137–141
The extra ^ (__tmp >> 17) is there because plain FNV-1a mixes high
input bits only into high output bits. The loop over the page, two
more rounds with zeros, and the 32 sums folded with xor:
/* initialize partial checksums to their corresponding offsets */
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets));
/* main checksum calculation */
for (i = 0; i < (uint32) (BLCKSZ / (sizeof(uint32) * N_SUMS)); i++)
for (j = 0; j < N_SUMS; j++)
CHECKSUM_COMP(sums[j], page->data[i][j]);
/* finally add in two rounds of zeroes for additional mixing */
for (i = 0; i < 2; i++)
for (j = 0; j < N_SUMS; j++)
CHECKSUM_COMP(sums[j], 0);
/* xor fold partial checksums together */
for (i = 0; i < N_SUMS; i++)
result ^= sums[i];
return result;
src/include/storage/checksum_block_internal.h, lines 25–42
Thirty-two independent sums leave the compiler free to vectorize the
loop; the header comment in checksum_impl.h gives the reasoning. Last,
pg_checksum_page() zeroes pd_checksum while summing, mixes in the
block number, and folds the result into 1 to 65535:
save_checksum = cpage->phdr.pd_checksum;
cpage->phdr.pd_checksum = 0;
checksum = pg_checksum_block(cpage);
cpage->phdr.pd_checksum = save_checksum;
/* Mix in the block number to detect transposed pages */
checksum ^= blkno;
/*
* Reduce to a uint16 (to fit in the pd_checksum field) with an offset of
* one. That avoids checksums of zero, which seems like a good idea.
*/
return (uint16) ((checksum % 65535) + 1);
src/include/storage/checksum_impl.h, lines 187–199
The block number makes a page that was written to the wrong place in its
file fail its check even if its bytes are intact, and the + 1 means a
checksum of 0 can’t occur. tinypg’s version is the same arithmetic in
Python:
def checksum_block(data):
"""pg_checksum_block(): the 32-bit sum of a whole page."""
words = WORDS.unpack(data)
sums = list(CHECKSUM_BASE_OFFSETS)
for i in range(0, len(words), N_SUMS):
for j in range(N_SUMS):
tmp = sums[j] ^ words[i + j]
sums[j] = ((tmp * FNV_PRIME) & 0xFFFFFFFF) ^ (tmp >> 17)
for _ in range(2):
for j in range(N_SUMS):
tmp = sums[j]
sums[j] = ((tmp * FNV_PRIME) & 0xFFFFFFFF) ^ (tmp >> 17)
result = 0
for s in sums:
result ^= s
return result
def pg_checksum_page(page, blkno):
"""The 16-bit checksum of page (bytes) as block blkno of its fork."""
data = bytearray(page)
data[PD_CHECKSUM_OFFSET:PD_CHECKSUM_OFFSET + 2] = b"\0\0"
checksum = checksum_block(bytes(data)) ^ blkno
return checksum % 65535 + 1
tinypg/checksum.py, lines 36–59
The recorder saved the file bytes of all ten pages before going on, and tinypg computes the same checksum for each:
$ python3 -m tinypg checksums tests/fixtures/pg19_checkpoint.json
ledger block 0: pd_checksum in the file 17956 (0x4624), tinypg's pg_checksum_page() 17956 (0x4624)
ledger block 1: pd_checksum in the file 21075 (0x5253), tinypg's pg_checksum_page() 21075 (0x5253)
ledger block 2: pd_checksum in the file 9922 (0x26C2), tinypg's pg_checksum_page() 9922 (0x26C2)
ledger block 3: pd_checksum in the file -21788 (0xAAE4), tinypg's pg_checksum_page() -21788 (0xAAE4)
ledger block 4: pd_checksum in the file 11880 (0x2E68), tinypg's pg_checksum_page() 11880 (0x2E68)
ledger block 5: pd_checksum in the file -15652 (0xC2DC), tinypg's pg_checksum_page() -15652 (0xC2DC)
ledger block 6: pd_checksum in the file 4425 (0x1149), tinypg's pg_checksum_page() 4425 (0x1149)
ledger block 7: pd_checksum in the file -29132 (0x8E34), tinypg's pg_checksum_page() -29132 (0x8E34)
ledger block 8: pd_checksum in the file 32198 (0x7DC6), tinypg's pg_checksum_page() 32198 (0x7DC6)
hints block 0: pd_checksum in the file 7925 (0x1EF5), tinypg's pg_checksum_page() 7925 (0x1EF5)
every checksum the same
When exactly is the checksum set? Not when the page changes: lesson 6’s
FlushBuffer() sets it on the buffer itself just before the write,
bufBlock = BufHdrGetBlock(buf);
/* Update page checksum if desired. */
PageSetChecksum((Page) bufBlock, buf->tag.blockNum);
src/backend/storage/buffer/bufmgr.c, lines 4599–4602
so a buffer changed since its last write carries a stale checksum until the next one. That matters below.
Torn pages and full-page writes
The operating system and the disk don’t promise to write 8 KB
atomically, so a crash in the middle of a write can leave part of the new
page and part of the old one in the file. A checksum notices such a page
but can’t repair it, and an ordinary record assumes the rest of the page
is good. The WAL part of src/backend/access/transam/README makes this
argument.
So, with full_page_writes on, the first record that changes a page
after the redo point carries a copy of the whole page as it is after the
change. (A record whose replay rebuilds the page from nothing, lesson 6’s
WILL_INIT, needs none.) Replay starts at the redo point, so the first
record replay meets for such a page has an image, and replay can write
the image over whatever the file holds. Later records for the page apply to the
restored copy. The image itself is safe: the record has a CRC, and the
log is appended to, not rewritten in place.
Step 2 of the recording inserts two rows into ledger in one
transaction. Block 8 has room for both, and nothing has touched it since
the checkpoint:
SELECT redo_lsn FROM pg_control_checkpoint();
redo_lsn
------------
0/023AB660
(1 row)
BEGIN;
INSERT INTO ledger VALUES (61, repeat('Q', 1000));
INSERT INTO ledger VALUES (62, 'short');
COMMIT;
SELECT start_lsn, prev_lsn, xid, resource_manager AS rmgr, record_type,
record_length AS length, fpi_length AS fpi, block_ref
FROM pg_get_wal_records_info('0/023AD768', '0/023AEC80');
start_lsn | prev_lsn | xid | rmgr | record_type | length | fpi | block_ref
------------+------------+-----+-------------+-------------+--------+------+---------------------------------------------------------------------------------------
0/023AD768 | 0/023AB738 | 783 | Heap | INSERT | 5258 | 5204 | blkref #0: rel 1663/16384/16621 fork main blk 8 (FPW); hole: offset: 44, length: 2988
0/023AEC10 | 0/023AD768 | 783 | Heap | INSERT | 65 | 0 | blkref #0: rel 1663/16384/16621 fork main blk 8
0/023AEC58 | 0/023AEC10 | 783 | Transaction | COMMIT | 34 | 0 |
(3 rows)
Row 61’s record is 5258 bytes, 5204 of them the image; row 62’s record,
for the same page, is 65 bytes with no image. The decision is in
XLogRecordAssemble():
/* Determine if this block needs to be backed up */
if (regbuf->flags & REGBUF_FORCE_IMAGE)
needs_backup = true;
else if (regbuf->flags & REGBUF_NO_IMAGE)
needs_backup = false;
else if (!doPageWrites)
needs_backup = false;
else
{
/*
* We assume page LSN is first data on *every* page that can be
* passed to XLogInsert, whether it has the standard page layout
* or not.
*/
XLogRecPtr page_lsn = PageGetLSN(regbuf->page);
needs_backup = (page_lsn <= RedoRecPtr);
if (!needs_backup)
{
if (!XLogRecPtrIsValid(*fpw_lsn) || page_lsn < *fpw_lsn)
*fpw_lsn = page_lsn;
}
}
/* Determine if the buffer data needs to included */
if (regbuf->rdata_len == 0)
needs_data = false;
else if ((regbuf->flags & REGBUF_KEEP_DATA) != 0)
needs_data = true;
else
needs_data = !needs_backup;
src/backend/access/transam/xloginsert.c, lines 678–708
The test is page_lsn <= RedoRecPtr. Block 8’s pd_lsn was from the
bulk insert, before the redo point 0/023AB660, so row 61 needed
an image. Its record set pd_lsn to its own end, 0/023AEC10, which is
past the redo point, so row 62’s did not. doPageWrites is
full_page_writes, or a base backup running: an online backup turns
full-page writes on even when the setting is off
(xlog.c, line 883).
Note needs_data = !needs_backup: with an image, the tuple itself is
left out of the record, since the image already has it.
The image doesn’t have to be 8 KB. On a page with the standard layout,
the free space between pd_lower and pd_upper is zeros, and it is left
out as a hole:
if (regbuf->flags & REGBUF_STANDARD)
{
/* Assume we can omit data between pd_lower and pd_upper */
uint16 lower = ((const PageHeaderData *) page)->pd_lower;
uint16 upper = ((const PageHeaderData *) page)->pd_upper;
if (lower >= SizeOfPageHeaderData &&
upper > lower &&
upper <= BLCKSZ)
{
bimg.hole_offset = lower;
cbimg.hole_length = upper - lower;
}
else
{
/* No "hole" to remove */
bimg.hole_offset = 0;
cbimg.hole_length = 0;
}
}
src/backend/access/transam/xloginsert.c, lines 737–756
Block 8 after row 61 has five line pointers, so pd_lower = 24 + 5 × 4
= 44, and five 1032-byte tuples, so pd_upper = 8192 − 5160 = 3032. The
hole is 44 to 3032, 2988 bytes, exactly what pg_walinspect printed, and
the image is 8192 − 2988 = 5204 bytes. The record adds up:
- 24 bytes of record header and 4 of block header;
- 5 bytes of image header: the image’s length, the hole’s offset, and
bimg_info0x03 (BKPIMAGE_HAS_HOLE | BKPIMAGE_APPLY); - 12 bytes of
RelFileLocator, 4 of block number, 2 of main-data header; - the 5204-byte image and the 3-byte
xl_heap_insert.
That is 5258. Without the image, row 61’s record would have been 24 + 4 + 12 + 4 + 2 + 5 + (1032 − 23) + 3 = 1063 bytes. This is what full-page writes cost: the first change to each page after a checkpoint logs up to a page instead of a row, which is one reason to keep checkpoints from coming too often.
Two more details of the image, which tinypg reproduces byte for byte
below. Its pd_lsn is still the old one: the page’s LSN is set only
after XLogInsert() returns. And its pd_checksum is 32198, the value
the checkpoint wrote, which no longer fits the page with row 61 on it.
Nothing checks it: the record’s CRC covers the image, and the page
README says redo should not verify an image’s checksum.
If a checkpoint moves the redo pointer while a record is being
assembled, an image may be missing; XLogInsertRecord() checks again
under the insertion lock and has the record assembled anew
(xlog.c, lines 885–896).
A SELECT that writes WAL
Step 3 counts the rows of hints in a new session. Nothing has read them
since they were inserted:
SELECT count(*) FROM hints;
count
-------
10
(1 row)
SELECT start_lsn, prev_lsn, xid, resource_manager AS rmgr, record_type,
record_length AS length, fpi_length AS fpi, block_ref
FROM pg_get_wal_records_info('0/023AECC0', '0/023AEE78');
start_lsn | prev_lsn | xid | rmgr | record_type | length | fpi | block_ref
------------+------------+-----+------+--------------+--------+-----+---------------------------------------------------------------------------------------
0/023AECC0 | 0/023AEC80 | 0 | XLOG | FPI_FOR_HINT | 433 | 384 | blkref #0: rel 1663/16384/16626 fork main blk 0 (FPW); hole: offset: 64, length: 7808
(1 row)
A SELECT, and an XLOG record of type FPI_FOR_HINT with an image of
hints’ only page. (The record before it, at 0/023AEC80, is not from
the scan: pg_walinspect reads only WAL that is flushed, so after each
step the script logs a small message with pg_logical_emit_message(..., flush => true) to flush it.)
A heap tuple’s header records the transaction that inserted it, its
xmin. To decide whether a row is visible, a reader needs to know
whether that transaction committed, which means a lookup in the commit
log. To spare the next reader the lookup, the first one to find the
answer stores it in the tuple as a hint bit, HEAP_XMIN_COMMITTED
(lesson 12 has the visibility rules). A hint isn’t logged in the usual
way: if it is lost, the next reader looks the status up again.
Losing a hint is harmless; tearing the page while writing it is not.
Without checksums, a torn page whose only change is a hint holds old and
new bits, each of them valid. With checksums, the checksum is computed
over the new page, and a page that is half old will fail its check on
the next read. So when checksums are on (or wal_log_hints, see
xlog.h, line 135),
MarkBufferDirtyHint() treats the first hint after the redo point like
a first change, and logs the page whole. In MarkSharedBufferDirtyHint(),
when the buffer wasn’t dirty yet:
UnlockBufHdrExt(bufHdr, buf_state,
BM_DIRTY,
0, 0);
/*
* If the block is already dirty because we either made a change or
* set a hint already, then we don't need to write a full page image.
* Note that aggressive cleaning of blocks dirtied by hint bit setting
* would increase the call rate. Bulk setting of hint bits would
* reduce the call rate...
*/
if (wal_log)
lsn = XLogSaveBufferForHint(buffer, buffer_std);
src/backend/storage/buffer/bufmgr.c, lines 5794–5806
and XLogSaveBufferForHint() makes the same test as before:
RedoRecPtr = GetRedoRecPtr();
/*
* We assume page LSN is first data on *every* page that can be passed to
* XLogInsert, whether it has the standard page layout or not.
*/
lsn = PageGetLSN(BufferGetPage(buffer));
if (lsn <= RedoRecPtr)
{
int flags = 0;
XLogBeginInsert();
if (buffer_std)
flags |= REGBUF_STANDARD;
XLogRegisterBuffer(0, buffer, flags);
recptr = XLogInsert(RM_XLOG_ID, XLOG_FPI_FOR_HINT);
}
return recptr;
src/backend/access/transam/xloginsert.c, lines 1158–1180
The record has no data, just the block reference and its image. Ten
tuples of 32 bytes and ten line pointers make pd_lower 64 and
pd_upper 7872: an image of 8192 − 7808 = 384 bytes, and 24 + 4 + 5 + 12 +
4 + 384 = 433 bytes for the record. The page’s pd_lsn becomes the
record’s end, 0/023AEE78 (line 5824). Had the buffer already been dirty,
the hint would have needed no record: as the page README puts the
argument, the log then already holds an image of the page taken since the
last checkpoint.
The image holds all ten rows with their hint bit set. A sequential scan
in 19 checks a page’s tuples together and sets all their hint bits
before marking the buffer dirty once
(heapam_visibility.c, lines 1717–1718),
and tinypg’s model of the scan does the same.
The checkpoint
Step 4 runs CHECKPOINT with the checkpointer’s counters around it:
SELECT num_requested, buffers_written FROM pg_stat_checkpointer;
num_requested | buffers_written
---------------+-----------------
22 | 1744
(1 row)
CHECKPOINT;
SELECT num_requested, buffers_written FROM pg_stat_checkpointer;
num_requested | buffers_written
---------------+-----------------
23 | 1747
(1 row)
SELECT redo_lsn, checkpoint_lsn, redo_wal_file
FROM pg_control_checkpoint();
redo_lsn | checkpoint_lsn | redo_wal_file
------------+----------------+--------------------------
0/023AEEB8 | 0/023AEF10 | 000000010000000000000002
(1 row)
SELECT start_lsn, prev_lsn, xid, resource_manager AS rmgr, record_type,
record_length AS length, fpi_length AS fpi, block_ref
FROM pg_get_wal_records_info('0/023AEEB8', '0/023AEF90');
start_lsn | prev_lsn | xid | rmgr | record_type | length | fpi | block_ref
------------+------------+-----+---------+-------------------+--------+-----+-----------
0/023AEEB8 | 0/023AEE78 | 0 | XLOG | CHECKPOINT_REDO | 30 | 0 |
0/023AEED8 | 0/023AEEB8 | 0 | Standby | RUNNING_XACTS | 50 | 0 |
0/023AEF10 | 0/023AEED8 | 0 | XLOG | CHECKPOINT_ONLINE | 122 | 0 |
(3 rows)
Three records: CHECKPOINT_REDO, RUNNING_XACTS and
CHECKPOINT_ONLINE, and pg_control now says the redo point is
0/023AEEB8, the start of CHECKPOINT_REDO, and the latest checkpoint is
0/023AEF10, the start of CHECKPOINT_ONLINE. CreateCheckPoint() in
xlog.c goes through these steps.
First the redo record. Its start becomes the new redo point:
/*
* If this is an online checkpoint, we have not yet determined the redo
* point. We do so now by inserting the special XLOG_CHECKPOINT_REDO
* record; the LSN at which it starts becomes the new redo pointer. We
* don't do this for a shutdown checkpoint, because in that case no WAL
* can be written between the redo point and the insertion of the
* checkpoint record itself, so the checkpoint record itself serves to
* mark the redo point.
*/
if (!shutdown)
{
xl_checkpoint_redo redo_rec;
WALInsertLockAcquire();
redo_rec.wal_level = wal_level;
WALInsertLockRelease();
/* Include WAL level in record for WAL summarizer's benefit. */
XLogBeginInsert();
XLogRegisterData(&redo_rec, sizeof(xl_checkpoint_redo));
(void) XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT_REDO);
/*
* XLogInsertRecord will have updated XLogCtl->Insert.RedoRecPtr in
* shared memory and RedoRecPtr in backend-local memory, but we need
* to copy that into the record that will be inserted when the
* checkpoint is complete.
*/
checkPoint.redo = RedoRecPtr;
}
src/backend/access/transam/xlog.c, lines 7210–7239
XLogInsertRecord() handles this record specially: it takes all the
insertion locks, reserves space, and sets the redo pointer to the
record’s start before letting anyone else insert
(xlog.c, lines 926–942).
From that moment, any record that changes a page compares the page’s LSN
with the new redo point, so the first change to each page logs an image
again.
Then CheckPointGuts() (line 7352) writes out the commit log and other
SLRU caches, then the shared buffers, through CheckPointBuffers() and
BufferSync(), then asks the operating system to sync the files
(ProcessSyncRequests(), line 7701). BufferSync() first marks every
dirty buffer of a permanent relation BM_CHECKPOINT_NEEDED, then sorts
them by tablespace, relation, fork and block so each file is written in
order, then writes the marked ones. A buffer dirtied after the marking
isn’t marked, so the checkpoint can’t be kept going forever by new
changes; its changes are after the redo point and in the log. The
CHECKPOINT command asks for a fast checkpoint by default; a checkpoint
triggered by checkpoint_timeout (5 minutes) or by max_wal_size (1 GB)
spreads its writes over checkpoint_completion_target (0.9) of the
interval, sleeping between buffers in CheckpointWriteDelay().
buffers_written went from 1744 to 1747. Two of the three are ours,
ledger’s block 8 and hints’ block 0. The recording doesn’t say which
the third was; a look at the WAL between the checkpoints after the run,
by hand and not recorded, found one more FPI_FOR_HINT, for a page of
the catalog pg_index, so (inferred) that page.
Then, since wal_level is replica, LogStandbySnapshot() logs the
running transactions for standbys (line 7378). Last, the checkpoint
record and the control file:
XLogBeginInsert();
XLogRegisterData(&checkPoint, sizeof(checkPoint));
recptr = XLogInsert(RM_XLOG_ID,
shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
XLOG_CHECKPOINT_ONLINE);
XLogFlush(recptr);
src/backend/access/transam/xlog.c, lines 7385–7391
The record’s main data is the 96-byte CheckPoint struct
(pg_control.h): the redo point, the timeline, full_page_writes, the
next transaction ID and OID, the oldest transaction IDs, and a few more
counters that recovery restarts from. 24 + 2 + 96 = 122 bytes, as
recorded. After the flush, the control file is updated, under
ControlFileLock:
LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
if (shutdown)
ControlFile->state = DB_SHUTDOWNED;
ControlFile->checkPoint = ProcLastRecPtr;
ControlFile->checkPointCopy = checkPoint;
/* crash recovery should always recover to the end of WAL */
ControlFile->minRecoveryPoint = InvalidXLogRecPtr;
ControlFile->minRecoveryPointTLI = 0;
/*
* Persist unloggedLSN value. It's reset on crash recovery, so this goes
* unused on non-shutdown checkpoints, but seems useful to store it always
* for debugging purposes.
*/
ControlFile->unloggedLSN = pg_atomic_read_membarrier_u64(&XLogCtl->unloggedLSN);
UpdateControlFile();
LWLockRelease(ControlFileLock);
src/backend/access/transam/xlog.c, lines 7425–7442
checkPoint is the checkpoint record’s start, and checkPointCopy
holds its contents, redo point included. The order is what makes it
safe: the dirty pages are written and synced first, the checkpoint
record is flushed next, and only then does the control file point at
it. A crash anywhere before that leaves pg_control pointing at the
previous checkpoint, whose redo point is older and still valid.
Last, CreateCheckPoint() removes or recycles WAL segments before the
redo point’s, unless a replication slot, wal_keep_size, WAL
summarization or archiving still needs them
(xlog.c, lines 7487–7502).
That is how the log stops growing.
Here is all of it as tinypg replays it, each step placed where the server’s log had it:
Two WAL pages drawn as bars, records as boxes on them. Step by step: row 61's record with a full-page image, long enough to run from the first page onto the second; row 62's short record; the commit; the FPI_FOR_HINT record a scan of hints logged; the CHECKPOINT_REDO record that becomes the new redo point; the two dirty heap pages written with checksums; and the running-transactions record and the CHECKPOINT_ONLINE record. Under the bars, a line shows how far the log is flushed and a triangle marks the insert position. Below, the fields of the newest record and both heap pages' pd_lsn and, once written, their checksums. (This figure steps through a recorded run; it needs JavaScript.)
The recorded steps as tinypg wrote them, from python3 -m tinypg trace-checkpoint tests/fixtures/pg19_checkpoint.json (tag lesson-07.1,
which corrects lesson-07’s figure: it showed hints’ page as dirty
before the scan).
Grey boxes are records from elsewhere: the script’s flush messages, which
tinypg leaves as gaps, and the server’s running-transactions record,
which tinypg copies from the server’s log. The fields are read back from
tinypg’s bytes. The last line under them is written into the trace, not
checked per frame; the comparison below is what shows the bytes are the
same. The caption for the buffer writes describes tinypg’s pool, which
had only these two pages dirty.
The pages afterwards
Both pages, read from the files after the checkpoint:
SELECT 'ledger' AS rel, 8 AS blkno, lsn, checksum AS pd_checksum,
page_checksum(p, 8) AS computed
FROM pg_read_binary_file(pg_relation_filepath('ledger'), 8 * 8192, 8192) AS p,
page_header(p)
UNION ALL
SELECT 'hints', 0, lsn, checksum, page_checksum(p, 0)
FROM pg_read_binary_file(pg_relation_filepath('hints'), 0, 8192) AS p,
page_header(p);
rel | blkno | lsn | pd_checksum | computed
--------+-------+------------+-------------+----------
ledger | 8 | 0/023AEC58 | -19311 | -19311
hints | 0 | 0/023AEE78 | 7692 | 7692
(2 rows)
ledger’s block 8 has pd_lsn 0/023AEC58, the end of row 62’s record
(the commit record changes no page), and hints’ block 0 has
0/023AEE78, the end of its FPI_FOR_HINT. Both checksums are new, and
both check out.
tinypg: images, hints and checkpoints
assemble() in wal.py gained the image:
for b in blocks:
flags = b.fork
if b.will_init:
flags |= BKPBLOCK_WILL_INIT
image = None
if b.page is not None and full_page_writes and not b.will_init:
if page_lsn(b.page) <= redo_lsn:
image = page_image(b.page, b.standard)
data = b"" if image else b.data
if image:
flags |= BKPBLOCK_HAS_IMAGE
if data:
flags |= BKPBLOCK_HAS_DATA
same = prev is not None and prev == b.locator
if same:
flags |= BKPBLOCK_SAME_REL
heads += BLOCK_HEADER.pack(b.id, flags, len(data))
if image:
img, hole_offset, hole_length = image
bimg_info = BKPIMAGE_APPLY | (BKPIMAGE_HAS_HOLE if hole_length else 0)
heads += IMAGE_HEADER.pack(len(img), hole_offset, bimg_info)
payload += img
if not same:
heads += RELFILELOCATOR.pack(*b.locator)
heads += struct.pack("<I", b.block)
payload += data
prev = b.locator
mark_dirty_hint() in bufmgr.py follows MarkSharedBufferDirtyHint():
dirty the buffer, log the page if it hasn’t been logged since the redo
point, and set pd_lsn to the record’s end:
def mark_dirty_hint(self, buf_id, standard=True):
"""MarkBufferDirtyHint(): a change that needn't be logged (a hint
bit), under a share-exclusive lock. If it makes the buffer dirty and
checksums are on, the page may have to be logged whole first
(XLogSaveBufferForHint()), and then pd_lsn is that record's end:
a torn write of a page whose checksum covers the hint would
otherwise be unrepairable."""
from .wal import log_hint
assert self.locks.get(buf_id) in (SHARE_EXCLUSIVE, EXCLUSIVE)
pool, buf = self.pool, self.pool.descs[buf_id]
if buf.state & BM_DIRTY:
return None
buf.state |= BM_DIRTY
pool.stats["dirtied"] += 1
if pool.wal is None or not pool.data_checksums or not buf.state & BM_PERMANENT:
return None
page = Page.over(pool.blocks[buf_id])
logged = log_hint(pool.wal, buf.tag.locator, buf.tag.block, page.data,
fork=buf.tag.fork, standard=standard)
if logged:
page.set_header(lsn=logged[1])
return logged
tinypg/bufmgr.py, lines 487–508
and checkpoint.py has the checkpoint, in the server’s order:
def create_checkpoint(pool, wal, backend, counters, others=()):
"""An online checkpoint. counters is a CheckPoint whose redo field is
ignored: the values tinypg can't know (next xid, OIDs, the time...).
others are records other processes logged after the redo point, as
finished bytes, placed before the checkpoint record as the server
placed them. Returns (redo, checkpoint start, checkpoint end, tags written)."""
redo, _ = wal.insert(assemble(RM_XLOG_ID, XLOG_CHECKPOINT_REDO, 0,
main=XL_CHECKPOINT_REDO.pack(counters.wal_level)))
wal.redo_lsn = redo
written = pool.buffer_sync(backend)
for rec in others:
wal.insert_raw(bytearray(rec))
cp = counters._replace(redo=redo)
start, end = wal.insert(assemble(RM_XLOG_ID, XLOG_CHECKPOINT_ONLINE, 0, main=cp.pack()))
wal.flush(end)
wal.control = {"checkPoint": start, "redo": redo, "checkPointCopy": cp}
return redo, start, end, written
tinypg/checkpoint.py, lines 60–76
The comparison replays the recording: the two tables’ files as they were after the first checkpoint, a pool with checksums on, and a log with the first checkpoint’s redo point. Then the transaction, the scan, and the checkpoint, each started where the server’s log had it:
$ python3 -m tinypg compare tests/fixtures/pg19_checkpoint.json
tinypg's log continues the server's at each step; redo point of the first checkpoint 0/023AB660
the transaction:
0/023AD768 Heap INSERT 5258 bytes, image 5204 bytes (hole at 44): the same
0/023AEC10 Heap INSERT 65 bytes: the same
0/023AEC58 Transaction COMMIT 34 bytes: the same
all 5400 bytes from 0/023AD768: the same
the scan of hints:
0/023AECC0 XLOG FPI_FOR_HINT 433 bytes, image 384 bytes (hole at 64): the same
all 440 bytes from 0/023AECC0: the same
the checkpoint:
0/023AEEB8 XLOG CHECKPOINT_REDO 30 bytes: the same
0/023AEED8 Standby RUNNING_XACTS 50 bytes: another process's, copied from the server
0/023AEF10 XLOG CHECKPOINT_ONLINE 122 bytes: the same
all 216 bytes from 0/023AEEB8: the same
redo point: tinypg 0/023AEEB8, pg_control 0/023AEEB8
checkpoint record: tinypg 0/023AEF10, pg_control 0/023AEF10
buffers the checkpoint wrote: ledger block 8, hints block 0
ledger block 8 in the file afterwards: pd_lsn 0/023AEC58, pd_checksum -19311 (checks out); the whole page the same as PostgreSQL's
hints block 0 in the file afterwards: pd_lsn 0/023AEE78, pd_checksum 7692 (checks out); the whole page the same as PostgreSQL's
every record and page the same
Every record tinypg wrote is byte for byte the server’s, including the two images and both CRCs, and so are both pages the checkpoint wrote, checksums included. tinypg leaves out:
- compressed images (
wal_compression),wal_log_hints, and the recheck under the insertion lock (tinypg has one backend); - spreading the writes, balancing them across tablespaces, syncing the files, the SLRU caches, and recycling WAL segments;
- shutdown checkpoints, and restartpoints on a standby;
- most of the control file: tinypg keeps the redo point, the checkpoint’s
position and its contents in a dict, and takes the counters in
CheckPoint(next xid, next OID, the time) from the server’s record, since it has no transaction manager yet.
That dict, the images with their BKPIMAGE_APPLY bit, and the flushed
log are what lesson 8 starts from: find the redo point, read forward,
restore images, and apply the other records to pages whose LSN is older.
Try it yourself
With a PostgreSQL 19 server, pageinspect and pg_walinspect, and the tables from the recording.
Suppose the transaction had inserted row 62, the short one, first. How long would its record have been? Row 62’s tuple is 34 bytes, stored in 40.
Answer
4266 bytes. Row 62 would have been the first change to block 8 since the redo point, so it would carry the image. With four 1032-byte tuples and one of 40,
pd_upper= 8192 − 4168 = 4024; with five line pointers,pd_lower= 44. Hole 3980, image 8192 − 3980 = 4212, and 24 + 4 + 5 + 12 + 4 + 2 + 4212 + 3 = 4266. Row 61’s record would then have had no image, 1063 bytes. Worked out from the code, not recorded.Run
SELECT count(*) FROM hints;again now. What do you expect pg_walinspect to show for it?Answer
Nothing from the scan. The hint bits are already set, in the buffer and in the file, so there is nothing to set, the buffer isn’t dirtied, and no record is logged. tinypg’s
test_checkpoint.pychecks the same (set_xmin_committed()returns 0 the second time and logs nothing); on the server it was not part of the recording.A cluster made with
initdb --no-data-checksumsand the defaultwal_log_hints = off: what would step 3 log?Answer
No
FPI_FOR_HINT.XLogHintBitIsNeeded()is false, soMarkSharedBufferDirtyHint()marks the buffer dirty without logging, and the page’spd_lsnstays where it was. A torn write of that page mixes old and new hint bits, each valid, and there is no checksum to fail. Not recorded: the recording’s cluster has checksums on.Why isn’t the redo point simply the checkpoint record’s own position?
Answer
Because the checkpoint takes time and others keep logging while it writes buffers. A change logged after the redo record may or may not be in the files
BufferSync()writes, so replay must start before it. A change logged before the redo record is in a page that is either in its file already or still dirty whenBufferSync()marks buffers, and then the checkpoint writes it. In the recording onlyRUNNING_XACTScame in between; on a busy server a spread checkpoint can take minutes. A shutdown checkpoint has no redo record: nothing else can log, and the checkpoint record itself marks the redo point (the comment before line 7219 ofxlog.c).
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-07.1
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_checkpoint.json
python3 -m tinypg checksums tests/fixtures/pg19_checkpoint.json
Sources
All PostgreSQL code is quoted from tag
REL_19_0 (commit
5c839a2a08b9), with tabs expanded to four spaces and the common indentation
removed.
src/include/storage/checksum_impl.h,src/include/storage/checksum_block_internal.h: the checksum algorithm and the reasons for its designsrc/backend/storage/page/bufpage.c:PageIsVerified()src/backend/storage/page/README: when checksums are valid, and hint bits and torn pagessrc/backend/access/transam/xloginsert.c:XLogRecordAssemble(),XLogSaveBufferForHint()src/backend/access/transam/xlog.c:XLogInsertRecord(),CreateCheckPoint(),CheckPointGuts()src/backend/storage/buffer/bufmgr.c:BufferSync(),FlushBuffer(),MarkSharedBufferDirtyHint()src/backend/access/heap/heapam_visibility.c: setting hint bits, one at a time and in batchessrc/include/catalog/pg_control.h:CheckPoint, the control filesrc/backend/access/transam/README: full-page writes, and writing hints without WAL recordspageinspect,pg_walinspect,CHECKPOINT- tinypg, tag
lesson-07.1:tinypg/checksum.py,tinypg/checkpoint.py,tinypg/wal.py,tinypg/bufmgr.py,tests/test_checkpoint.py,tests/test_postgres19_checkpoint.py, andtools/record_checkpoint.py, which recorded every psql and shell output above
ls postgres-internals/
Storage
- 01 A table is a file of 8 KB pages draftWhere a table lives on disk, the page header, line pointers, tuples filling from the end, and what a ctid is.
- 02 Inside a tuple: alignment, nulls and varlena draftHow column values are laid out after the header, why column order changes a row's size, and the 1-byte and 4-byte length headers.
- 03 TOAST: values too big for a page draftCompression, out-of-line storage in a TOAST table, and the 2 KB threshold that triggers them.
- 04 The free space map draftThe _fsm fork: a tree of one-byte free-space categories that tells an INSERT which page has room.
Buffers and durability
- 05 Shared buffers: a page cache with pins and locks draftThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
- 06 The write-ahead log: records and LSNs draftWAL record layout, pd_lsn, and the rule that a page may not reach disk before its log does.
- 07 Checkpoints, full-page writes and checksums draftWhat a checkpoint guarantees, why the first change after one logs the whole page, and how pd_checksum is computed.
- 08 Crash recovery: replaying the log plannedStarting from the last checkpoint's redo point and replaying records whose LSN is newer than the page's.
MVCC
- 09 Transaction IDs and the commit log plannedAssigning xids, and pg_xact: two bits of commit status per transaction.
- 10 xmin, xmax and the life of a row version plannedWhat UPDATE and DELETE really write, and following ctid chains to the newest version.
- 11 Snapshots: what a transaction can see plannedxmin, xmax and the in-progress list, and when READ COMMITTED and REPEATABLE READ take them.
- 12 Visibility rules and hint bits plannedHeapTupleSatisfiesMVCC case by case, and why reading a row can write to its page.
- 13 HOT updates and page pruning plannedHeap-only tuples, redirect line pointers, and cleaning a page while reading it.
- 14 VACUUM: removing dead tuples plannedScanning the heap, cleaning indexes, and marking line pointers unused.
- 15 The visibility map plannedThe _vm fork's all-visible and all-frozen bits, and what index-only scans and VACUUM get from them.
- 16 Freezing and transaction ID wraparound plannedWhy 32-bit xids wrap around, what freezing writes, and multixacts.
Indexes
- 17 B-tree pages and the Lehman–Yao tree plannedSpecial space, high keys and right links: a B-tree you can search while it changes.
- 18 B-tree insertion and page splits plannedDescending the tree, choosing a split point, and finishing a split in the parent.
- 19 Deduplication and bottom-up deletion plannedPosting lists for duplicate keys, and deleting old versions before a page has to split.
- 20 Hash indexes plannedBuckets, overflow pages and linear-hashing splits.
- 21 GIN and GiST, briefly plannedAn inverted index and a balanced tree of predicates: what each stores and when each fits.
Queries
- 22 From text to parse tree plannedThe grammar, the raw parse tree, and why parsing needs no catalog.
- 23 Analysis and rewriting plannedResolving names against the catalog, the Query tree, and the rewriter's views and rules.
- 24 The planner: paths and the cost model plannedseq_page_cost, random_page_cost and cpu_tuple_cost, and how the cheapest path wins.
- 25 Statistics and selectivity plannedWhat ANALYZE samples, most common values, histograms, and estimating a WHERE clause.
- 26 Join algorithms and join order plannedNested loop, hash and merge joins, and searching the join orders.
- 27 The executor: Volcano-style iterators plannedPlan nodes that each return one row per call, from a sequential scan up to a sort.
Concurrency and the server
- 28 Locks: heavyweight, row-level and lightweight plannedThe lock manager, row locks stored in xmax, LWLocks and spinlocks, and deadlock detection.
- 29 Processes and shared memory plannedThe postmaster, one backend per connection, the background workers, and what they share.
- 30 Streaming replication plannedShipping WAL to a standby, replaying it there, and replication slots.