man postgres-internals/pages-and-tuples
lesson 1 of 30 · Storage
A table is a file of 8 KB pages
When you run INSERT, where does the row go? Into a file, inside an
8192-byte page, in a numbered slot that indexes and other rows can point at. This lesson follows five rows, then three hundred, into a table on a
PostgreSQL 19.0 server, reads the page they land on with the pageinspect
extension, and reads the C code that put each byte there. Then tinypg gets
the same page in Python, and we compare the two byte for byte.
Every psql and shell output below comes from one run of
tools/record_pg19.py in the tinypg repository (tag lesson-01) against
PostgreSQL 19.0 on 64-bit ARM macOS, with data checksums on, pasted as the
script recorded it; that includes one tinypg inspect run on the server’s
file. The tinypg comparison comes from the same tag, run on the fixture this
run recorded. The two byte-by-byte tables are decoded by
hand from those outputs, and checked against the recorded page.
pageinspect is a contrib extension; it needs a superuser:
CREATE EXTENSION pageinspect;
The table is a file
CREATE TABLE fruit (id int, name text) WITH (autovacuum_enabled = off);
CREATE TABLE
SELECT pg_relation_filepath('fruit');
pg_relation_filepath
----------------------
base/16420/20337
(1 row)
SELECT oid, relfilenode FROM pg_class WHERE relname = 'fruit';
oid | relfilenode
-------+-------------
20337 | 20337
(1 row)
SELECT oid FROM pg_database WHERE datname = current_database();
oid
-------
16420
(1 row)
pg_relation_filepath gives the path relative to the data directory:
base/, then the database’s OID, then the table’s relfilenode. When a
table is created the relfilenode equals its OID, as here. They can drift
apart later: an operation that rewrites the whole table, such as TRUNCATE
or VACUUM FULL, writes a new file with a new relfilenode, and the OID
stays. The path is built by GetRelationPath():
sprintf(rp.str, "base/%u/%u",
dbOid, relNumber);
src/common/relpath.c, lines 172–173
The file exists as soon as the table does, and it is empty:
$ wc -c base/16420/20337
0 base/16420/20337
One row later the table is one page long:
INSERT INTO fruit VALUES (1, 'apple') RETURNING xmin;
xmin
------
847
(1 row)
INSERT 0 1
SELECT pg_relation_size('fruit');
pg_relation_size
------------------
8192
(1 row)
RETURNING xmin shows the ID of the transaction that inserted the row, 847;
it will turn up again inside the page. But look at the file itself:
$ wc -c base/16420/20337
8192 base/16420/20337
$ xxd -a base/16420/20337
00000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................
*
00001ff0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
The file has grown by exactly 8192 bytes, and every one of them is zero.
To add a page, PostgreSQL extends the file with zeros
(smgrzeroextend()
in bufmgr.c, which ends in
mdzeroextend()),
and then builds the real page in a buffer in shared memory. The buffer
reaches the file later, at a checkpoint or when the background writer or a
backend needs the buffer. Until then the row is safe only because the
write-ahead log has it, which is the subject of a later part. We will look at
the file again after a checkpoint.
A table never becomes one huge file: md.c splits it into segments of
RELSEG_SIZE blocks, 1 GB with the default build (SHOW segment_size says
1GB on this server), named 20337, 20337.1, 20337.2, and so on. Other
forks of the same table sit next to it with a suffix: _fsm and _vm will
appear below.
One page, three regions
Every page in the table has the same shape: a 24-byte header, an array of 4-byte line pointers growing up from the header, the tuples growing down from the end, and the free space between the two:
0 24 pd_lower pd_upper 8192
+--------+----------------+---------------+--------------------------+
| header | lp1 lp2 ... -> | free space | <- ... tuple2 tuple1 |
+--------+----------------+---------------+--------------------------+
Index pages also keep a special space at the very end for the index’s own
data; heap pages have none, so pd_special is 8192. page_header decodes
the header of a page that get_raw_page copies out of the buffer:
SELECT * FROM page_header(get_raw_page('fruit', 0));
lsn | checksum | flags | lower | upper | special | pagesize | version | prune_xid
------------+----------+-------+-------+-------+---------+----------+---------+-----------
0/0299DDC0 | 0 | 0 | 28 | 8152 | 8192 | 8192 | 4 | 847
(1 row)
The C struct behind it, in bufpage.h:
typedef struct PageHeaderData
{
/* XXX LSN is member of *any* block, not only page-organized ones */
PageXLogRecPtr pd_lsn; /* LSN: next byte after last byte of xlog
* record for last change to this page */
uint16 pd_checksum; /* checksum */
uint16 pd_flags; /* flag bits, see below */
LocationIndex pd_lower; /* offset to start of free space */
LocationIndex pd_upper; /* offset to end of free space */
LocationIndex pd_special; /* offset to start of special space */
uint16 pd_pagesize_version;
TransactionId pd_prune_xid; /* oldest prunable XID, or zero if none */
ItemIdData pd_linp[FLEXIBLE_ARRAY_MEMBER]; /* line pointer array */
} PageHeaderData;
src/include/storage/bufpage.h, lines 184–197
pd_lsnis the position in the write-ahead log just past the record for the last change to this page. The buffer manager will not write the page to disk until the log has been flushed that far.pd_checksumis 0 because the checksum is only computed when the page is written out.pd_flagsholds hint bits about the whole page, such as “every tuple here is visible to everyone”.pd_lowerandpd_upperare where the free space starts and ends. With one line pointer, lower is 24 + 4 = 28; with one tuple, upper is 8192 − 40 = 8152. Why 40 and not the tuple’s 34 bytes is explained below.pd_specialis where the special space starts, the page size here.pd_pagesize_versionpacks two numbers into oneuint16: the page size (a multiple of 256) in the high bits and the layout version, 4, in the low byte. 8192 + 4 = 8196, whichpage_headershows as two columns.pd_prune_xidis a hint for later cleanup: the oldest transaction that may have left something prunable on the page. In 19,heap_insert()sets it to the inserting transaction, 847 here:
/*
* Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
* is full so that we can set the page all-visible in the VM on the next
* page access.
*
* Setting pd_prune_xid is also handy if the inserting transaction
* eventually aborts making this tuple DEAD and hence available for
* pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
* tuple would never otherwise be pruned until next vacuum is triggered.
*
* Don't set it if we are in bootstrap mode or we are inserting a frozen
* tuple, as there is no further pruning/freezing needed in those cases.
*/
if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
PageSetPrunable(page, xid);
src/backend/access/heap/heapam.c, lines 2084–2098
The raw bytes are the same fields, little-endian, in struct order:
SELECT substr(get_raw_page('fruit', 0), 1, 24) AS header,
substr(get_raw_page('fruit', 0), 25, 4) AS lp1;
header | lp1
----------------------------------------------------+------------
\x00000000c0dd9902000000001c00d81f002004204f030000 | \xd89f4400
(1 row)
00000000 c0dd9902 pd_lsn 0/0299DDC0
0000 pd_checksum 0
0000 pd_flags 0
1c00 pd_lower 0x001c = 28
d81f pd_upper 0x1fd8 = 8152
0020 pd_special 0x2000 = 8192
0420 pd_pagesize_version 0x2004 = 8192 | 4
4f030000 pd_prune_xid 0x034f = 847
One detail: pd_lsn is a single 64-bit value in the struct, but its 32-bit
halves are stored high half first on a little-endian machine, so that the
bytes on disk stay what they were when the field was a pair of 32-bit
integers:
static inline void
PageXLogRecPtrSet(volatile PageXLogRecPtr *ptr, XLogRecPtr lsn)
{
ptr->lsn = (lsn << 32) | (lsn >> 32);
}
src/include/storage/bufpage.h, lines 130–134
Line pointers
Four more rows, each in its own transaction (xids 848 to 851):
INSERT INTO fruit VALUES (2, 'fig');
INSERT INTO fruit VALUES (3, 'banana');
INSERT INTO fruit VALUES (4, 'elderberry');
INSERT INTO fruit VALUES (5, NULL);
heap_page_items lists the line pointers:
SELECT lower, upper, prune_xid FROM page_header(get_raw_page('fruit', 0));
lower | upper | prune_xid
-------+-------+-----------
44 | 8008 | 847
(1 row)
SELECT lp, lp_off, lp_flags, lp_len FROM heap_page_items(get_raw_page('fruit', 0));
lp | lp_off | lp_flags | lp_len
----+--------+----------+--------
1 | 8152 | 1 | 34
2 | 8120 | 1 | 32
3 | 8080 | 1 | 35
4 | 8040 | 1 | 39
5 | 8008 | 1 | 28
(5 rows)
A line pointer is one 32-bit word with three bit fields: where the tuple starts, a 2-bit state, and the tuple’s length.
typedef struct ItemIdData
{
unsigned lp_off:15, /* offset to tuple (from start of page) */
lp_flags:2, /* state of line pointer, see below */
lp_len:15; /* byte length of tuple */
} ItemIdData;
src/include/storage/itemid.h, lines 25–30
On this machine (clang, little-endian) the first field takes the lowest
bits. The first line pointer’s bytes were d89f4400 above: as a
little-endian integer that is 0x00449fd8, so lp_off is the low 15 bits,
0x1fd8 = 8152, lp_flags is the next two bits (15 and 16), 01 = 1, and
lp_len is the top 15 bits,
0x22 = 34. State 1 is LP_NORMAL, a pointer to a tuple. The others,
LP_UNUSED, LP_REDIRECT and LP_DEAD, only appear once rows are updated
and deleted.
Why have line pointers at all, instead of addressing a tuple by its byte
offset? Because the address of a row is (page, line pointer number), not
(page, byte offset). Code that tidies the page can move tuples around inside
it, to squeeze out the holes left by dead ones, and only has to fix the line
pointers. Every index entry and every reference to the row keeps working.
The comment at the top of bufpage.h
(lines 63–69)
gives this reason, and also that it keeps crash recovery simple.
Why fill tuples from the end? Both the line pointer array and the tuples
grow, and neither size is known in advance: a page might hold 291 tiny rows
or a few large ones. Growing toward each other, they share a single free space
in the middle, and the page is full exactly when they would cross. That is
the whole fit test in PageAddItemExtended(), the function that adds an
item to any page:
if (offsetNumber == limit || needshuffle)
lower = phdr->pd_lower + sizeof(ItemIdData);
else
lower = phdr->pd_lower;
alignedSize = MAXALIGN(size);
upper = (int) phdr->pd_upper - (int) alignedSize;
if (lower > upper)
return InvalidOffsetNumber;
src/backend/storage/page/bufpage.c, lines 312–322
and after the item is copied in:
/* copy the item's data onto the page */
memcpy((char *) page + upper, item, size);
/* adjust page header */
phdr->pd_lower = (LocationIndex) lower;
phdr->pd_upper = (LocationIndex) upper;
src/backend/storage/page/bufpage.c, lines 350–355
Alignment
lp_len is the tuple’s real length, but upper moves by MAXALIGN(size),
the length rounded up to the platform’s largest alignment:
$ pg_controldata "$PGDATA" | grep -i alignment
Maximum data alignment: 8
So the 34-byte tuple takes 40 bytes, and every tuple starts at a multiple of 8: 8152, 8120, 8080, 8040, 8008. The lengths 34, 32, 35, 39 and 28 cost 40, 32, 40, 40 and 32 bytes. The padding is there so that, once the header has been read, the code can load an 8-byte column straight from the page without copying it to an aligned address first. Five tuples took 184 bytes of tuple space for 168 bytes of data.
The tuple
SELECT lp, t_xmin, t_xmax, t_field3, t_ctid, t_infomask2, t_infomask,
t_hoff, t_bits, t_data
FROM heap_page_items(get_raw_page('fruit', 0));
lp | t_xmin | t_xmax | t_field3 | t_ctid | t_infomask2 | t_infomask | t_hoff | t_bits | t_data
----+--------+--------+----------+--------+-------------+------------+--------+----------+----------------------------------
1 | 847 | 0 | 0 | (0,1) | 2 | 2050 | 24 | | \x010000000d6170706c65
2 | 848 | 0 | 0 | (0,2) | 2 | 2050 | 24 | | \x0200000009666967
3 | 849 | 0 | 0 | (0,3) | 2 | 2050 | 24 | | \x030000000f62616e616e61
4 | 850 | 0 | 0 | (0,4) | 2 | 2050 | 24 | | \x0400000017656c6465726265727279
5 | 851 | 0 | 0 | (0,5) | 2 | 2049 | 24 | 10000000 | \x05000000
(5 rows)
Each tuple starts with a fixed 23-byte header, HeapTupleHeaderData. Its
first 12 bytes are a union. In a stored row they are these three fields:
typedef struct HeapTupleFields
{
TransactionId t_xmin; /* inserting xact ID */
TransactionId t_xmax; /* deleting or locking xact ID */
union
{
CommandId t_cid; /* inserting or deleting command ID, or both */
TransactionId t_xvac; /* old-style VACUUM FULL xact ID */
} t_field3;
} HeapTupleFields;
src/include/access/htup_details.h, lines 122–132
and then come the rest:
ItemPointerData t_ctid;
/* Fields below here must match MinimalTupleData! */
#define FIELDNO_HEAPTUPLEHEADERDATA_INFOMASK2 2
uint16 t_infomask2; /* number of attributes + various flags */
#define FIELDNO_HEAPTUPLEHEADERDATA_INFOMASK 3
uint16 t_infomask; /* various flag bits, see below */
#define FIELDNO_HEAPTUPLEHEADERDATA_HOFF 4
uint8 t_hoff; /* sizeof header incl. bitmap, padding */
src/include/access/htup_details.h, lines 186–197
Laid out, tuple 1 ((1, 'apple'), at byte 8152) is:
offset bytes field
0 4f030000 t_xmin 847, the inserting transaction
4 00000000 t_xmax 0: nobody has deleted it
8 00000000 t_cid 0: the first command in its transaction
12 0000 0000 0100 t_ctid (0,1): block (two halves), line pointer
18 0200 t_infomask2 2 columns
20 0208 t_infomask 0x0802
22 18 t_hoff 24: the data starts at byte 24
23 00 padding up to t_hoff
24 01000000 id 1, a 4-byte integer
28 0d name 1-byte length header: (6 << 1) | 1
29 6170706c65 "apple"
That is 34 bytes. heap_prepare_insert() fills the transaction fields just
before the tuple goes into the page:
tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
HeapTupleHeaderSetXmin(tup->t_data, xid);
if (options & HEAP_INSERT_FROZEN)
HeapTupleHeaderSetXminFrozen(tup->t_data);
HeapTupleHeaderSetCmin(tup->t_data, cid);
HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
src/backend/access/heap/heapam.c, lines 2246–2254
t_infomask 2050 is 0x0802: HEAP_XMAX_INVALID (0x0800, set by the code
above) and HEAP_HASVARWIDTH (0x0002, the row has a variable-length value):
#define HEAP_HASNULL 0x0001 /* has null attribute(s) */
#define HEAP_HASVARWIDTH 0x0002 /* has variable-width attribute(s) */
#define HEAP_HASEXTERNAL 0x0004 /* has external stored attribute(s) */
src/include/access/htup_details.h, lines 214–216
#define HEAP_XMIN_COMMITTED 0x0100 /* t_xmin committed */
#define HEAP_XMIN_INVALID 0x0200 /* t_xmin invalid/aborted */
#define HEAP_XMIN_FROZEN (HEAP_XMIN_COMMITTED|HEAP_XMIN_INVALID)
#define HEAP_XMAX_COMMITTED 0x0400 /* t_xmax committed */
#define HEAP_XMAX_INVALID 0x0800 /* t_xmax invalid/aborted */
src/include/access/htup_details.h, lines 228–232
The text value’s header is one byte because the value is short. A
variable-length value normally carries a 4-byte length word, but one that
fits in 127 bytes, header included, is stored with a 1-byte header whose low
bit is 1 and whose other seven bits are the total length: 0x0d is
(6 << 1) | 1, six bytes for the header and “apple”. Values with a 1-byte
header are not aligned either, so the text sits right after the integer.
The macro, in varatt.h, is:
#define SET_VARSIZE_1B(PTR,len) \
(((varattrib_1b *) (PTR))->va_header = (((uint8) (len)) << 1) | 0x01)
src/include/varatt.h, lines 254–255
Row 5 has a NULL. t_infomask 2049 is HEAP_XMAX_INVALID plus
HEAP_HASNULL (0x0001); HEAP_HASVARWIDTH is gone because the only text
column is NULL. With HEAP_HASNULL a null bitmap follows the 23-byte header,
one bit per column, 1 for present: t_bits is 10000000, column 1 present,
column 2 null. The bitmap is byte 23, which was padding before, so t_hoff
stays 24 and the data is just the integer, 28 bytes in all. In a table with
more than 8 columns a row with a NULL needs a second bitmap byte, and its
t_hoff becomes MAXALIGN(23 + 2) = 32
(heaptuple.c, lines 1123–1128).
t_ctid is the tuple’s own address. RelationPutHeapTuple() writes it
once PageAddItem has chosen the line pointer:
if (!token)
{
ItemId itemId = PageGetItemId(pageHeader, offnum);
HeapTupleHeader item = (HeapTupleHeader) PageGetItem(pageHeader, itemId);
item->t_ctid = tuple->t_self;
}
src/backend/access/heap/hio.c, lines 76–82
When the row is updated, the old version’s t_ctid will point at the new
version; the MVCC part follows those chains.
ctid: block and line pointer
Now fill the page:
INSERT INTO fruit SELECT i, 'fruit ' || i FROM generate_series(6, 300) AS i;
INSERT 0 295
SELECT pg_relation_size('fruit');
pg_relation_size
------------------
16384
(1 row)
$ ls base/16420/20337*
base/16420/20337
base/16420/20337_fsm
Three hundred rows take two pages. Each new row, 'fruit 6' to
'fruit 300', is 36 to 38 bytes, so 40 with padding, plus 4 for its line
pointer: 44 bytes. Page 0 had 8008 − 44 = 7964 bytes free after the first
five rows, and 7964 is exactly 181 × 44. So page 0 ends up holding
5 + 181 = 186 rows with pd_lower and pd_upper both at 768, not one byte
of free space left, and row 187 starts page 1. A _fsm file, the free
space map, also appeared. That is where PostgreSQL recorded that page 0 had
no room left, before giving up on it and extending the table.
How did the inserts pick their page? Each insert first tries the page the table last inserted into, which the relation remembers. With no remembered page it asks the free space map, and when that knows nothing either:
/*
* If the FSM knows nothing of the rel, try the last page before we give
* up and extend. This avoids one-tuple-per-page syndrome during
* bootstrapping or in a recently-started system.
*/
if (targetBlock == InvalidBlockNumber)
{
BlockNumber nblocks = RelationGetNumberOfBlocks(relation);
if (nblocks > 0)
targetBlock = nblocks - 1;
}
src/backend/access/heap/hio.c, lines 588–599
If the row does not fit on the chosen page, the free space map is updated and asked again, and as a last resort the table grows by a page.
The address of a row version is its ctid, (block number, line pointer
number). It is a hidden column of every table, and it can be used in a
WHERE clause, which EXPLAIN shows as a Tid Scan: the executor reads
that one page and that one line pointer, nothing else.
SELECT ctid, id, name FROM fruit WHERE id IN (1, 2, 185, 186, 187);
ctid | id | name
---------+-----+-----------
(0,1) | 1 | apple
(0,2) | 2 | fig
(0,185) | 185 | fruit 185
(0,186) | 186 | fruit 186
(1,1) | 187 | fruit 187
(5 rows)
SELECT * FROM fruit WHERE ctid = '(1,1)';
id | name
-----+-----------
187 | fruit 187
(1 row)
There is a second limit besides bytes. A page can never have more line pointers than would fit if every tuple were an empty header:
#define MaxHeapTuplesPerPage \
((int) ((BLCKSZ - SizeOfPageHeaderData) / \
(MAXALIGN(SizeofHeapTupleHeader) + sizeof(ItemIdData))))
src/include/access/htup_details.h, lines 769–771
that is (8192 − 24) / (24 + 4) = 291 rows per page, however small.
The same table is in the box below: press run and the query runs in your browser, in PGlite (PostgreSQL 19.0 compiled to WebAssembly), on a database built by the same INSERTs. Its ctids come out the same, because the layout rules are the same. Its xids will differ.
SELECT ctid, id, name FROM fruit WHERE id IN (1, 2, 185, 186, 187);
SELECT * FROM fruit WHERE ctid = '(1,1)';ctid | id | name ---------+-----+----------- (0,1) | 1 | apple (0,2) | 2 | fig (0,185) | 185 | fruit 185 (0,186) | 186 | fruit 186 (1,1) | 187 | fruit 187 (5 rows) id | name -----+----------- 187 | fruit 187 (1 row)
Reading the page changed it
The SELECTs above were the first statements to read the table. Afterwards,
page 0 is no longer as the inserts left it:
SELECT lsn, flags, lower, upper, prune_xid FROM page_header(get_raw_page('fruit', 0));
lsn | flags | lower | upper | prune_xid
------------+-------+-------+-------+-----------
0/029A5360 | 4 | 768 | 768 | 0
(1 row)
SELECT lp, t_infomask FROM heap_page_items(get_raw_page('fruit', 0)) WHERE lp <= 2;
lp | t_infomask
----+------------
1 | 2306
2 | 2306
(2 rows)
$ ls base/16420/20337*
base/16420/20337
base/16420/20337_fsm
base/16420/20337_vm
Three things were written by a read. t_infomask went from 2050 to 2306,
which adds HEAP_XMIN_COMMITTED (0x0100): the reader looked up whether
transaction 847 had committed and cached the answer in the tuple, a hint
bit. pd_prune_xid went back to 0 and pd_flags became 4,
PD_ALL_VISIBLE, and a visibility map fork, _vm, appeared. That is the
plan the heap_insert() comment above describes. Page 0 was full and had
pd_prune_xid set, which is when a read runs page pruning; pruning that
finds every tuple visible to everyone records it in the page and in the
visibility map. That reading rests on the source and on the page before and
after the SELECT; the call itself was not traced. The trigger is in
heap_page_prune_opt():
minfree = Max(minfree, BLCKSZ / 10);
if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
src/backend/access/heap/pruneheap.c, lines 321–323
Page 1, with 3148 bytes free, is above the threshold of BLCKSZ / 10
(819 bytes) and
was left alone (tinypg inspect below shows its pd_prune_xid still set).
Hint bits, pruning and the visibility map each get a lesson in the MVCC
part. For now, this is why the recording script copies the raw pages before
anything reads the table.
On disk, after a checkpoint
$ xxd -l 32 base/16420/20337
00000000: 0000 0000 6053 9a02 7cb3 0400 0003 0003 ....`S..|.......
00000010: 0020 0420 0000 0000 d89f 4400 b89f 4000 . . ......D...@.
$ wc -c base/16420/20337
16384 base/16420/20337
SELECT checksum FROM page_header(get_raw_page('fruit', 0));
checksum
----------
-19588
(1 row)
The bytes are the header again, and now with a checksum: 7cb3 is
0xb37c = 45948. page_header returns the checksum as a signed smallint,
so the same value prints as −19588. In 19, the buffer manager computes it in
place, in the shared buffer, just before writing the page:
/* Update page checksum if desired. */
PageSetChecksum((Page) bufBlock, buf->tag.blockNum);
src/backend/storage/buffer/bufmgr.c, lines 4601–4602
tinypg: the same page in Python
tinypg’s first state, tag lesson-01, is three small modules and no
dependencies: page.py (the page), heaptuple.py (the tuple) and
heapfile.py (a table as a file of pages). It has no shared buffers, no
write-ahead log and no free space map: an insert reads the last page from the
file, adds the tuple, and writes the page back.
The page header and the line pointer are struct formats. < means
little-endian with no padding, which is how the C structs come out on this
platform:
# PageHeaderData. pd_lsn is one uint64 in PostgreSQL 19, but stored as two
# native-endian uint32 halves, high half first (PageXLogRecPtrSet).
# pd_lsn_hi pd_lsn_lo pd_checksum pd_flags pd_lower pd_upper pd_special
# pd_pagesize_version pd_prune_xid
PAGE_HEADER = struct.Struct("<IIHHHHHHI")
SIZE_OF_PAGE_HEADER = PAGE_HEADER.size # 24
# ItemIdData: one uint32 with three bit fields, lowest bits first.
# lp_off:15 lp_flags:2 lp_len:15
ITEM_ID = struct.Struct("<I")
SIZE_OF_ITEM_ID = ITEM_ID.size # 4
LP_UNUSED, LP_NORMAL, LP_REDIRECT, LP_DEAD = 0, 1, 2, 3
def pack_item_id(off, flags, length):
return off | flags << 15 | length << 17
def unpack_item_id(word):
return ItemId(word & 0x7FFF, (word >> 15) & 0x3, word >> 17)
Adding an item is PageAddItemExtended()’s fit test and its two header
updates. tinypg never deletes yet, so it always appends a new line pointer:
def add_item(self, item, max_items=None):
"""PageAddItem() for the case tinypg needs so far: append.
The new line pointer goes at pd_lower, the item just below pd_upper.
Returns the item's offset number. tinypg never deletes, so there are
no unused line pointers to recycle yet.
"""
h = self.header()
offnum = self.max_offset() + 1
if max_items is not None and offnum > max_items:
raise PageFull(f"page already has {max_items} items")
lower = h.lower + SIZE_OF_ITEM_ID
upper = h.upper - maxalign(len(item))
if lower > upper:
raise PageFull(f"{len(item)}-byte item does not fit")
ITEM_ID.pack_into(self.data, h.lower,
pack_item_id(upper, LP_NORMAL, len(item)))
self.data[upper:upper + len(item)] = item
self.set_header(lower=lower, upper=upper)
return offnum
The tuple header is one more struct format, 23 bytes:
# HeapTupleHeaderData, packed as on disk (no padding between fields):
# t_xmin t_xmax t_cid | t_ctid: bi_hi bi_lo ip_posid |
# t_infomask2 t_infomask t_hoff
TUPLE_HEADER = struct.Struct("<IIIHHHHHB")
SIZEOF_HEAP_TUPLE_HEADER = TUPLE_HEADER.size # 23
# t_infomask bits tinypg sets (htup_details.h has the full list)
HEAP_HASNULL = 0x0001 # there is a null bitmap
HEAP_HASVARWIDTH = 0x0002 # some column is variable width
HEAP_XMAX_INVALID = 0x0800 # nobody deleted or locked this tuple
# t_infomask2: the low 11 bits are the number of columns
HEAP_NATTS_MASK = 0x07FF
tinypg/heaptuple.py, lines 13–24
form_tuple does the work of heap_form_tuple() and
heap_prepare_insert() together: encode the columns, compute t_hoff, and
fill the transaction fields. Only int and text columns exist so far, and a
row big enough that PostgreSQL would TOAST it is refused.
def form_tuple(values, types, xmin, cid=0):
"""heap_form_tuple() plus heap_prepare_insert(): a tuple ready to store.
t_ctid is left zero; the page sets it once the tuple has a place.
"""
if len(values) != len(types):
raise ValueError("one value per column")
data, bitmap, infomask = encode_columns(values, types)
hoff = maxalign(SIZEOF_HEAP_TUPLE_HEADER + len(bitmap or b""))
tup = bytearray(hoff + len(data))
TUPLE_HEADER.pack_into(tup, 0, xmin, 0, cid, 0, 0, 0,
len(values) & HEAP_NATTS_MASK,
infomask | HEAP_XMAX_INVALID, hoff)
if bitmap:
tup[SIZEOF_HEAP_TUPLE_HEADER:SIZEOF_HEAP_TUPLE_HEADER + len(bitmap)] = bitmap
tup[hoff:] = data
if len(tup) > TOAST_TUPLE_THRESHOLD:
raise ValueError(f"{len(tup)}-byte tuple would be TOASTed")
return tup
tinypg/heaptuple.py, lines 72–90
The text encoding is the 1-byte and 4-byte varlena headers from above:
elif typ == "text":
raw = value.encode("utf-8")
infomask |= HEAP_HASVARWIDTH
if len(raw) + 1 <= VARATT_SHORT_MAX:
# 1-byte varlena header: (total length << 1) | 1, unaligned
data += bytes([(len(raw) + 1) << 1 | 1]) + raw
else:
# 4-byte varlena header: total length << 2, 4-byte aligned
data += bytes(align(len(data), 4) - len(data))
data += struct.pack("<I", (len(raw) + 4) << 2) + raw
tinypg/heaptuple.py, lines 57–66
And the table: try the last page, else extend the file by one page, then set
t_ctid and pd_prune_xid as RelationPutHeapTuple() and heap_insert() do.
def insert(self, values, xid, cid=0):
"""heap_insert(): store one row, return its ctid (block, offset).
Like PostgreSQL with no free space map to ask, try the last page
and add a new one when the row does not fit there.
"""
tup = form_tuple(values, self.types, xmin=xid, cid=cid)
offnum = None
if self.nblocks() > 0:
blkno = self.nblocks() - 1
page = self.read_page(blkno)
try:
offnum = page.add_item(tup, max_items=MAX_HEAP_TUPLES_PER_PAGE)
except PageFull:
pass
if offnum is None:
blkno, page = self.nblocks(), Page() # extend the file by one page
offnum = page.add_item(tup, max_items=MAX_HEAP_TUPLES_PER_PAGE)
# RelationPutHeapTuple(): the stored tuple's t_ctid is its own TID.
lp = page.item_id(offnum)
set_ctid(memoryview(page.data)[lp.off:lp.off + lp.len], blkno, offnum)
# PostgreSQL 19's heap_insert() sets pd_prune_xid to the oldest
# inserting xid, so a later visit can prune or mark the page.
prune = page.header().prune_xid
if prune == 0 or xid < prune:
page.set_header(prune_xid=xid)
self.write_page(blkno, page)
return blkno, offnum
tinypg/heapfile.py, lines 36–63
The figure below is tinypg replaying the first five INSERTs, with the xids
PostgreSQL gave them. The last line of each frame is PostgreSQL’s
pd_lower and pd_upper after the same INSERT, recorded by the same script
in the same run.
An 8 KB heap page drawn as a bar: the header, line pointers growing to the right, free space, and tuples growing to the left from the end, after each of five inserts. (This figure steps through a recorded run; it needs JavaScript.)
tinypg’s page after each INSERT, from python3 -m tinypg trace tests/fixtures/pg19_fruit.json (tag lesson-01). Arcs go from each line
pointer to its tuple; the numbers under the bar are byte offsets. Not to
scale.
They agree at every step. The full comparison replays all six INSERTs (300
rows) and compares tinypg’s two pages with the two pages get_raw_page
returned, all 16384 bytes:
$ python3 -m tinypg compare tests/fixtures/pg19_fruit.json
6 INSERTs, 300 rows; PostgreSQL wrote 2 pages, tinypg 2
block 0: 186 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000b0129a02, tinypg 0000000000000000; 4 bytes differ
block 1: 114 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000d8329a02, tinypg 0000000000000000; 4 bytes differ
The only bytes that differ are the low half of pd_lsn. tinypg has no
write-ahead log, so it has no log position to record. Everything else is
identical: the rest of the header, all 300 line pointers, every tuple
header, the padding and the zeros in the free space. pd_checksum matches
only because both are 0: the pages were copied from shared buffers before
their first write. The test tests/test_postgres19.py checks the same thing
on every run, and also checks pd_lower and pd_upper after each of the
first five inserts.
It works the other way too: tinypg can read the file the server wrote, checksums, hint bits and all:
$ python3 -m tinypg inspect "$PGDATA/base/16420/20337" --limit 5
block 0: lsn 0/029A5360 checksum 45948 flags 4 lower 768 upper 768 special 8192 pagesize_version 8196 prune_xid 0
lp off len xmin xmax ctid infomask2 infomask hoff row
1 8152 34 847 0 (0,1) 2 2306 24 (1, 'apple')
2 8120 32 848 0 (0,2) 2 2306 24 (2, 'fig')
3 8080 35 849 0 (0,3) 2 2306 24 (3, 'banana')
4 8040 39 850 0 (0,4) 2 2306 24 (4, 'elderberry')
5 8008 28 851 0 (0,5) 2 2305 24 (5, NULL)
... 181 more
block 1: lsn 0/029A32D8 checksum 15777 flags 0 lower 480 upper 3632 special 8192 pagesize_version 8196 prune_xid 852
lp off len xmin xmax ctid infomask2 infomask hoff row
1 8152 38 852 0 (1,1) 2 2306 24 (187, 'fruit 187')
2 8112 38 852 0 (1,2) 2 2306 24 (188, 'fruit 188')
3 8072 38 852 0 (1,3) 2 2306 24 (189, 'fruit 189')
4 8032 38 852 0 (1,4) 2 2306 24 (190, 'fruit 190')
5 7992 38 852 0 (1,5) 2 2306 24 (191, 'fruit 191')
... 109 more
What tinypg leaves out, for now: checksums, the write-ahead log (so
pd_lsn stays 0), shared buffers, the free space map, any type but int and
text, TOAST, and everything that happens after an insert, starting with
reading a row and setting hint bits. Its xids are whatever the caller passes
in. Each of those is a later lesson.
Try it yourself
With a PostgreSQL 19 server and a superuser:
CREATE EXTENSION pageinspect;
CREATE TABLE fruit (id int, name text) WITH (autovacuum_enabled = off);
INSERT INTO fruit VALUES (1, 'apple');
SELECT * FROM page_header(get_raw_page('fruit', 0));
SELECT lp, lp_off, lp_len, t_xmin, t_ctid, t_infomask, t_hoff, t_data
FROM heap_page_items(get_raw_page('fruit', 0));
autovacuum_enabled = off keeps autovacuum from reading the table while you
look at it, since a read can change the page. Things to try:
- Insert a row whose
nameis 200 characters long. Predictlp_lenand the first bytes oft_data(the value no longer fits a 1-byte header), then check. - Create
CREATE TABLE t (a int, b bigint)andCREATE TABLE u (b bigint, a int), insert the same row into both, and comparelp_len. The next lesson explains the difference. - Find the file with
pg_relation_filepath, runCHECKPOINT, and read it withxxdor with tinypg. - Run
SELECT * FROM fruitand look att_infomaskagain.
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-01
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_fruit.json
python3 -m tinypg inspect "$PGDATA/$(psql -Atc "SELECT pg_relation_filepath('fruit')")" --types int,text
To record the fixture and this lesson’s outputs from your own server, run
tools/record_pg19.py --out DIR with the usual PGHOST, PGPORT, PGUSER
and PGDATABASE set. It drops and recreates a table named fruit. Then
regenerate the figure’s trace with:
python3 -m tinypg trace tests/fixtures/pg19_fruit.json > trace.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/bufpage.h: the page layout,PageHeaderData,PageSetPrunablesrc/include/storage/itemid.h:ItemIdDataand the line pointer statessrc/backend/storage/page/bufpage.c:PageInit(),PageAddItemExtended()src/include/access/htup_details.h:HeapTupleHeaderData, the infomask bits,MaxHeapTuplesPerPagesrc/backend/access/common/heaptuple.c:heap_form_tuple()andfill_val(), how columns are encodedsrc/include/varatt.h: varlena headerssrc/backend/access/heap/heapam.c:heap_insert(),heap_prepare_insert()src/backend/access/heap/hio.c:RelationPutHeapTuple(),RelationGetBufferForTuple()src/backend/access/heap/pruneheap.c:heap_page_prune_opt()src/common/relpath.c,src/backend/storage/smgr/md.c: file paths and segmentssrc/backend/storage/buffer/bufmgr.c: extending a relation, checksums on writecontrib/pageinspect/:get_raw_page,page_header,heap_page_items- tinypg at
lesson-01: the code, the fixturetests/fixtures/pg19_fruit.json, andtools/record_pg19.py, which recorded every psql and shell output on this page (the comparison ispython3 -m tinypg compare)
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 plannedThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
- 06 The write-ahead log: records and LSNs plannedWAL 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 plannedWhat 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.