man postgres-internals/write-ahead-log
lesson 6 of 30 · Buffers and durability
The write-ahead log: records and LSNs
Lesson 5 left pages changed in shared buffers and written to their files later, whenever a buffer was needed for something else. If the server stops in between, the change is lost; if it stops while an 8 KB page is half written, the file holds half of the old page and half of the new one. Writing every changed page at commit would be slow, since one row can change a heap page, a page of each index, and the free space map, and it wouldn’t help with the second problem: a crash in the middle of those writes would leave some pages new, some old, and one perhaps torn.
PostgreSQL’s answer is a log. Each change to a page in a buffer is also described in a WAL record appended to the write-ahead log, one sequential stream of records for the whole cluster, and the page may not reach its file before that record has reached the log on disk: the log is written ahead of the data. At commit, only the log has to reach disk, written in order, and one write can carry the records of several transactions. The pages follow at leisure, and after a crash the log is replayed over whatever the files hold. That replay is lesson 8; this lesson is about what gets written, where, and in what order.
All psql and shell output below comes from one run of
tools/record_wal.py in the tinypg repository (tag lesson-06) against
PostgreSQL 19.0 on 64-bit ARM macOS with data checksums on, wal_level = replica and 16 MB segments, pasted as the script recorded it. The script asks for UTC, so the commit time below is in UTC.
The experiment
A new table, and one transaction that inserts four rows of 1990 characters each:
CREATE TABLE notes (id int, body text) WITH (autovacuum_enabled = off);
CREATE TABLE
SELECT pg_relation_filepath('notes');
pg_relation_filepath
----------------------
base/16384/16565
(1 row)
SHOW wal_segment_size;
wal_segment_size
------------------
16MB
(1 row)
SELECT timeline_id FROM pg_control_checkpoint();
timeline_id
-------------
1
(1 row)
BEGIN;
INSERT INTO notes SELECT i, repeat(chr(96 + i), 1990)
FROM generate_series(1, 4) AS i;
SELECT pg_current_xact_id() AS xid, pg_current_wal_insert_lsn() AS insert_lsn,
pg_current_wal_flush_lsn() AS flush_lsn;
xid | insert_lsn | flush_lsn
-----+------------+------------
730 | 0/021E6E98 | 0/021E4E60
(1 row)
COMMIT;
SELECT pg_current_wal_insert_lsn() AS insert_lsn, pg_current_wal_flush_lsn() AS flush_lsn;
insert_lsn | flush_lsn
------------+------------
0/021E6EC0 | 0/021E6EC0
(1 row)
Each row is a 2022-byte tuple, under the 2032 bytes above which TOAST
steps in (lesson 3), so four of them fill block 0, and their records
together are more than one 8 KB page of log. A fifth row would need a new
heap page, and before adding one, RecordAndGetPageWithFreeSpace() would
record in the free space map how little room block 0 has left. fsm_set_and_search() marks
the map page dirty with MarkBufferDirtyHint()
(freespace.c line 659),
which with checksums on can log an image of the whole map page. Images are
lesson 7, which records one, so this recording stays on one page.
pg_current_wal_insert_lsn() is where the next record will go, and
pg_current_wal_flush_lsn() how far the log is known to be on disk.
Inside the transaction, after its four inserts, the log had been flushed
to 0/021E4E60, which (the next listing shows) is where the first insert’s
record starts: in this run, none of the transaction’s records had been flushed. After
COMMIT both positions are equal.
Reading the log back
The pg_walinspect extension decodes records between two positions:
SELECT start_lsn, end_lsn, prev_lsn, xid, resource_manager AS rmgr, record_type,
record_length AS length, main_data_length AS main, fpi_length AS fpi,
description
FROM pg_get_wal_records_info('0/021E4E60', '0/021E6EC0');
start_lsn | end_lsn | prev_lsn | xid | rmgr | record_type | length | main | fpi | description
------------+------------+------------+-----+-------------+-------------+--------+------+-----+------------------------------
0/021E4E60 | 0/021E5668 | 0/021E4A18 | 730 | Heap | INSERT+INIT | 2053 | 3 | 0 | off: 1, flags: 0x00
0/021E5668 | 0/021E5E70 | 0/021E4E60 | 730 | Heap | INSERT | 2053 | 3 | 0 | off: 2, flags: 0x00
0/021E5E70 | 0/021E6690 | 0/021E5668 | 730 | Heap | INSERT | 2053 | 3 | 0 | off: 3, flags: 0x00
0/021E6690 | 0/021E6E98 | 0/021E5E70 | 730 | Heap | INSERT | 2053 | 3 | 0 | off: 4, flags: 0x00
0/021E6E98 | 0/021E6EC0 | 0/021E6690 | 730 | Transaction | COMMIT | 34 | 8 | 0 | 2026-12-04 08:55:09.55856+00
(5 rows)
An LSN (log sequence number) such as 0/021E4E60 is a byte position in the
log: a 64-bit number printed as two 32-bit halves in hex. The log doesn’t
start again at zero in each file. Its 16 MB segment files are pieces of
one long byte stream, and the segment number and offset come from the
LSN. Each record has a start, an end, and a prev_lsn: the start of the
record before it, whoever wrote that one. The four inserts are 2053 bytes
each, but each next one starts 2056 bytes later (0/021E5668 −
0/021E4E60 = 0x808), because records start at 8-byte boundaries:
ReserveXLogInsertLocation() rounds the space it reserves up with
MAXALIGN
(xlog.c line 1160).
The commit record is 34 bytes and takes 40.
Inside a record
Every record starts with the same 24-byte header:
typedef struct XLogRecord
{
uint32 xl_tot_len; /* total len of entire record */
TransactionId xl_xid; /* xact id */
XLogRecPtr xl_prev; /* ptr to previous record in log */
uint8 xl_info; /* flag bits, see below */
RmgrId xl_rmid; /* resource manager for this record */
/* 2 bytes of padding here, initialize to zero */
pg_crc32c xl_crc; /* CRC for this record */
/* XLogRecordBlockHeaders and XLogRecordDataHeader follow, no padding */
} XLogRecord;
#define SizeOfXLogRecord (offsetof(XLogRecord, xl_crc) + sizeof(pg_crc32c))
src/include/access/xlogrecord.h, lines 41–55
xl_rmid names the resource manager, the part of PostgreSQL that wrote
the record and knows how to replay it: 10 is Heap, 1 is Transaction
(rmgrlist.h).
The high bits of xl_info are the resource manager’s own: for Heap, 0x00
is an insert and 0x80 adds XLOG_HEAP_INIT_PAGE. After the header, a
record lists the pages it changes as block references, each with a small
header:
typedef struct XLogRecordBlockHeader
{
uint8 id; /* block reference ID */
uint8 fork_flags; /* fork within the relation, and flags */
uint16 data_length; /* number of payload bytes (not including page
* image) */
/* If BKPBLOCK_HAS_IMAGE, an XLogRecordBlockImageHeader struct follows */
/* If BKPBLOCK_SAME_REL is not set, a RelFileLocator follows */
/* BlockNumber follows */
} XLogRecordBlockHeader;
src/include/access/xlogrecord.h, lines 103–113
and then the main data, which belongs to no block. tinypg’s reader
decodes the first record from the bytes the script read out of the
segment file, with pg_read_binary_file():
$ python3 -m tinypg waldump tests/fixtures/pg19_wal.json
8288 bytes of WAL from 0/021E4E60 to 0/021E6EC0, read from the segment file: 5 records
0/021E4E60 Heap INSERT+INIT xid 730 length 2053 prev 0/021E4A18 CRC ok
0/021E5668 Heap INSERT xid 730 length 2053 prev 0/021E4E60 CRC ok
0/021E5E70 Heap INSERT xid 730 length 2053 prev 0/021E5668 CRC ok
continues after the page header at 0/021E6000: xlp_magic 0xD122, xlp_info 0x0001, xlp_pageaddr 0/021E6000, xlp_rem_len 1653
0/021E6690 Heap INSERT xid 730 length 2053 prev 0/021E5E70 CRC ok
0/021E6E98 Transaction COMMIT xid 730 length 34 prev 0/021E6690 CRC ok
the first record, field by field:
xl_tot_len 2053
xl_xid 730
xl_prev 0/021E4A18
xl_info 0x80
xl_rmid 10 (Heap)
xl_crc 0xDE9F9B5A (checks out)
block 0 rel 1663/16384/16565, fork 0, block 0; WILL_INIT|HAS_DATA; 2004 bytes of data
main data xl_heap_insert: offnum 1, flags 0x00
its 2053 bytes:
XLogRecord 05 08 00 00 da 02 00 00 18 4a 1e 02 00 00 00 00 ... (24 bytes)
block 0 header 00 60 d4 07
RelFileLocator 7f 06 00 00 00 40 00 00 b5 40 00 00
BlockNumber 00 00 00 00
main data header ff 03
xl_heap_header 02 00 02 08 18
tuple from t_bits 00 01 00 00 00 28 1f 00 00 61 61 61 61 61 61 61 ... (1999 bytes)
xl_heap_insert 01 00 00
Field by field, the first record:
- the header:
xl_tot_len2053, then xid 730,xl_prev,xl_info0x80,xl_rmid10, two bytes of padding, and the CRC; - block 0’s header,
00 60 d4 07: block id 0; flags 0x60, which isBKPBLOCK_WILL_INIT(0x40) andBKPBLOCK_HAS_DATA(0x20), on fork 0, the main fork; and 0x07d4 = 2004 bytes of data for this block; - the
RelFileLocator: tablespace 1663, database 16384, relfilenode 16565; the last two are the numbers in the file path in the setup output, and 1663 ispg_default, the tablespace thatbase/stands for; - the block number, 0;
ff 03: the main data follows, 3 bytes long. 255 isXLR_BLOCK_ID_DATA_SHORT, a marker in the same position as a block id; longer main data than 255 bytes would get 254 and a 4-byte length;- then the data: block 0’s 2004 bytes, then the 3 bytes of main data.
The headers come first and the data after all of them, the order in
which XLogRecordAssemble() chains them. 24 + 4 + 12 + 4 + 2 + 2004 + 3 =
2053.
What heap_insert logs
The records come from the end of heap_insert(), after the tuple is on
the page and the buffer marked dirty. First the case of a new page:
/*
* If this is the single and first tuple on page, we can reinit the
* page instead of restoring the whole thing. Set flag, and hide
* buffer references from XLogInsert.
*/
if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
{
info |= XLOG_HEAP_INIT_PAGE;
bufflags |= REGBUF_WILL_INIT;
}
src/backend/access/heap/heapam.c, lines 2118–2128
The first row of block 0 is the first and only tuple on its page, so its
record is INSERT+INIT and the block is registered with
REGBUF_WILL_INIT: redo will build the page from nothing, with no need
to read the old one. Then the record itself:
XLogBeginInsert();
XLogRegisterData(&xlrec, SizeOfHeapInsert);
xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
xlhdr.t_infomask = heaptup->t_data->t_infomask;
xlhdr.t_hoff = heaptup->t_data->t_hoff;
/*
* note we mark xlhdr as belonging to buffer; if XLogInsert decides to
* write the whole page to the xlog, we don't need to store
* xl_heap_header in the xlog.
*/
XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
REGBUF_STANDARD | bufflags);
XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
SizeOfHeapHeader);
/* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
(char *) heaptup->t_data + SizeofHeapTupleHeader,
heaptup->t_len - SizeofHeapTupleHeader);
/* filtering by origin on a row level is much more efficient */
XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
if (vmbuffer_modified)
XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
recptr = XLogInsert(RM_HEAP_ID, info);
PageSetLSN(page, recptr);
src/backend/access/heap/heapam.c, lines 2153–2182
The main data is xl_heap_insert, the offset number and a flags byte (3
bytes). Block 0 is the heap page, and its data is an xl_heap_header (5
bytes: t_infomask2, t_infomask, t_hoff) followed by the tuple from
byte 23 on. The rest of the tuple header (xmin, xmax, cid, ctid) isn’t
logged: redo takes xmin from xl_xid, sets the command id to the first
one and the ctid to the record’s block and offset
(heapam_xlog.c lines 481-483). In the dump,
02 00 02 08 18 is two attributes, infomask 0x0802 (HEAP_XMAX_INVALID
and HEAP_HASVARWIDTH, lesson 2) and t_hoff 24; the tuple data starts
with one padding byte up to t_hoff, the int 1, and the 4-byte varlena
header 28 1f 00 00 of the text.
The last line sets pd_lsn. XLogInsert() returns the position just past
the new record, and the page remembers it: the page reflects every change
to it logged up to that point. The page header field’s comment says the same
(bufpage.h line 187).
The CRC
A record’s last defence against a torn or garbled log is xl_crc, a
CRC-32C. XLogRecordAssemble() starts it over everything after the fixed
header:
INIT_CRC32C(rdata_crc);
COMP_CRC32C(rdata_crc, hdr_scratch + SizeOfXLogRecord, hdr_rdt.len - SizeOfXLogRecord);
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
src/backend/access/transam/xloginsert.c, lines 985–988
and XLogInsertRecord() finishes it with the header up to xl_crc, once
it knows xl_prev:
/*
* Now that xl_prev has been filled in, calculate CRC of the record
* header.
*/
rdata_crc = rechdr->xl_crc;
COMP_CRC32C(rdata_crc, rechdr, offsetof(XLogRecord, xl_crc));
FIN_CRC32C(rdata_crc);
rechdr->xl_crc = rdata_crc;
src/backend/access/transam/xlog.c, lines 946–953
Python’s zlib.crc32 uses a different polynomial, so tinypg has its own
table-driven CRC-32C in crc32c.py. In the dump, every record’s CRC
checks out.
WAL pages
The log is written in 8 KB pages, each starting with a header:
typedef struct XLogPageHeaderData
{
uint16 xlp_magic; /* magic value for correctness checks */
uint16 xlp_info; /* flag bits, see below */
TimeLineID xlp_tli; /* TimeLineID of first record on page */
XLogRecPtr xlp_pageaddr; /* XLOG address of this page */
/*
* When there is not enough space on current page for whole record, we
* continue on the next page. xlp_rem_len is the number of bytes
* remaining from a previous page; it tracks xl_tot_len in the initial
* header. Note that the continuation data isn't necessarily aligned.
*/
uint32 xlp_rem_len; /* total len of remaining data for record */
} XLogPageHeaderData;
#define SizeOfXLogShortPHD MAXALIGN(sizeof(XLogPageHeaderData))
src/include/access/xlog_internal.h, lines 37–53
The header is 24 bytes; the first page of each segment file has a longer one, 40 bytes, adding the cluster’s system identifier and the segment and page sizes. A record that doesn’t fit in what is left of a page goes on after the next page’s header, and that header says so:
while (rdata_len > freespace)
{
/*
* Write what fits on this page, and continue on the next page.
*/
Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
memcpy(currpos, rdata_data, freespace);
rdata_data += freespace;
rdata_len -= freespace;
written += freespace;
CurrPos += freespace;
/*
* Get pointer to beginning of next page, and set the xlp_rem_len
* in the page header. Set XLP_FIRST_IS_CONTRECORD.
*
* It's safe to set the contrecord flag and xlp_rem_len without a
* lock on the page. All the other flags were already set when the
* page was initialized, in AdvanceXLInsertBuffer, and we're the
* only backend that needs to set the contrecord flag.
*/
currpos = GetXLogBuffer(CurrPos, tli);
pagehdr = (XLogPageHeader) currpos;
pagehdr->xlp_rem_len = write_len - written;
pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
/* skip over the page header */
if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
{
CurrPos += SizeOfXLogLongPHD;
currpos += SizeOfXLogLongPHD;
}
else
{
CurrPos += SizeOfXLogShortPHD;
currpos += SizeOfXLogShortPHD;
}
freespace = INSERT_FREESPACE(CurrPos);
}
src/backend/access/transam/xlog.c, lines 1299–1337
The third insert started at 0/021E5E70, 0x1E70 = 7792 bytes into its page,
so 400 bytes fit there, and the header of the page at 0/021E6000 has
xlp_info 0x0001 (XLP_FIRST_IS_CONTRECORD) and xlp_rem_len 2053 − 400
= 1653, as the dump shows. Someone reading the log from the start of that
page knows to skip those 1653 bytes, and the padding up to the next 8-byte
boundary, to reach the next record: 24 + 1656 = 0x690 bytes into the page,
where the fourth insert starts.
Two WAL pages drawn as bars, records as boxes on them. Each step adds one record: four heap inserts, the third running from the first page onto the second after its header, then the commit record and a short insert from a second transaction. 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 the heap page's pd_lsn. In the last step the page is written to its file after the log has been flushed past its LSN. (This figure steps through a recorded run; it needs JavaScript.)
The records of the recorded transactions as tinypg wrote them, continuing
the server’s log at the same position, from python3 -m tinypg trace-wal tests/fixtures/pg19_wal.json (tag lesson-06). “earlier” is whatever the
server logged before the transaction; the fields are read back from
tinypg’s bytes, and the last line says whether the server’s bytes for the
record were the same.
Commit
COMMIT writes one more record, Transaction/COMMIT: 34 bytes, of which
the main data is 8, the commit time in microseconds since 2000-01-01. A
transaction that only inserted rows has nothing else to record: no
subtransactions, no files to delete, no cache invalidations. Then:
if ((wrote_xlog && markXidCommitted &&
synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
forceSyncCommit || nrels > 0)
{
XLogFlush(XactLastRecEnd);
src/backend/access/transam/xact.c, lines 1544–1548
With synchronous_commit on, the default, the commit waits for
XLogFlush() to get the log onto disk up to the end of its commit record,
and after that the transaction counts as committed even if the server
crashes the next moment. Everything before the commit record in the log
is flushed with it, which is why the insert records didn’t need flushing
on their own. With synchronous_commit = off the commit returns without
waiting and only tells the WAL writer how far to flush
(XLogSetAsyncXactLSN(),
line 1575):
a crash can then lose a transaction that was reported as committed, but
the database stays consistent. The recording didn’t try that setting.
The commit changed no heap page: block 0’s pd_lsn is still the end of
the fourth insert, 0/021E6E98, which is where the commit record begins.
The rule: log first
The WAL writer process also flushes the log in the background, waking
every wal_writer_delay (200 ms by default). It flushes only completed
pages unless something, such as an asynchronous commit, has asked for
more: XLogBackgroundFlush() rounds its target down to a page boundary
(xlog.c line 3037).
So an uncommitted transaction’s last records can sit unflushed in the WAL
buffers in memory while its pages sit dirty in shared buffers. What if
such a page has to be written? The second part of the recording forces it:
BEGIN;
INSERT INTO notes VALUES (5, 'eeeeeeeeee');
SELECT lsn AS page_lsn, pg_current_wal_flush_lsn() AS flush_lsn
FROM page_header(get_raw_page('notes', 0));
page_lsn | flush_lsn
------------+------------
0/021E6F08 | 0/021E6EC0
(1 row)
SELECT b.bufferid, e.* FROM pg_buffercache b, pg_buffercache_evict(b.bufferid) e
WHERE b.relfilenode = pg_relation_filenode('notes') AND b.relblocknumber = 0;
bufferid | buffer_evicted | buffer_flushed
----------+----------------+----------------
577 | t | t
(1 row)
SELECT pg_current_wal_flush_lsn() AS flush_lsn;
flush_lsn
------------
0/021E6F08
(1 row)
SELECT lsn AS page_lsn_in_file
FROM page_header(pg_read_binary_file(pg_relation_filepath('notes'), 0, 8192));
page_lsn_in_file
------------------
0/021E6F08
(1 row)
COMMIT;
The insert set block 0’s LSN to 0/021E6F08, and the log was flushed only
to 0/021E6EC0, the end of the first transaction’s commit. Evicting the
buffer made PostgreSQL write the page, and before that, flush the log:
afterwards the flush position is 0/021E6F08, and the page in the file
carries that LSN. In FlushBuffer():
recptr = BufferGetLSN(buf);
/*
* Force XLOG flush up to buffer's LSN. This implements the basic WAL
* rule that log updates must hit disk before any of the data-file changes
* they describe do.
*
* However, this rule does not apply to unlogged relations, which will be
* lost after a crash anyway. Most unlogged relation pages do not bear
* LSNs since we never emit WAL records for them, and therefore flushing
* up through the buffer LSN would be useless, but harmless. However,
* some index AMs use LSNs internally to detect concurrent page
* modifications, and therefore unlogged index pages bear "fake" LSNs
* generated by XLogGetFakeLSN. It is unlikely but possible that the fake
* LSN counter could advance past the WAL insertion point; and if it did
* happen, attempting to flush WAL through that location would fail, with
* disastrous system-wide consequences. To make sure that can't happen,
* skip the flush if the buffer isn't permanent.
*/
if (pg_atomic_read_u64(&buf->state) & BM_PERMANENT)
XLogFlush(recptr);
src/backend/storage/buffer/bufmgr.c, lines 4571–4591
That is the whole rule: a page may go to disk only after the log describing
its changes. It holds whether or not the transaction will commit; here the
file now holds a row from a transaction that was still open. After a crash
that row would be on disk with no commit record behind it, and what makes
it invisible is the transaction status that later lessons are about, not
its absence from the file. The rule’s other side is that replay after a
crash can rely on every change in a data file being in the log, in order,
so it can tell from pd_lsn which records a page has already seen
(lesson 8; the reasoning is the source comments’, not traced here).
XLogFlush() may flush further than it is asked to; here the flush
position afterwards was exactly the page’s LSN.
tinypg: wal.py
tinypg/wal.py builds records as XLogRecordAssemble() does (block
headers, locators, the main data header, then the data) and places them
in pages as XLogInsertRecord() and CopyXLogRecordToWAL() do:
def insert(self, rec):
"""XLogInsertRecord(): fill in xl_prev, finish the CRC (the data
after the header first, then the header up to xl_crc), and copy the
record into place, page by page (CopyXLogRecordToWAL()). Returns
(start, end): end is the MAXALIGNed position after the record,
which is what XLogInsert() returns."""
start = self.insert_lsn
struct.pack_into("<Q", rec, 8, self.prev_lsn)
struct.pack_into("<I", rec, CRC_OFFSET,
crc32c(rec[:CRC_OFFSET], crc32c(rec[SIZE_OF_XLOG_RECORD:])))
pos, done = start, 0
while True:
addr = pos - pos % XLOG_BLCKSZ
page = self._page(addr)
n = min(XLOG_BLCKSZ - pos % XLOG_BLCKSZ, len(rec) - done)
page[pos - addr:pos - addr + n] = rec[done:done + n]
done += n
pos += n
if done == len(rec):
break
# continued on the next page: its header says how much is left
nxt = self._page(pos)
info, = struct.unpack_from("<H", nxt, 2)
struct.pack_into("<H", nxt, 2, info | XLP_FIRST_IS_CONTRECORD)
struct.pack_into("<I", nxt, 16, len(rec) - done)
pos += page_header_size(pos, self.seg_size)
end = pos + (maxalign(len(rec)) - len(rec)) # zero padding
self.prev_lsn = start
self.insert_lsn = end
if end % XLOG_BLCKSZ == 0: # the next record starts
self.insert_lsn += page_header_size(end, self.seg_size) # after a header
self.records.append((start, end, bytes(rec)))
if self.trace is not None:
self.trace.append(("insert", start, end))
return start, end
heap_insert()’s part:
def log_heap_insert(wal, locator, blkno, offnum, tup, xid, init_page,
all_visible_cleared=False):
"""heap_insert()'s XLOG part: main data xl_heap_insert, block 0 the heap
page, with xl_heap_header and the tuple after its 23-byte header as the
block's data. The first and only tuple on a page makes it an INIT_PAGE
record: redo builds the page afresh instead of reading it.
(PostgreSQL also registers the visibility map page as block 1 when it
clears a bit there; tinypg has no visibility map.)"""
info = XLOG_HEAP_INSERT | (XLOG_HEAP_INIT_PAGE if init_page else 0)
flags = XLH_INSERT_ALL_VISIBLE_CLEARED if all_visible_cleared else 0
infomask2, infomask, hoff = struct.unpack_from("<HHB", tup, 18)
data = HEAP_HEADER.pack(infomask2, infomask, hoff) + bytes(tup[SIZEOF_HEAP_TUPLE_HEADER:])
rec = assemble(RM_HEAP_ID, info, xid,
[BlockRef(0, tuple(locator), blkno, data, will_init=init_page)],
HEAP_INSERT.pack(offnum, flags))
return wal.insert(rec)
and HeapFile calls it after changing the page, sets pd_lsn, and, when
there is no buffer pool, flushes the log before writing the page itself:
if buf is not None:
self.backend.mark_dirty(buf)
if self.wal is not None:
# XLogInsert(), then PageSetLSN(): pd_lsn is the record's end
init = offnum == 1 and page.max_offset() == 1
_, end = log_heap_insert(self.wal, self.locator, blkno, offnum, tup, xid,
init, all_visible)
page.set_header(lsn=end)
if buf is None:
if self.wal is not None:
self.wal.flush(page.header().lsn) # the log first, then the page
self.write_page(blkno, page)
else:
self.backend.unlock_release(buf)
return blkno, offnum
tinypg/heapfile.py, lines 161–175
With a pool, flush_buffer() from lesson 5 now calls wal.flush() with
the page’s LSN before the write.
The comparison inserts the same rows with the same xid into an empty
tinypg table, its log continuing the server’s at the same position with
the same xl_prev, and takes the commit time from the server’s commit
record, the one value it cannot predict:
$ python3 -m tinypg compare tests/fixtures/pg19_wal.json
transaction 730: 4 rows, then COMMIT; tinypg's log starts at 0/021E4E60, xl_prev 0/021E4A18, as the server's did
0/021E4E60 Heap INSERT+INIT 2053 bytes, ends 0/021E5668: the same
0/021E5668 Heap INSERT 2053 bytes, ends 0/021E5E70: the same
0/021E5E70 Heap INSERT 2053 bytes, ends 0/021E6690: the same
0/021E6690 Heap INSERT 2053 bytes, ends 0/021E6E98: the same
0/021E6E98 Transaction COMMIT 34 bytes, ends 0/021E6EC0: the same
all 8288 bytes from 0/021E4E60 to 0/021E6EC0, page headers and padding included: the same
heap block 0: pd_lsn 0/021E6E98, PostgreSQL's 0/021E6E98; the whole page the same (pd_checksum aside)
transaction 731: one row, 0/021E6EC0 Heap INSERT 70 bytes: the same
page LSN: tinypg 0/021E6F08, PostgreSQL 0/021E6F08
page LSN in the file after it: tinypg 0/021E6F08, PostgreSQL 0/021E6F08
evicting the buffer flushed tinypg's log from 0/021E6EC0 to 0/021E6F08 before writing the page (PostgreSQL's: to 0/021E6F08)
every record the same
All 8288 bytes match, the page header in the middle of the third record
and the zero padding after each record included, and so does the heap page
with its pd_lsn, all but pd_checksum, which the server only sets when
it writes the page. The second transaction’s record is the same too, and
tinypg’s log is flushed to the page’s LSN before the page reaches its
file.
What tinypg leaves out: WAL buffers in shared memory (wal_buffers) and
what happens when they fill; the insertion locks that let backends copy
records into the log at the same time; the WAL writer; group commit;
segment files and their recycling; timelines; full-page images (lesson 7);
wal_compression; the replication origin and top-level xid a record can
carry; the visibility map block that heap_insert() registers when it
clears a page’s all-visible bit; and the extra tuple data logged for
logical decoding.
Try it yourself
With a PostgreSQL 19 server, pg_walinspect, and the table from the
recording.
Row 5 is
(5, 'eeeeeeeeee'). Before looking at the comparison output, work out its record’s length.Answer
70 bytes. The tuple is 23 bytes of header, one byte of padding to
t_hoff24, the 4-byte int, and the text with a 1-byte varlena header (it is short): 24 + 4 + 1 + 10 = 39. The record: 24 (header) + 4 (block header) + 12 (locator) + 4 (block number) + 2 (main data header) + 5 (xl_heap_header) + 39 − 23 = 16 (tuple from byte 23) + 3 (main data) = 70, as the comparison output shows. It starts at 0/021E6EC0 and ends at 0/021E6F08, 72 bytes later: 70 rounded up to a multiple of 8.Why does row 1’s record have
WILL_INITand row 2’s not, and what would redo do differently for them?Answer
Row 1 was the first and only tuple on block 0 after the insert, so
heap_insert()setXLOG_HEAP_INIT_PAGEandREGBUF_WILL_INIT: replay initializes an empty page and adds the tuple, without reading block 0 from the file. Row 2’s replay has to read the page as it is and add its tuple at offset 2. (REGBUF_WILL_INITalso includesREGBUF_NO_IMAGE, so such a block gets no full-page image for redo to restore: there is nothing on the old page worth keeping.)If row 3 had started 8 bytes further into the page, what would
xlp_rem_lenof the next page have been?Answer
1661: 392 bytes would have fit on the first page instead of 400, so 2053 − 392 = 1661 would have been left. Worked out from the code, not recorded.
Run the first transaction again with
SET synchronous_commit = off;beforeCOMMIT. What do you expect the last query to show?Answer
The flush position may be behind the insert position: the commit no longer calls
XLogFlush(), onlyXLogSetAsyncXactLSN(), and the WAL writer flushes the commit record a little later (within aboutwal_writer_delay). Whether you see the gap depends on timing. Not tried in the recording.
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-06
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_wal.json
python3 -m tinypg waldump tests/fixtures/pg19_wal.json
To record your own, run tools/record_wal.py --out DIR with the usual
PGHOST, PGPORT, PGUSER (a superuser) and PGDATABASE. It drops and
recreates the table notes. If another process writes WAL in the middle
of the transaction (the background writer logs the running transactions
now and then), or a checkpoint begins, it tries again.
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/access/xlogrecord.h:XLogRecord, block references and their flags, the main data headersrc/include/access/xlog_internal.h: WAL page headers,XLOG_PAGE_MAGICsrc/backend/access/transam/xloginsert.c:XLogInsert(),XLogRecordAssemble()src/backend/access/transam/xlog.c:XLogInsertRecord(),ReserveXLogInsertLocation(),CopyXLogRecordToWAL(),XLogFlush(),XLogBackgroundFlush()src/backend/access/heap/heapam.c,src/include/access/heapam_xlog.h:heap_insert(),xl_heap_insert,xl_heap_headersrc/backend/access/transam/xact.c:RecordTransactionCommit(),XactLogCommitRecord()src/backend/storage/buffer/bufmgr.c:FlushBuffer()src/backend/access/transam/README: the write-ahead log rules, in the sections on WALpg_walinspect- tinypg, tag
lesson-06:tinypg/wal.py,tinypg/crc32c.py,tinypg/heapfile.py,tests/test_wal.py, andtools/record_wal.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.